text:
package com.kmwllc.brigade.utils;

import com.kmwllc.brigade.Brigade;
import com.kmwllc.brigade.config.*;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * Represents a Brigade "job" to be run on the Brigade server.  It includes all the config
 * objects which govern execution of the pipeline.
 *

 * Calling exec() will begin execution of the pipeline.  At this point, all the configuration objects
 * are "frozen".  Changes made to them after this point will not be reflected in the pipeline execution.
 * Created by matt on 3/22/17.
 */
public class BrigadeRunner {

  private final BrigadeProperties brigadeProperties;
  private final ConnectorConfig connectorConfig;
  private final WorkflowConfig<StageConfig> workflowConfig;

  /**
   * Convenience invocation of BrigadeRunner which builds from given configurations.  This is how
   * BrigadeRunner is invoked when Brigade is run from the command line.
   *

   * Note that it is not clear whether we are building the configurations from a file or stream and so
   * the following logic is performed for each of propertiesFile, connectorFile, workflowFile:

   *
If there is a file in the filesystem at the path given, build the config object from the file

   *
If not, attempt to build from a stream of a classpath resource at the given path

   *
An exception is thrown otherwise

   *

   * @param propertiesFile Path to properties
   * @param connectorFile Path to connector config
   * @param workflowFile Path to workflow config
   * @return BrigadeRunner instance ready to manipulate programmatically or exec
   * @throws IOException If could not locate one of the paths to config object
   * @throws ConfigException If an error occurs while instantiating a config object
   */
  public static BrigadeRunner init(String propertiesFile, String connectorFile, String workflowFile)
          throws IOException, ConfigException {
    BrigadeProperties bp = null;
    ConnectorConfig cc = null;
    WorkflowConfig<StageConfig> wc = null;
    if (isFile(propertiesFile)) {
      bp = BrigadeProperties.fromFile(propertiesFile);
    } else {
      bp = BrigadeProperties.fromStream(getStream(propertiesFile));
    }
    // bootstrap existing properties
    if (isFile(propertiesFile)) {
      bp = BrigadeProperties.fromFile(propertiesFile, bp);
    } else {
      bp = BrigadeProperties.fromStream(getStream(propertiesFile), bp);
    }

    if (isFile(connectorFile)) {
      cc = ConnectorConfig.fromFile(connectorFile, bp);
    } else {
      cc = ConnectorConfig.fromStream(getStream(connectorFile), bp);
    }

    if (isFile(workflowFile)) {
      wc = WorkflowConfig.fromFile(workflowFile, bp);
    } else {
      wc = WorkflowConfig.fromStream(getStream(workflowFile), bp);
    }

    return new BrigadeRunner(bp, cc, wc);
  }

  public BrigadeRunner(BrigadeProperties brigadeProperties, ConnectorConfig connectorConfig,
                       WorkflowConfig<StageConfig> workflowConfig) {
    this.brigadeProperties = brigadeProperties;
    this.connectorConfig = connectorConfig;
    this.workflowConfig = workflowConfig;
  }

  private static boolean isFile(String fileName) {
    File f = new File(fileName);
    return f.exists();
  }

  private static InputStream getStream(String fileName) {
    InputStream in =  BrigadeRunner.class.getClassLoader().getResourceAsStream(fileName);
    return in;
  }

  /**
   * Begin executing the pipeline based upon configuration objects.  Once this is called, the configuration
   * is "frozen" (ie. config settings cannot be changed programmatically)
   *
   * @throws Exception If an exception occurred while running the pipeline
   */
  public void exec() throws Exception {

    // init the brigade config!
    BrigadeConfig config = new BrigadeConfig();
    config.addConnectorConfig(connectorConfig);
    config.addWorkflowConfig(workflowConfig);
    config.setProps(brigadeProperties);

    // Start up the Brigade Server
    Brigade brigadeServer = Brigade.getInstance();
    brigadeServer.setConfig(config);
    try {
      brigadeServer.start();

      if (brigadeServer.isRunning()) {
        try {
          brigadeServer.startConnector(connectorConfig.getConnectorName());
        } catch (InterruptedException e) {
          e.printStackTrace();
          throw e;
        }

        // TODO: this should do a flush! and then shutdown..
        try {
          brigadeServer.waitForConnector(connectorConfig.getConnectorName());
        } catch (InterruptedException e) {
          e.printStackTrace();
          throw e;
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      brigadeServer.shutdown(false);
      throw e;
    }

    brigadeServer.shutdown(false);

    // System.exit(0);
  }
}


text:
package com.biqasoft.microservice.communicator.interfaceimpl;

import com.biqasoft.microservice.communicator.interfaceimpl.demo.UserAccount;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.springframework.test.context.web.WebAppConfiguration;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * @author Nikita Bakaev, ya@nbakaev.ru
 *         Date: 7/25/2016
 *         All Rights Reserved
 */
@SpringBootTest(classes = StartApplicationTest.class)
@WebAppConfiguration
@Test(suiteName = "microserviceCommunicationInterface")
@ActiveProfiles({"development", "test"})
public class MicroserviceInterfaceImplementationFactoryTest extends AbstractTestNGSpringContextTests {

    @Test(enabled = true)
    public void testCreate() throws Exception {
        Object o = MicroserviceInterface.create(MicroserviceUsersRepository.class);
        Assert.assertNotNull(o, "MicroserviceInterfaceImplementorFactory object is NULL");

        if (o instanceof MicroserviceUsersRepository) {
            UserAccount userAccount = ((MicroserviceUsersRepository) o).returnSingleObject();

            Assert.assertNotNull(userAccount);
            Assert.assertNotNull(userAccount.getId());
        } else {
            Assert.fail(o.toString() + "Not implements interface");
        }
    }

    @Test(enabled = true, description = "assert that we create implementation of interface")
    public void testIsImplementInterface() throws Exception {
        Object o = MicroserviceInterface.create(MicroserviceUsersRepository.class);

        if (!(o instanceof MicroserviceUsersRepository)) {
            Assert.fail("Not implements interface");
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
using Akka.Actor;
using Akka.Event;
using Me20.Contracts;
using System;
using MassTransit;
using Me20.Contracts.Events;
using Akka.DI.Core;

namespace Me20.IdentityActors
{
    public class UsersManagerActor : ReceiveActor
    {
        //private readonly IActorRef usersListActor;

        private ILoggingAdapter Logger { get; set; }

        private readonly ISendEndpointProvider sendEndpointProvider;

        public UsersManagerActor(ISendEndpointProvider sendEndpointProvider)
        {
            Logger = Logging.GetLogger(Context);
            this.sendEndpointProvider = sendEndpointProvider;
            //usersListActor = Context.ActorOf(UsersListActor.Props, Guid.NewGuid().ToString());

            Receive<IUserLoggedInEvent>(msg =>
            {
                //usersListActor.Tell(msg.UserName);
                HandleUserLoggedInMessage(msg);
            },
                msg => msg.IsValid);

            Receive<IHaveUserName>(msg => Context.Child(msg.UserName).Forward(msg));
        }

        private void HandleUserLoggedInMessage(IUserLoggedInEvent msg)
        {
            /*var sendee = */
            CreateUserActorIfNotExists(msg);
            //sendee.Forward(msg);
        }

        private IActorRef CreateUserActorIfNotExists(IUserIdentity userIdentity)
        {

            var actorPath = userIdentity.UserName;
            if (!Context.Child(actorPath).IsNobody())
                return Context.Child(actorPath);
            else
                return Context.ActorOf(Props.Create<UserActor>(() => new UserActor(userIdentity, sendEndpointProvider)), actorPath);
        }
    }
}


text:
package de.tblsoft.solr.pipeline;

import de.tblsoft.solr.pipeline.bean.Document;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.*;

public class ElasticdumpJsonReaderTest {
    @Test
    public void parseJsonLineAsDoc() throws Exception {
        // given
        String jsonLine = "{\"_index\":\"example\",\"_type\":\"doc\",\"_id\":\"123-456-789\",\"_score\":1,\"_source\":{\"title\":\"Hello World!\",\"tags\":[\"tag1\", \"tag2\"],\"weight\":10.5}}";

        // when
        Document doc = ElasticdumpJsonReader.parseJsonLineAsDoc(jsonLine, "$['_source']");

        // then
        assertNotNull(doc);
        assertEquals("example", doc.getFieldValue("_index"));
        assertEquals("doc", doc.getFieldValue("_type"));
        assertEquals("123-456-789", doc.getFieldValue("_id"));
        assertEquals("Hello World!", doc.getFieldValue("title"));
        assertEquals(Arrays.asList("tag1", "tag2"), doc.getFieldValues("tags"));
        assertEquals("10.5", doc.getFieldValue("weight"));
    }

    @Test
    public void parseJsonLineAsDocWithEmptyId() throws Exception {
        // given
        String jsonLine = "{\"_index\":\"example\",\"_type\":\"doc\",\"_score\":1,\"_source\":{\"title\":\"Hello World!\",\"tags\":[\"tag1\", \"tags2\"],\"weight\":10.5}}";

        // when
        Document doc = ElasticdumpJsonReader.parseJsonLineAsDoc(jsonLine, "$['_source']");

        // then
        assertNotNull(doc);
        assertEquals("example", doc.getFieldValue("_index"));
        assertEquals("doc", doc.getFieldValue("_type"));
        assertEquals(null, doc.getFieldValue("_id"));
    }

    @Test
    public void parseJsonLineAsDocWithEmptySource() throws Exception {
        // given
        String jsonLine = "{\"_index\":\"example\",\"_type\":\"doc\",\"_score\":1}";

        // when
        Document doc = ElasticdumpJsonReader.parseJsonLineAsDoc(jsonLine, "$['_source']");

        // then
        assertNotNull(doc);
        assertEquals("example", doc.getFieldValue("_index"));
        assertEquals("doc", doc.getFieldValue("_type"));
        assertEquals(null, doc.getFieldValue("_id"));
        assertEquals(3, doc.getFields().size());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:padding="8dp"
    android:layout_height="match_parent">

    <CheckBox
        android:id="@+id/cb_multi_select"
        android:focusable="false"
        android:clickable="false"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tv_multi_select"
        android:textAppearance="?android:attr/textAppearance"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:tint="@color/colorAccent"
        android:id="@+id/tooltip_multi_select"
        android:layout_weight="1"
        android:visibility="invisible"
        android:scaleType="fitEnd"
        android:layout_gravity="end"
        android:src="@drawable/ic_tooltip"/>

</LinearLayout>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycotaxon 30: 332 (1987)

#### Original name
Xanthoparmelia subsorediata Hale

### Remarks
null


text:
namespace blink {

// When ThreadedInputConnection is used, we want to make sure that FROM_IME
// is set only for OnRequestTextInputStateUpdate() so that we can distinguish
// it from other updates so that we can wait for it safely. So it is false by
// default.
ImeEventGuard::ImeEventGuard(base::WeakPtr<WidgetBase> widget)
    : widget_(std::move(widget)) {
  widget_->OnImeEventGuardStart(this);
}

ImeEventGuard::~ImeEventGuard() {
  if (widget_)
    widget_->OnImeEventGuardFinish(this);
}

}  //  namespace blink


text:
import React from 'react';
import PropTypes from 'prop-types';

import CommonProps from '../../../utils/CommonProps';
import CommonMethods from '../../../utils/CommonMethods';

const ItemDetail = (props) => {
  const { item } = props;
  const price = CommonMethods.parsePrice(item.price);
  const soldCounter = item.sold_quantity || 0;
  return (

            {`${item.condition} - ${soldCounter} vendido${(soldCounter > 1) ? 's' : ''}`}

{item.title}

            {`$ ${price.amount}`}
            {price.cents}

          <button className="button-buy">Comprar</button>

Descripción del producto

        {item.description}

  );
};

ItemDetail.propTypes = {
  item: PropTypes.shape(CommonProps.Item).isRequired,
};

export default ItemDetail;


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="schafm.android.flynxfilter" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:theme="@android:style/Theme.DeviceDefault.Light.DarkActionBar"
        android:label="@string/app_name">
        <activity
            android:name=".FilterActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.NoDisplay" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="http" />
                <data android:host="www.google.com" />
                <data android:pathPattern="/" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SettingsActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Revit.SDK.Samples.EventsMonitor.CS
{
    /// <summary>
    /// The UI to show the events history logs. This class is not the main one just a assistant
    /// in this sample. If you just want to learn how to use Revit events,
    /// please pay more attention to EventManager class.
    /// </summary>
    public partial class EventsInfoWindows : System.Windows.Forms.Form
    {
        #region Class Member Variable
        /// <summary>
        /// An instance of RevitApplicationEvents class
        /// Which prepares the informations which is shown in this UI
        /// </summary>
        private LogManager m_dataBuffer;
        #endregion

        #region Class Constructors
        /// <summary>
        /// Constructor without any argument
        /// </summary>
        public EventsInfoWindows()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Constructor with one argument
        /// </summary>
        /// <param name="dataBuffer">prepare the informations which is shown in this UI</param>
        public EventsInfoWindows(LogManager dataBuffer)
            : this()
        {
            m_dataBuffer = dataBuffer;
            Initialize();
        }
        #endregion

        #region Class Implementation
        /// <summary>
        /// Initialize the DataGridView property
        /// </summary>
        private void Initialize()
        {
            // set dataSource
            appEventsLogDataGridView.AutoGenerateColumns = false;
            appEventsLogDataGridView.DataSource          = m_dataBuffer.EventsLog;
            timeColumn.DataPropertyName                  = "Time";
            eventColumn.DataPropertyName                 = "Event";
            typeColumn.DataPropertyName                  = "Type";
        }
        #endregion

        #region Class Events Handler
        /// <summary>
        /// form closed event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InformationWindows_FormClosed(object sender, FormClosedEventArgs e)
        {
            // when form closed the relevant resource will be set free.
            // Then the instance InfoWindows become invalid, so we set InfoWindows with null.
            ExternalApplication.InfoWindows = null;
        }

        /// <summary>
        /// windows shown event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void applicationEventsInfoWindows_Shown(object sender, EventArgs e)
        {
            // set window's display location
            int left             = Screen.PrimaryScreen.WorkingArea.Right - this.Width - 5;
            int top              = Screen.PrimaryScreen.WorkingArea.Bottom - this.Height;
            Point windowLocation = new Point(left, top);
            this.Location        = windowLocation;
        }

        /// <summary>
        /// Scroll to last line when add new log lines
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void appEventsLogDataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            appEventsLogDataGridView.CurrentCell = appEventsLogDataGridView.Rows[appEventsLogDataGridView.Rows.Count - 1].Cells[0];
        }
        #endregion
    }
}


text:
<?php

namespace app\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use app\models\GacEntityListV;
use app\models\GacEntityListU;

/**
 * This is the model class for table "user".
 *
 * @property integer $id
 * @property string $username
 * @property string $password_hash
 * @property string $password_hash_repeat
 * @property string $firstname
 * @property string $lastname
 * @property string $email
 * @property string $phone
 * @property integer $login_counts
 * @property string $last_login_date
 * @property integer $failed_login_attempts
 * @property string $auth_key
 * @property string $last_password_update_date
 * @property integer $created_at
 * @property integer $created_by
 * @property integer $updated_at
 * @property integer $status
 * @property string $password_reset_token
 * @property integer $institutional_code
 * @property string $password write-only password
 */
class User extends ActiveRecord implements IdentityInterface {

    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 1;

    public $password_hash_repeat;
    public $entity_sector_id;
    public $entity_sub_sector_id;

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'gac_user_u';
    }

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['username', 'institutional_code'], 'required'],
            [['username'], 'unique', 'targetClass' => 'app\models\User', 'targetAttribute' => 'username'],
            [['password_hash', 'password_hash_repeat'], 'required', 'on' => 'create'],
            [['password_hash_repeat'], 'compare', 'compareAttribute' => 'password_hash', 'message' => 'The passwords must match'],
            [['status', 'login_counts', 'failed_login_attempts', 'created_by'], 'integer'],
            [['last_login_date', 'last_password_update_date', 'created_at', 'entity_sector_id', 'entity_sub_sector_id', 'institutional_code', 'updated_at', 'firstname', 'lastname'], 'safe'],
            [['username', 'password_hash', 'phone', 'auth_key', 'password_reset_token'], 'string', 'max' => 255],
            ['institutional_code', 'exist', 'targetClass' => 'app\models\GacEntityListV', 'targetAttribute' => 'InstitutionalCode'],
            [['email'], 'email'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'User ID',
            'username' => 'Username',
            'firstname' => 'Firstname',
            'lastname' => 'Lastname',
            'password_hash' => 'Password',
            'password_hash_repeat' => 'Confirm Password',
            'email' => 'Email',
            'phone' => 'Phone',
            'status' => 'Status',
            'login_counts' => 'Login Counts',
            'last_login_date' => 'Last Login Date',
            'failed_login_attempts' => 'Failed Login Attempts',
            'auth_key' => 'Auth Key',
            'last_password_update_date' => 'Last Password Update Date',
            'created_at' => 'Created At',
            'created_by' => 'Created By',
            'password_reset_token' => 'Password Reset Token',
            'institutional_code' => 'Institution Name',
            'entity_sector_id' => 'Entity Sector',
            'entity_sub_sector_id' => 'Entity Subsector'
        ];
    }

    /** INCLUDE USER LOGIN VALIDATION FUNCTIONS* */

    /**
     * @inheritdoc
     */
    public static function findIdentity($id) {
        return static::findOne($id);
    }

    /**
     * @inheritdoc
     */
    /* modified */
    public static function findIdentityByAccessToken($token, $type = null) {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByUsername($username) {
        return static::findOne(['username' => $username]);
    }

    /**
     * Finds user by password reset token
     *
     * @param  string      $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token) {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
                    'password_reset_token' => $token,
                    'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return boolean
     */
    public static function isPasswordResetTokenValid($token) {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId() {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey() {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey) {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password) {
//        return $this->password === sha1($password);
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password) {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey() {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken() {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken() {
        $this->password_reset_token = null;
    }

    public static function getEntitySectorIdByUserId($id) {
        $model = self::findOne(['id' => $id]);
        $entitySector = GacEntityListV::findOne(['InstitutionalCode' => $model->institutional_code]);
        return $entitySector->SectorID;
    }

    public static function getEntitySubSectorIdByUserId($id) {
        $model = self::findOne(['id' => $id]);
        $entitySubSector = GacEntityListV::findOne(['InstitutionalCode' => $model->institutional_code]);
        return $entitySubSector->SubSectorID;
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getGacEntityListU() {
        return $this->hasOne(GacEntityListU::className(), ['InstitutionalCode' => 'institutional_code']);
    }

    public function getFullName() {
        return $this->firstname . ' ' . $this->lastname;
    }

}


text:
package cz.kamenitxan.jakon.core.dynamic

import cz.kamenitxan.jakon.Circe.ParsedValue
import cz.kamenitxan.jakon.core.configuration.{DeployMode, Settings}
import cz.kamenitxan.jakon.core.database.DBHelper
import cz.kamenitxan.jakon.core.dynamic.PageletInitializer.{MethodArgs, createMethodArgs}
import cz.kamenitxan.jakon.core.dynamic.entity.{AbstractJsonResponse, JsonErrorResponse, JsonFailResponse, ResponseStatus}
import cz.kamenitxan.jakon.logging.Logger
import cz.kamenitxan.jakon.utils.I18nUtil
import cz.kamenitxan.jakon.utils.TypeReferences.*
import cz.kamenitxan.jakon.validation.EntityValidator
import cz.kamenitxan.jakon.webui.entity.Message
import spark.{Request, Response, Spark}

import java.io.{PrintWriter, StringWriter}
import java.lang.reflect.{Field, Method}
import java.sql.Connection
import scala.collection.immutable.Map
import scala.jdk.CollectionConverters.*

/**
 * Created by TPa on 13.04.2020.
 */
object JsonPageletInitializer {
	private val JsonContentType = "application/json"

	def initControllers(controllers: Seq[Class[_]]): Unit = {
		Logger.info("Initializing json pagelets")
		controllers.foreach(c => {
			Logger.debug("Initializing json pagelet: " + c.getSimpleName)
			val controllerAnn = c.getAnnotation(classOf[JsonPagelet])

			c.getDeclaredMethods
			  .filter(m => m.getAnnotation(classOf[Get]) != null || m.getAnnotation(classOf[Post]) != null)
			  .foreach(m => {
					val get = m.getAnnotation(classOf[Get])
					val post = m.getAnnotation(classOf[Post])
					if (get != null) {
					  initGetAnnotation(get, controllerAnn, m, c)
					}
					if (post != null) {
					  initPostAnnotation(post, controllerAnn, m, c)
					}
				})
		})

		Logger.info("Json pagelet initialization complete")
	}

	private def initGetAnnotation(get: Get, controllerAnn: JsonPagelet, m: Method, c: Class[_]): Unit = {
		Spark.get(controllerAnn.path() + get.path(), (req: Request, res: Response) => {
			res.raw().setContentType(JsonContentType)
			val pagelet = c.getDeclaredConstructor().newInstance().asInstanceOf[AbstractJsonPagelet]
			val response: String = DBHelper.withDbConnection(implicit conn => {
				val methodArgs = createMethodArgs(m, req, res, conn, pagelet)
				try {
					val responseData = m.invoke(pagelet, methodArgs.array: _*)
					createResponse(responseData, pagelet)
				} catch {
					case ex: Exception =>
						Logger.error(s"${pagelet.getClass.getCanonicalName}.${m.getName}() threw exception", ex)
						createErrorResponse(ex, res, pagelet)
				}
			})
			response
		})
	}

	private def initPostAnnotation(post: Post, controllerAnn: JsonPagelet, m: Method, c: Class[_]): Unit = {
		Spark.post(controllerAnn.path() + post.path(), (req: Request, res: Response) => {
			res.raw().setContentType(JsonContentType)
			val controller = c.getDeclaredConstructor().newInstance().asInstanceOf[AbstractJsonPagelet]
				var methodArgs: (PageletInitializer.MethodArgs, Option[Connection]) = null
				try {
					val dataClass = PageletInitializer.getDataClass(m)
					if (post.validate() && dataClass.isDefined) {
						val jsonData = controller.parseRequestData(req, dataClass.get)
						EntityValidator.validateJson(dataClass.get.getSimpleName, jsonData) match {
							case Left(result) =>
								val translatedErrors = result.map(m => {
									val ut = I18nUtil.getTranslation(Settings.getTemplateDir, "validations", m.text, Settings.getDefaultLocale)
									val t = if (ut == m.text) {
										I18nUtil.getTranslation("templates/admin", "validations", m.text, Settings.getDefaultLocale)
									} else {
										ut
									}
									new Message(m._severity, t, m.params, m.bundle)
								})
								createFailResponse(res, controller, translatedErrors)
							case Right(validatedData) =>
								methodArgs = parseJsonArgs(m, req, res, controller, validatedData)
								val methodArgsArray = methodArgs._1.array
								val responseData = m.invoke(controller, methodArgsArray: _*)
								createResponse(responseData, controller)
						}
					} else {
						methodArgs = parseJsonArgs(m, req, res, controller)
						val methodArgsArray = methodArgs._1.array
						val responseData = m.invoke(controller, methodArgsArray: _*)
						createResponse(responseData, controller)
					}
				} catch {
					case ex: Exception =>
						Logger.error(s"${controller.getClass.getCanonicalName}.${m.getName}() threw exception", ex)
						createErrorResponse(ex, res, controller)
				} finally {
					if (methodArgs != null && methodArgs._2.isDefined) {
						methodArgs._2.get.close()
					}
				}
		})
	}

	private def createResponse(responseData: AnyRef, controller: AbstractJsonPagelet): String = {
		if (responseData == null) {
			return ""
		}
		val wrap = (data: AnyRef) => {
			val jr = new AbstractJsonResponse(ResponseStatus.success, data) {}
			controller.gson.toJson(jr, classOf[AbstractJsonResponse[AnyRef]])
		}
		responseData match {
			case rd: AbstractJsonResponse[AnyRef] => controller.gson.toJson(rd)
			case rd: String => if (controller.wrapResponse) {
				wrap(rd)
			} else {
				rd
			}
			case rd => if (controller.wrapResponse) {
				wrap(rd)
				} else {
				controller.gson.toJson(rd)
				}
		}
	}

	private def createFailResponse(res: Response, controller: AbstractJsonPagelet, messages: Seq[Message]): String = {
		res.status(400)
		val responseData = new JsonFailResponse(messages.asJava)
		controller.gson.toJson(responseData)
	}

	private def createErrorResponse(ex: Exception, res: Response, controller: AbstractJsonPagelet): String = {
		val msg = if (Settings.getDeployMode != DeployMode.PRODUCTION) {
			val sw = new StringWriter
			val pw = new PrintWriter(sw)
			ex.printStackTrace(pw)
			sw.toString
		} else {
			null
		}
		res.status(500)
		val responseData = new JsonErrorResponse(null, 1, msg)
		controller.gson.toJson(responseData)
	}

	private def parseJsonArgs(m: Method,
														req: Request,
														res: Response,
														controller: AbstractJsonPagelet,
														validatedData: Map[Field, ParsedValue] = Map.empty
													 ): (PageletInitializer.MethodArgs, Option[Connection]) = {
		var dataRef: Any = null
		var conn: Connection = null
		val arr: Array[Any] = m.getParameterTypes.map {
			case REQUEST_CLS => req
			case RESPONSE_CLS => res
			case CONNECTION_CLS =>
				conn = DBHelper.getConnection
				conn
			case t =>
				val data = controller.createDataObject(validatedData, t)
				dataRef = data
				Logger.debug(data.toString)
				data
		}
		(new MethodArgs(arr, dataRef), Option.apply(conn))
	}
}


text:
# JIRA commit acceptance python client for CVS
# Author: istvan.vamosi@midori.hu
# $Id$

import sys
import urlparse
import xmlrpclib

# configure JIRA access
# ("projectKey" can contain multiple comma-separated JIRA project keys like "projectKey = 'TST,ARP'".
# If you specify multiple keys, the commit will be accepted if at least one project listed accepts it.
# Or you can specify "projectKey = '*'" to force using the global commit acceptance settings if you don't
# want to specify any exact project key.)
jiraBaseURL = '<JIRA base URL>'
jiraLogin = '<JIRA user name>'
jiraPassword = '<JIRA password>'
projectKey = '<JIRA project key>'

# get committer passed as arg[1]
committer = sys.argv[1]

# slurp log message from log message file passed as arg[2]
try:
	f = open(sys.argv[2])
	commitMessage = f.read()
	f.close()
	commitMessage = commitMessage.rstrip('\n\r')
except:
	print 'Unable to open ' + sys.argv[2] + '.'
	sys.exit(1)

# print arguments
print 'Committer: ' + committer
print 'Commit message: "' + commitMessage + '"'

# invoke JIRA web service
xmlrpcUrl = jiraBaseURL + '/rpc/xmlrpc'
try:
	s = xmlrpclib.ServerProxy(xmlrpcUrl)
	acceptance, comment = s.commitacc.acceptCommit(jiraLogin, jiraPassword, committer, projectKey, commitMessage).split('|');
except:
	acceptance, comment = ['false', 'Unable to connect to the JIRA server at "' + jiraBaseURL + '".']

if acceptance == 'true':
	print 'Commit accepted.'
	sys.exit(0)
else:
	print 'Commit rejected: ' + comment
	sys.exit(1)


text:
<?php
namespace Monitor\Model;
/**
 * Class definition for DataTable
 *
 * @author      Tom Sartain <tomsartain@gmail.com>
 */
class DataTable
{
    protected $title = '';

    protected $data = array();

    public function __construct($title = '') {
        $this->setTitle($title);
    }

    public function setTitle($title) {
        $this->title = $title;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function addData($label, $value) {
        $this->data[$label] = $value;
    }

    public function getData() {
        return $this->data;
    }
}


text:
require 'spec_helper'

describe EmberRouteUrlHelpers, fixtures: false do

  let :helper do
    helper_class = Class.new do
      include Rails.application.routes.url_helpers
    end
    helper_class.default_url_options = default_url_options
    helper_class.new
  end

  def default_url_options
    {
      host: 'example.com',
      port: 3456,
    }
  end

  it "returns the expected urls" do
    expect(helper.root_url).to eq "http://example.com:3456/"

    expect( helper.organization_member_url        'raceteam', '1'                                ).to eq 'http://example.com:3456/raceteam/members/1'
    expect( helper.organization_members_url       'raceteam'                                     ).to eq 'http://example.com:3456/raceteam/members'
    expect( helper.add_organization_member_url    'raceteam'                                     ).to eq 'http://example.com:3456/raceteam/members/add'
    expect( helper.group_member_url               'raceteam', 'electronics', '1'                 ).to eq 'http://example.com:3456/raceteam/electronics/members/1'
    expect( helper.group_members_url              'raceteam', 'electronics'                      ).to eq 'http://example.com:3456/raceteam/electronics/members'
    expect( helper.conversation_url               'raceteam', 'electronics', 'who-ate-my-cheese' ).to eq 'http://example.com:3456/raceteam/electronics/conversations/who-ate-my-cheese'
    expect( helper.compose_conversation_url       'raceteam', 'electronics'                      ).to eq 'http://example.com:3456/raceteam/electronics/conversations/compose'
    expect( helper.conversations_url              'raceteam', 'electronics'                      ).to eq 'http://example.com:3456/raceteam/electronics/conversations'
    expect( helper.muted_conversation_url         'raceteam', 'electronics', 'who-ate-my-cheese' ).to eq 'http://example.com:3456/raceteam/electronics/muted-conversations/who-ate-my-cheese'
    expect( helper.compose_muted_conversation_url 'raceteam', 'electronics'                      ).to eq 'http://example.com:3456/raceteam/electronics/muted-conversations/compose'
    expect( helper.muted_conversations_url        'raceteam', 'electronics'                      ).to eq 'http://example.com:3456/raceteam/electronics/muted-conversations'
    expect( helper.task_url                       'raceteam', 'electronics', 'who-ate-my-cheese' ).to eq 'http://example.com:3456/raceteam/electronics/tasks/who-ate-my-cheese'
    expect( helper.compose_task_url               'raceteam', 'electronics'                      ).to eq 'http://example.com:3456/raceteam/electronics/tasks/compose'
    expect( helper.tasks_url                      'raceteam', 'electronics'                      ).to eq 'http://example.com:3456/raceteam/electronics/tasks'
    expect( helper.doing_task_url                 'raceteam', 'electronics', 'who-ate-my-cheese' ).to eq 'http://example.com:3456/raceteam/electronics/doing-tasks/who-ate-my-cheese'
    expect( helper.compose_doing_task_url         'raceteam', 'electronics'                      ).to eq 'http://example.com:3456/raceteam/electronics/doing-tasks/compose'
    expect( helper.doing_tasks_url                'raceteam', 'electronics'                      ).to eq 'http://example.com:3456/raceteam/electronics/doing-tasks'
    expect( helper.group_url                      'raceteam', 'electronics'                      ).to eq 'http://example.com:3456/raceteam/electronics'
    expect( helper.organization_url               'raceteam'                                     ).to eq 'http://example.com:3456/raceteam'
  end

  it 'url encodes values before generating a path' do
    expect( helper.conversation_url 'raceteam', 'electronics', 'cats->-than-dogs' ).to eq 'http://example.com:3456/raceteam/electronics/conversations/cats-%3E-than-dogs'
  end

end


text:
<!DOCTYPE html>

<title>Shared transitions: element with inline child</title>
<link rel="help" href="https://github.com/WICG/view-transitions">
<link rel="stylesheet" href="/fonts/ahem.css">
<link rel="author" href="mailto:bokan@chromium.org">
<link rel="match" href="content-with-inline-child-ref.html">
<meta name="flags" content="ahem">

  INLINE
BOX


text:
<?php
    $controller = "manage/manage_parameter/1";
    echo form_open($controller)
?>

        Minimum Support

            <input type="text" name="min_sup" id="min_sup" class="input-large" value="<?php echo $min_sup; ?>"/>
            <button type="submit" class="btn btn-primary input-large">Submit</button>

<?php
        echo form_close();
?>


text:
use std::io::{Read, Take, Seek, SeekFrom};
use std::fs::File;

extern crate getopts;

use getopts::Options;
use std::env;

extern crate byteorder;

use byteorder::{LittleEndian, ReadBytesExt};

fn print_usage(cmd: &str, opts: Options) {
    print!("{}", opts.usage(&format!("Usage: {} ARCHIVE [HUNK] [options]", cmd)));
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let cmd = args[0].clone();

    let mut opts = Options::new();
    opts.optflag("h", "help", "print this help menu");
    opts.optflag("l", "list", "list hunks in archive");

    let matches = opts.parse(&args[1..]).unwrap();

    if matches.opt_present("h") || matches.free.is_empty() {
        print_usage(&cmd, opts);
        return;
    }

    let file = File::open(matches.free[0].clone()).unwrap();
    let mut archive = file.into_archive().unwrap();

    if matches.opt_present("l") {
        for entry in archive.entries {
            println!("{}", entry.path);
        }
        return;
    }

    if matches.free.len() == 2 {
        match archive.take_hunk(matches.free[1].clone()).unwrap() {
            Some(take) => {
                take.tee(std::io::stdout()).read_to_end(&mut Vec::new()).unwrap();
            },
            None => {
                println!("No such hunk!");
            }
        }
        return;
    }
    print_usage(&cmd, opts);
}

struct Archive<T: Read> {
    entries: Vec<Entry>,
    offset: u64,
    stream: T,
}

#[derive(Clone, Default, Debug)]
struct Entry {
    path:   String,
    size:   u64,
    offset: u64,
}

trait ArchiveUnpack<T: Read> {
    fn read_entries(&mut self) -> std::io::Result<Vec<Entry>>;
    fn into_archive(mut self) -> std::io::Result<Archive<T>>;
}

impl<T: Read + Seek> ArchiveUnpack<T> for T {
    fn read_entries(&mut self) -> std::io::Result<Vec<Entry>> {
        let count = try!(self.read_u32::<LittleEndian>());

        let mut entries: Vec<Entry> = vec![Entry {
            ..Default::default()
        }; count as usize];

        for entry in entries.iter_mut() {
            let str_len = try!(self.read_u32::<LittleEndian>());

            try!(self.take(str_len as u64).read_to_string(&mut entry.path));

            entry.size = try!(self.read_u64::<LittleEndian>());
            entry.offset = try!(self.read_u64::<LittleEndian>());
        }

        Ok(entries)
    }

    fn into_archive(mut self) -> std::io::Result<Archive<T>> {
        Ok(Archive {
            entries: try!(self.read_entries()),
            offset: try!(self.seek(SeekFrom::Current(0))),
            stream: self,
        })
    }
}

impl<T: Read + Seek> Archive<T> {
    fn take_hunk(&mut self, hunk: String) -> std::io::Result<Option<Take<&mut T>>> {
        match self.entries.iter().find(|&entry| {
            entry.path == hunk
        }) {
            Some(entry) => {
                try!((&mut self.stream).seek(SeekFrom::Start(self.offset + entry.offset as u64)));
                Ok(Some((&mut self.stream).take(entry.size as u64)))
            },
            None => Ok(None)
        }
    }
}


text:
<?php
/*
 * This file is part of the SamlBundle.
 *
 * (c) Paulo Dias <dias.paulo@gmail.com>
 *
 */
namespace PDias\SamlBundle\Twig\Extension;

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

/**
 * Twig extension for saml
 *
 * @package    SamlBundle
 * @subpackage Twig\Extension
 * @author     Paulo Dias <dias.paulo@gmail.com>
 */
class SamlExtension extends \Twig_Extension
{
    protected $router;

    /**
     * @param UrlGeneratorInterface $router
     */
    public function __construct(UrlGeneratorInterface $router)
    {
        $this->router = $router;
    }

    /**
     * @return array
     */
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('samlLoginUrl', [$this, 'getLoginUrl'], ['is_safe' => ['html']]),
            new \Twig_SimpleFunction('samlLogoutUrl', [$this, 'getLogoutUrl'], ['is_safe' => ['html']]),
        ];
    }

    /**
     * @return url
     */
    public function getLoginUrl()
    {
        return $this->router->generate('saml_login_check');
    }

    /**
     * @return url
     */
    public function getLogoutUrl()
    {
        return $this->router->generate('saml_logout');
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'saml_extension';
    }
}


text:
import sys
import os
import json
import django
import datetime
from spotify.secret import *

os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_file)

django.setup()

from spotify.neighbors import *

# from spotify.models import User

start_time = datetime.datetime.now()

all_users = User.objects.all()

users_with_songs = []

for user in all_users:
	songs = UserSong.objects.filter(user=user)
	if len(songs) > 0:
		users_with_songs.append(user)

update_users(users_with_songs)

end_time = datetime.datetime.now()

time_delta = end_time - start_time

current_time = str(end_time)
benchmark = str(time_delta)

x = "Time of update: {0} \nTime to complete: {1}\n".format(current_time,time_delta)

current_directory = os.getcwd()

directory_string = current_directory + "/automatelogfile.txt"

with open(directory_string,'a') as myfile:
	myfile.write(x)


text:
package com.jme3.scene.plugins.blender;

import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Stack;

import com.jme3.animation.Animation;
import com.jme3.animation.Bone;
import com.jme3.animation.Skeleton;
import com.jme3.asset.AssetManager;
import com.jme3.asset.BlenderKey;
import com.jme3.light.Light;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.post.Filter;
import com.jme3.renderer.Camera;
import com.jme3.scene.Node;
import com.jme3.scene.plugins.blender.animations.BlenderAction;
import com.jme3.scene.plugins.blender.animations.BoneContext;
import com.jme3.scene.plugins.blender.constraints.Constraint;
import com.jme3.scene.plugins.blender.file.BlenderInputStream;
import com.jme3.scene.plugins.blender.file.DnaBlockData;
import com.jme3.scene.plugins.blender.file.FileBlockHeader;
import com.jme3.scene.plugins.blender.file.FileBlockHeader.BlockCode;
import com.jme3.scene.plugins.blender.file.Structure;
import com.jme3.scene.plugins.blender.materials.MaterialContext;
import com.jme3.scene.plugins.blender.meshes.TemporalMesh;
import com.jme3.texture.Texture;

/**
 * The class that stores temporary data and manages it during loading the belnd
 * file. This class is intended to be used in a single loading thread. It holds
 * the state of loading operations.
 *
 * @author Marcin Roguski (Kaelthas)
 */
public class BlenderContext {
    /** The blender file version. */
    private int                                    blenderVersion;
    /** The blender key. */
    private BlenderKey                             blenderKey;
    /** The header of the file block. */
    private DnaBlockData                           dnaBlockData;
    /** The scene structure. */
    private Structure                              sceneStructure;
    /** The input stream of the blend file. */
    private BlenderInputStream                     inputStream;
    /** The asset manager. */
    private AssetManager                           assetManager;
    /** The blocks read from the file. */
    protected List<FileBlockHeader>                blocks                 = new ArrayList<FileBlockHeader>();
    /**
     * A map containing the file block headers. The key is the old memory address.
     */
    private Map<Long, FileBlockHeader>             fileBlockHeadersByOma  = new HashMap<Long, FileBlockHeader>();
    /** A map containing the file block headers. The key is the block code. */
    private Map<BlockCode, List<FileBlockHeader>>  fileBlockHeadersByCode = new HashMap<BlockCode, List<FileBlockHeader>>();
    /**
     * This map stores the loaded features by their old memory address. The
     * first object in the value table is the loaded structure and the second -
     * the structure already converted into proper data.
     */
    private Map<Long, Map<LoadedDataType, Object>> loadedFeatures         = new HashMap<Long, Map<LoadedDataType, Object>>();
    /** Features loaded from external blender files. The key is the file path and the value is a map between feature name and loaded feature. */
    private Map<String, Map<String, Object>>       linkedFeatures         = new HashMap<String, Map<String, Object>>();
    /** A stack that hold the parent structure of currently loaded feature. */
    private Stack<Structure>                       parentStack            = new Stack<Structure>();
    /** A list of constraints for the specified object. */
    protected Map<Long, List<Constraint>>          constraints            = new HashMap<Long, List<Constraint>>();
    /** Animations loaded for features. */
    private Map<Long, List<Animation>>             animations             = new HashMap<Long, List<Animation>>();
    /** Loaded skeletons. */
    private Map<Long, Skeleton>                    skeletons              = new HashMap<Long, Skeleton>();
    /** A map between skeleton and node it modifies. */
    private Map<Skeleton, Node>                    nodesWithSkeletons     = new HashMap<Skeleton, Node>();
    /** A map of bone contexts. */
    protected Map<Long, BoneContext>               boneContexts           = new HashMap<Long, BoneContext>();
    /** A map og helpers that perform loading. */
    private Map<String, AbstractBlenderHelper>     helpers                = new HashMap<String, AbstractBlenderHelper>();
    /** Markers used by loading classes to store some custom data. This is made to avoid putting this data into user properties. */
    private Map<String, Map<Object, Object>>       markers                = new HashMap<String, Map<Object, Object>>();
    /** A map of blender actions. The key is the action name and the value is the action itself. */
    private Map<String, BlenderAction>             actions                = new HashMap<String, BlenderAction>();

    /**
     * This method sets the blender file version.
     *
     * @param blenderVersion
     *            the blender file version
     */
    public void setBlenderVersion(String blenderVersion) {
        this.blenderVersion = Integer.parseInt(blenderVersion);
    }

    /**
     * @return the blender file version
     */
    public int getBlenderVersion() {
        return blenderVersion;
    }

    /**
     * This method sets the blender key.
     *
     * @param blenderKey
     *            the blender key
     */
    public void setBlenderKey(BlenderKey blenderKey) {
        this.blenderKey = blenderKey;
    }

    /**
     * This method returns the blender key.
     *
     * @return the blender key
     */
    public BlenderKey getBlenderKey() {
        return blenderKey;
    }

    /**
     * This method sets the dna block data.
     *
     * @param dnaBlockData
     *            the dna block data
     */
    public void setBlockData(DnaBlockData dnaBlockData) {
        this.dnaBlockData = dnaBlockData;
    }

    /**
     * This method returns the dna block data.
     *
     * @return the dna block data
     */
    public DnaBlockData getDnaBlockData() {
        return dnaBlockData;
    }

    /**
     * This method sets the scene structure data.
     *
     * @param sceneStructure
     *            the scene structure data
     */
    public void setSceneStructure(Structure sceneStructure) {
        this.sceneStructure = sceneStructure;
    }

    /**
     * This method returns the scene structure data.
     *
     * @return the scene structure data
     */
    public Structure getSceneStructure() {
        return sceneStructure;
    }

    /**
     * This method returns the asset manager.
     *
     * @return the asset manager
     */
    public AssetManager getAssetManager() {
        return assetManager;
    }

    /**
     * This method sets the asset manager.
     *
     * @param assetManager
     *            the asset manager
     */
    public void setAssetManager(AssetManager assetManager) {
        this.assetManager = assetManager;
    }

    /**
     * This method returns the input stream of the blend file.
     *
     * @return the input stream of the blend file
     */
    public BlenderInputStream getInputStream() {
        return inputStream;
    }

    /**
     * This method sets the input stream of the blend file.
     *
     * @param inputStream
     *            the input stream of the blend file
     */
    public void setInputStream(BlenderInputStream inputStream) {
        this.inputStream = inputStream;
    }

    /**
     * This method adds a file block header to the map. Its old memory address
     * is the key.
     *
     * @param oldMemoryAddress
     *            the address of the block header
     * @param fileBlockHeader
     *            the block header to store
     */
    public void addFileBlockHeader(Long oldMemoryAddress, FileBlockHeader fileBlockHeader) {
        blocks.add(fileBlockHeader);
        fileBlockHeadersByOma.put(oldMemoryAddress, fileBlockHeader);
        List<FileBlockHeader> headers = fileBlockHeadersByCode.get(fileBlockHeader.getCode());
        if (headers == null) {
            headers = new ArrayList<FileBlockHeader>();
            fileBlockHeadersByCode.put(fileBlockHeader.getCode(), headers);
        }
        headers.add(fileBlockHeader);
    }

    /**
     * @return the block headers
     */
    public List<FileBlockHeader> getBlocks() {
        return blocks;
    }

    /**
     * This method returns the block header of a given memory address. If the
     * header is not present then null is returned.
     *
     * @param oldMemoryAddress
     *            the address of the block header
     * @return loaded header or null if it was not yet loaded
     */
    public FileBlockHeader getFileBlock(Long oldMemoryAddress) {
        return fileBlockHeadersByOma.get(oldMemoryAddress);
    }

    /**
     * This method returns a list of file blocks' headers of a specified code.
     *
     * @param code
     *            the code of file blocks
     * @return a list of file blocks' headers of a specified code
     */
    public List<FileBlockHeader> getFileBlocks(BlockCode code) {
        return fileBlockHeadersByCode.get(code);
    }

    /**
     * This method adds a helper instance to the helpers' map.
     *
     * @param <T>
     *            the type of the helper
     * @param clazz
     *            helper's class definition
     * @param helper
     *            the helper instance
     */
    public <T> void putHelper(Class<T> clazz, AbstractBlenderHelper helper) {
        helpers.put(clazz.getSimpleName(), helper);
    }

    @SuppressWarnings("unchecked")
    public <T> T getHelper(Class<?> clazz) {
        return (T) helpers.get(clazz.getSimpleName());
    }

    /**
     * This method adds a loaded feature to the map. The key is its unique old
     * memory address.
     *
     * @param oldMemoryAddress
     *            the address of the feature
     * @param featureName
     *            the name of the feature
     * @param structure
     *            the filled structure of the feature
     * @param feature
     *            the feature we want to store
     */
    public void addLoadedFeatures(Long oldMemoryAddress, LoadedDataType featureDataType, Object feature) {
        if (oldMemoryAddress == null || featureDataType == null || feature == null) {
            throw new IllegalArgumentException("One of the given arguments is null!");
        }
        Map<LoadedDataType, Object> map = loadedFeatures.get(oldMemoryAddress);
        if (map == null) {
            map = new HashMap<BlenderContext.LoadedDataType, Object>();
            loadedFeatures.put(oldMemoryAddress, map);
        }
        map.put(featureDataType, feature);
    }

    /**
     * This method returns the feature of a given memory address. If the feature
     * is not yet loaded then null is returned.
     *
     * @param oldMemoryAddress
     *            the address of the feature
     * @param loadedFeatureDataType
     *            the type of data we want to retreive it can be either filled
     *            structure or already converted feature
     * @return loaded feature or null if it was not yet loaded
     */
    public Object getLoadedFeature(Long oldMemoryAddress, LoadedDataType loadedFeatureDataType) {
        Map<LoadedDataType, Object> result = loadedFeatures.get(oldMemoryAddress);
        if (result != null) {
            return result.get(loadedFeatureDataType);
        }
        return null;
    }

    /**
     * The method adds linked content to the blender context.
     * @param blenderFilePath
     *            the path of linked blender file
     * @param featureGroup
     *            the linked feature group (ie. scenes, materials, meshes, etc.)
     * @param feature
     *            the linked feature
     */
    @Deprecated
    public void addLinkedFeature(String blenderFilePath, String featureGroup, Object feature) {
        // the method is deprecated and empty at the moment
    }

    /**
     * The method returns linked feature of a given name from the specified blender path.
     * @param blenderFilePath
     *            the blender file path
     * @param featureName
     *            the feature name we want to get
     * @return linked feature or null if none was found
     */
    @SuppressWarnings("unchecked")
    public Object getLinkedFeature(String blenderFilePath, String featureName) {
        Map<String, Object> linkedFeatures = this.linkedFeatures.get(blenderFilePath);
        if(linkedFeatures != null) {
            String namePrefix = (featureName.charAt(0) + "" + featureName.charAt(1)).toUpperCase();
            featureName = featureName.substring(2);

            if("SC".equals(namePrefix)) {
                List<Node> scenes = (List<Node>) linkedFeatures.get("scenes");
                if(scenes != null) {
                    for(Node scene : scenes) {
                        if(featureName.equals(scene.getName())) {
                            return scene;
                        }
                    }
                }
            } else if("OB".equals(namePrefix)) {
                List<Node> features = (List<Node>) linkedFeatures.get("objects");
                if(features != null) {
                    for(Node feature : features) {
                        if(featureName.equals(feature.getName())) {
                            return feature;
                        }
                    }
                }
            } else if("ME".equals(namePrefix)) {
                List<TemporalMesh> temporalMeshes = (List<TemporalMesh>) linkedFeatures.get("meshes");
                if(temporalMeshes != null) {
                    for(TemporalMesh temporalMesh : temporalMeshes) {
                        if(featureName.equals(temporalMesh.getName())) {
                            return temporalMesh;
                        }
                    }
                }
            } else if("MA".equals(namePrefix)) {
                List<MaterialContext> features = (List<MaterialContext>) linkedFeatures.get("materials");
                if(features != null) {
                    for(MaterialContext feature : features) {
                        if(featureName.equals(feature.getName())) {
                            return feature;
                        }
                    }
                }
            } else if("TX".equals(namePrefix)) {
                List<Texture> features = (List<Texture>) linkedFeatures.get("textures");
                if(features != null) {
                    for(Texture feature : features) {
                        if(featureName.equals(feature.getName())) {
                            return feature;
                        }
                    }
                }
            } else if("IM".equals(namePrefix)) {
                List<Texture> features = (List<Texture>) linkedFeatures.get("images");
                if(features != null) {
                    for(Texture feature : features) {
                        if(featureName.equals(feature.getName())) {
                            return feature;
                        }
                    }
                }
            } else if("AC".equals(namePrefix)) {
                List<Animation> features = (List<Animation>) linkedFeatures.get("animations");
                if(features != null) {
                    for(Animation feature : features) {
                        if(featureName.equals(feature.getName())) {
                            return feature;
                        }
                    }
                }
            } else if("CA".equals(namePrefix)) {
                List<Camera> features = (List<Camera>) linkedFeatures.get("cameras");
                if(features != null) {
                    for(Camera feature : features) {
                        if(featureName.equals(feature.getName())) {
                            return feature;
                        }
                    }
                }
            } else if("LA".equals(namePrefix)) {
                List<Light> features = (List<Light>) linkedFeatures.get("lights");
                if(features != null) {
                    for(Light feature : features) {
                        if(featureName.equals(feature.getName())) {
                            return feature;
                        }
                    }
                }
            } else if("FI".equals(featureName)) {
                List<Filter> features = (List<Filter>) linkedFeatures.get("lights");
                if(features != null) {
                    for(Filter feature : features) {
                        if(featureName.equals(feature.getName())) {
                            return feature;
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * @return all linked features for the current blend file
     */
    public Map<String, Map<String, Object>> getLinkedFeatures() {
        return linkedFeatures;
    }

    /**
     * This method adds the structure to the parent stack.
     *
     * @param parent
     *            the structure to be added to the stack
     */
    public void pushParent(Structure parent) {
        parentStack.push(parent);
    }

    /**
     * This method removes the structure from the top of the parent's stack.
     *
     * @return the structure that was removed from the stack
     */
    public Structure popParent() {
        try {
            return parentStack.pop();
        } catch (EmptyStackException e) {
            return null;
        }
    }

    /**
     * This method retreives the structure at the top of the parent's stack but
     * does not remove it.
     *
     * @return the structure from the top of the stack
     */
    public Structure peekParent() {
        try {
            return parentStack.peek();
        } catch (EmptyStackException e) {
            return null;
        }
    }

    /**
     * This method adds a new modifier to the list.
     *
     * @param ownerOMA
     *            the owner's old memory address
     * @param constraints
     *            the object's constraints
     */
    public void addConstraints(Long ownerOMA, List<Constraint> constraints) {
        List<Constraint> objectConstraints = this.constraints.get(ownerOMA);
        if (objectConstraints == null) {
            objectConstraints = new ArrayList<Constraint>();
            this.constraints.put(ownerOMA, objectConstraints);
        }
        objectConstraints.addAll(constraints);
    }

    /**
     * Returns constraints applied to the feature of the given OMA.
     * @param ownerOMA
     *            the constraints' owner OMA
     * @return a list of constraints or <b>null</b> if no constraints are applied to the feature
     */
    public List<Constraint> getConstraints(Long ownerOMA) {
        return constraints.get(ownerOMA);
    }

    /**
     * @return all available constraints
     */
    public List<Constraint> getAllConstraints() {
        List<Constraint> result = new ArrayList<Constraint>();
        for (Entry<Long, List<Constraint>> entry : constraints.entrySet()) {
            result.addAll(entry.getValue());
        }
        return result;
    }

    /**
     * This method adds the animation for the specified OMA of its owner.
     *
     * @param ownerOMA
     *            the owner's old memory address
     * @param animation
     *            the animation for the feature specified by ownerOMA
     */
    public void addAnimation(Long ownerOMA, Animation animation) {
        List<Animation> animList = animations.get(ownerOMA);
        if (animList == null) {
            animList = new ArrayList<Animation>();
            animations.put(ownerOMA, animList);
        }
        animList.add(animation);
    }

    /**
     * This method returns the animation data for the specified owner.
     *
     * @param ownerOMA
     *            the old memory address of the animation data owner
     * @return the animation or null if none exists
     */
    public List<Animation> getAnimations(Long ownerOMA) {
        return animations.get(ownerOMA);
    }

    /**
     * This method sets the skeleton for the specified OMA of its owner.
     *
     * @param skeletonOMA
     *            the skeleton's old memory address
     * @param skeleton
     *            the skeleton specified by the given OMA
     */
    public void setSkeleton(Long skeletonOMA, Skeleton skeleton) {
        skeletons.put(skeletonOMA, skeleton);
    }

    /**
     * The method stores a binding between the skeleton and the proper armature
     * node.
     *
     * @param skeleton
     *            the skeleton
     * @param node
     *            the armature node
     */
    public void setNodeForSkeleton(Skeleton skeleton, Node node) {
        nodesWithSkeletons.put(skeleton, node);
    }

    /**
     * This method returns the armature node that is defined for the skeleton.
     *
     * @param skeleton
     *            the skeleton
     * @return the armature node that defines the skeleton in blender
     */
    public Node getControlledNode(Skeleton skeleton) {
        return nodesWithSkeletons.get(skeleton);
    }

    /**
     * This method returns the skeleton for the specified OMA of its owner.
     *
     * @param skeletonOMA
     *            the skeleton's old memory address
     * @return the skeleton specified by the given OMA
     */
    public Skeleton getSkeleton(Long skeletonOMA) {
        return skeletons.get(skeletonOMA);
    }

    /**
     * This method sets the bone context for the given bone old memory address.
     * If the context is already set it will be replaced.
     *
     * @param boneOMA
     *            the bone's old memory address
     * @param boneContext
     *            the bones's context
     */
    public void setBoneContext(Long boneOMA, BoneContext boneContext) {
        boneContexts.put(boneOMA, boneContext);
    }

    /**
     * This method returns the bone context for the given bone old memory
     * address. If no context exists then <b>null</b> is returned.
     *
     * @param boneOMA
     *            the bone's old memory address
     * @return bone's context
     */
    public BoneContext getBoneContext(Long boneOMA) {
        return boneContexts.get(boneOMA);
    }

    /**
     * Returns bone by given name.
     *
     * @param skeletonOMA
     *            the OMA of the skeleton where the bone will be searched
     * @param name
     *            the name of the bone
     * @return found bone or null if none bone of a given name exists
     */
    public BoneContext getBoneByName(Long skeletonOMA, String name) {
        for (Entry<Long, BoneContext> entry : boneContexts.entrySet()) {
            if (entry.getValue().getArmatureObjectOMA().equals(skeletonOMA)) {
                Bone bone = entry.getValue().getBone();
                if (bone != null && name.equals(bone.getName())) {
                    return entry.getValue();
                }
            }
        }
        return null;
    }

    /**
     * Returns bone context for the given bone.
     *
     * @param bone
     *            the bone
     * @return the bone's bone context
     */
    public BoneContext getBoneContext(Bone bone) {
        for (Entry<Long, BoneContext> entry : boneContexts.entrySet()) {
            if (entry.getValue().getBone().getName().equals(bone.getName())) {
                return entry.getValue();
            }
        }
        throw new IllegalStateException("Cannot find context for bone: " + bone);
    }

    /**
     * This metod returns the default material.
     *
     * @return the default material
     */
    public synchronized Material getDefaultMaterial() {
        if (blenderKey.getDefaultMaterial() == null) {
            Material defaultMaterial = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
            defaultMaterial.setColor("Color", ColorRGBA.DarkGray);
            blenderKey.setDefaultMaterial(defaultMaterial);
        }
        return blenderKey.getDefaultMaterial();
    }

    /**
     * Adds a custom marker for scene's feature.
     *
     * @param marker
     *            the marker name
     * @param feature
     *            te scene's feature (can be node, material or texture or
     *            anything else)
     * @param markerValue
     *            the marker value
     */
    public void addMarker(String marker, Object feature, Object markerValue) {
        if (markerValue == null) {
            throw new IllegalArgumentException("The marker's value cannot be null.");
        }
        Map<Object, Object> markersMap = markers.get(marker);
        if (markersMap == null) {
            markersMap = new HashMap<Object, Object>();
            markers.put(marker, markersMap);
        }
        markersMap.put(feature, markerValue);
    }

    /**
     * Returns the marker value. The returned value is null if no marker was
     * defined for the given feature.
     *
     * @param marker
     *            the marker name
     * @param feature
     *            the scene's feature
     * @return marker value or null if it was not defined
     */
    public Object getMarkerValue(String marker, Object feature) {
        Map<Object, Object> markersMap = markers.get(marker);
        return markersMap == null ? null : markersMap.get(feature);
    }

    /**
     * Adds blender action to the context.
     * @param action
     *            the action loaded from the blend file
     */
    public void addAction(BlenderAction action) {
        actions.put(action.getName(), action);
    }

    /**
     * @return a map of blender actions; the key is the action name and the value is action itself
     */
    public Map<String, BlenderAction> getActions() {
        return actions;
    }

    /**
     * This enum defines what loaded data type user wants to retreive. It can be
     * either filled structure or already converted data.
     *
     * @author Marcin Roguski (Kaelthas)
     */
    public static enum LoadedDataType {
        STRUCTURE, FEATURE, TEMPORAL_MESH;
    }

    @Override
    public String toString() {
        return blenderKey == null ? "BlenderContext [key = null]" : "BlenderContext [ key = " + blenderKey.toString() + " ]";
    }
}


text:
Bangladesh GeoCode
==================

**Division**, **District**, **Upazila** and, **Union** level fully mapped MySQL Database. Import all the files in your DB and make Join Queries (may be) to get your desired geo information.

> All information, content and spelling has been taken from bangladesh.gov.bd, wikipedia.org, maps.google.com

#### Currently has following columns
* Division name in English
    * Division name in Bangla
    * Division's government verified website address
* District mapped with Division
    * District name in English
    * district name in Bangla
    * District Commissioner's (DC) office - latitude (3 meter accuracy)
    * District Commissioner's (DC )office - longitude (3 meter accuracy)
    * District's government verified website address
* Upazila mapped with District
    * Upazila name in English
    * Upazila name in Bangla
    * Upazila's government verified website address
* Union mapped with Upazila
    * Union name is English
    * Union name in Bangla
    * Union's government verified website address

#### Available Format
* SQL
* CSV
* JSON
* PHP Array
* XML

#### Upcoming columns
* Postal Code
* Area
* Population

#### New Features
* GeoJSON data for every districts is available

> Please, create a pull request to add, update, or delete any records!

#### Now Accepting -
❤ [Paypal Donation](https://www.paypal.me/nuhil)

#### Contact
Feel free to find and contact me at [Nuhil.net](https://nuhil.net "Go To My Blog")


text:
package com.haku.log.test;

import com.haku.log.Logger;
import org.junit.Before;
import org.junit.Test;

public class TestLogTimer {
    private static final int LOOP_COUNT = 1_000;

    public final Logger log = new Logger("LogTimerTest");

    public long total_nanos = 0;

    @Before
    public void before() {
        this.log.timer.setEnabled(true);
        this.log.timer.setHandler(null);
    }

    @Test
    public void testWithoutLogTimer() {
        total_nanos = 0;
        this.log.timer.setEnabled(false);
        long nanos = System.nanoTime();
        for (int c = 0; c < LOOP_COUNT; c++) {
            int i = 0;
        }
        nanos = System.nanoTime() - nanos;
        this.log.d("%sns per call WITHOUT LogTimer", nanos / LOOP_COUNT);
    }

    @Test
    public void testLogTimerEnabled() {
        total_nanos = 0;
        this.log.timer.setEnabled(true);
        long nanos = System.nanoTime();
        for (int c = 0; c < LOOP_COUNT; c++) {
            this.log.timer.start();
            this.log.timer.stop();
        }
        nanos = System.nanoTime() - nanos;
        this.log.d("%sns per call when LogTimer ENABLED", nanos / LOOP_COUNT);
    }

    @Test
    public void testLogTimerDisabled() {
        total_nanos = 0;
        this.log.timer.setEnabled(false);
        long nanos = System.nanoTime();
        for (int c = 0; c < LOOP_COUNT; c++) {
            this.log.timer.start();
            this.log.timer.stop();

        }
        nanos = System.nanoTime() - nanos;
        this.log.d("%sns per call when LogTimer DISABLED", nanos / LOOP_COUNT);
    }
}


text:
<?php
/**
 * GOTMLS Plugin Global Variables and Functions
 * @package GOTMLS
*/

//if(!session_save_path()) session_save_path(dirname(__FILE__).'/');
$GOTMLS_HeadersError = "";
function GOTMLS_admin_notices() {
	global $GOTMLS_HeadersError;
	echo $GOTMLS_HeadersError;
}
function GOTMLS_loaded() {
	if (headers_sent($filename, $linenum)) {
		if (!$filename)
			$filename = "an unknown file";
		if (!is_numeric($linenum))
			$linenum = "unknown";
		$GOTMLS_HeadersError = "
Headers already sent in $filename on line $linenum.
This is not a good sign, it may just be a poorly written plugin but Headers should not have been sent at this point.
Check the code in the above mentioned file to fix this problem.
";
	} elseif (!session_id())
		@session_start();
	$_SESSION["GOTMLS_debug"] = array("START_microtime" => microtime(true));
	$_SESSION["GOTMLS_debug"]["START_memory_usage"] = GOTMLS_memory_usage(true);
	if (!(isset($_SERVER["SCRIPT_FILENAME"]) && "wp-login.php" == substr($_SERVER["SCRIPT_FILENAME"], -12)))
		$save_GOTMLS_login_ok=true;
	if (isset($save_GOTMLS_login_attempts))
		$_SESSION['GOTMLS_login_attempts'] = $save_GOTMLS_login_attempts;
	if (isset($save_GOTMLS_login_ok))
		$_SESSION['GOTMLS_login_ok'] = $save_GOTMLS_login_ok;
	if (isset($_SESSION["GOTMLS_login_ok"]))
		$GOTMLS_SessionError = "";
	else
		$GOTMLS_SessionError = "
Session not found, some functionality may be diminished.
If you are getting this error consistently it may mean that this site is unable to maintain a persistent session.
Check with your hosting provider or see if you can enable sessions on this site.
";
}
if (!function_exists("add_action")) {
	GOTMLS_loaded();
	GOTMLS_admin_notices();
}
/* GOTMLS init Global Variables */
$GOTMLS_Version="3.08.31";
$GOTMLS_plugin_dir="GOTMLS";
$GOTMLS_loop_execution_time = 60;
$GOTMLS_chmod_file = octdec(0644);
$GOTMLS_chmod_dir = octdec(0755);
$GOTMLS_file_contents = "";
$GOTMLS_new_contents = "";
$GOTMLS_default_ext = "";
$GOTMLS_encode = "";
$GOTMLS_onLoad = "";
$GOTMLS_threats_found = array();
$GOTMLS_dir_at_depth = array();
$GOTMLS_dirs_at_depth = array();
$GOTMLS_scanfiles = array();
$GOTMLS_skip_ext = array("png", "jpg", "jpeg", "gif", "bmp", "tif", "tiff", "exe", "zip", "pdf", "css", "mo", "psd", "so");
$GOTMLS_skip_dirs = array(".", "..");
$GOTMLS_settings_array = get_option($GOTMLS_plugin_dir.'_settings_array', array());
if (!isset($GOTMLS_settings_array["menu_group"]))
	$GOTMLS_settings_array["menu_group"] = 0;
if (!isset($GOTMLS_settings_array["scan_what"]))
	$GOTMLS_settings_array["scan_what"] = 2;
if (!isset($GOTMLS_settings_array["scan_depth"]))
	$GOTMLS_settings_array["scan_depth"] = -1;
if (!(isset($GOTMLS_settings_array["exclude_ext"]) && is_array($GOTMLS_settings_array["exclude_ext"])))
	$GOTMLS_settings_array["exclude_ext"] = $GOTMLS_skip_ext;
if (!isset($GOTMLS_settings_array["check_custom"]))
	$GOTMLS_settings_array["check_custom"] = "";
if (!(isset($GOTMLS_settings_array['exclude_dir']) && is_array($GOTMLS_settings_array['exclude_dir'])))
	$GOTMLS_settings_array["exclude_dir"] = array();
$GOTMLS_scan_logs_array = get_option($GOTMLS_plugin_dir.'_scan_logs_array', array());
$GOTMLS_total_percent = 0;

/* GOTMLS Plugin Functions */

function GOTMLS_fileperms($file) {
	$perms = fileperms($file);
	if (($perms & 0xC000) == 0xC000) {
		$info = 's';    // Socket
	} elseif (($perms & 0xA000) == 0xA000) {
		$info = 'l';    // Symbolic Link
	} elseif (($perms & 0x8000) == 0x8000) {
		$info = '-';    // Regular
	} elseif (($perms & 0x6000) == 0x6000) {
		$info = 'b';    // Block special
	} elseif (($perms & 0x4000) == 0x4000) {
		$info = 'd';    // Directory
	} elseif (($perms & 0x2000) == 0x2000) {
		$info = 'c';    // Character special
	} elseif (($perms & 0x1000) == 0x1000) {
		$info = 'p';    // FIFO pipe
	} else
		$info = 'u';    // Unknown
	// Owner
	$info .= (($perms & 0x0100) ? 'r' : '-');
	$info .= (($perms & 0x0080) ? 'w' : '-');
	$info .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) : (($perms & 0x0800) ? 'S' : '-'));

	// Group
	$info .= (($perms & 0x0020) ? 'r' : '-');
	$info .= (($perms & 0x0010) ? 'w' : '-');
	$info .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) : (($perms & 0x0400) ? 'S' : '-'));
	// World
	$info .= (($perms & 0x0004) ? 'r' : '-');
	$info .= (($perms & 0x0002) ? 'w' : '-');
	$info .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) : (($perms & 0x0200) ? 'T' : '-'));
	return $info;
}

if (!function_exists('array_replace_recursive')) {
	//create this function for PHP versions older that 5.0
	function array_replace_recursive($array, $array1) {
		function GOTMLS_recurse($array, $array1) {
			foreach ($array1 as $key => $value) {
				if (!isset($array[$key]) || (isset($array[$key]) && !is_array($array[$key])))
					$array[$key] = array();
				if (is_array($value))
					$value = GOTMLS_recurse($array[$key], $value);
				$array[$key] = $value;
			}
			return $array;
		}
		$args = func_get_args();
		$array = $args[0];
		if (!is_array($array))
			return $array;
		for ($i = 1; $i < count($args); $i++)
			if (is_array($args[$i]))
				$array = GOTMLS_recurse($array, $args[$i]);
		return $array;
	}
}

function GOTMLS_get_ext($filename) {
	$nameparts = explode(".", ".$filename");
	return strtolower($nameparts[(count($nameparts)-1)]);
}

function GOTMLS_check_threat($check_threats, $file='UNKNOWN') {
	global $GOTMLS_threats_found, $GOTMLS_definitions_array, $GOTMLS_new_contents, $GOTMLS_file_contents;
	$GOTMLS_threats_found = array();
	if (is_array($check_threats)) {
		foreach ($check_threats as $threat_name=>$threat_definitions) {
			if (is_array($threat_definitions) && count($threat_definitions) > 1 && strlen(array_shift($threat_definitions)) == 5) {
				while ($threat_definition = array_shift($threat_definitions)) {
					if ($found = @preg_match_all($threat_definition, $GOTMLS_file_contents, $threats_found)) {
						foreach ($threats_found[0] as $find) {
							$GOTMLS_threats_found[$find] = $threat_name;
							$GOTMLS_new_contents = str_replace($find, "", $GOTMLS_new_contents);
						}
					}
				}
			}
		}
	} elseif (strlen($check_threats) && isset($_GET['eli']) && substr($check_threats, 0, 1) == '/' && ($found = preg_match_all($check_threats, $GOTMLS_file_contents, $threats_found))) {
		foreach ($threats_found[0] as $find) {
			$GOTMLS_threats_found[$find] = "known";
			$GOTMLS_new_contents = str_replace($find, "", $GOTMLS_new_contents);
		}
	}
	return count($GOTMLS_threats_found);
}

function GOTMLS_scanfile($file) {
	global $GOTMLS_quarantine_dir, $GOTMLS_threat_levels, $GOTMLS_threat_files, $GOTMLS_definitions_array, $GOTMLS_threats_found, $GOTMLS_chmod_file, $GOTMLS_chmod_dir, $GOTMLS_settings_array, $GOTMLS_file_contents, $GOTMLS_new_contents, $GOTMLS_script_URI;
	$GOTMLS_threats_found = array();
	$found = false;
	$threat_link = "";
	$className = "scanned";
	$clean_file = GOTMLS_encode($file);
	if (is_file($file) && ($filesize = filesize($file)) && ($GOTMLS_file_contents = @file_get_contents($file))) {
		foreach ($GOTMLS_definitions_array["whitelist"] as $whitelist_file=>$non_threats) {
			if (isset($non_threats[0])) {
				$updated = $non_threats[0];
				unset($non_threats[0]);
			} else
				$updated = "A0002";
			if (is_array($non_threats) && count($non_threats) && substr(str_replace("\\", "/", $file), (-1 * strlen($whitelist_file))) == str_replace("\\", "/", $whitelist_file)) {
				if (in_array(md5($GOTMLS_file_contents).'O'.$filesize, array_keys($non_threats), true))
					return GOTMLS_return_threat($className, "checked.gif?$className", $file, $threat_link);
				elseif (in_array(md5($GOTMLS_file_contents), $non_threats, true)) {
					if (!(isset($GOTMLS_definitions_array["whitelist"][''.GOTMLS_get_ext($file)][0]) && $GOTMLS_definitions_array["whitelist"][''.GOTMLS_get_ext($file)][0] >= $updated))
						$GOTMLS_definitions_array["whitelist"][''.GOTMLS_get_ext($file)][0] = $updated;
					$GOTMLS_definitions_array["whitelist"][''.GOTMLS_get_ext($file)][md5($GOTMLS_file_contents).'O'.$filesize] = $updated;
					unset($GOTMLS_definitions_array["whitelist"][$whitelist_file]);
					update_option("GOTMLS_definitions_array", $GOTMLS_definitions_array);
					return GOTMLS_return_threat($className, "checked.gif?$className", $file, $threat_link);
				}
			}
		}
		$GOTMLS_new_contents = $GOTMLS_file_contents;
		if (isset($_SESSION["GOTMLS"]["check_custom"]) && strlen($_SESSION["GOTMLS"]["check_custom"]) && isset($_GET['eli']) && substr($_SESSION["GOTMLS"]["check_custom"], 0, 1) == '/' && ($found = GOTMLS_check_threat($_SESSION["GOTMLS"]["check_custom"]))) //don't use this without registration
			$className = "known";
		else
			foreach ($GOTMLS_threat_levels as $threat_level)
				if (in_array($threat_level, $_SESSION["GOTMLS"]["check"]) && !$found && isset($GOTMLS_definitions_array[$threat_level]) && (!array_key_exists($threat_level,$GOTMLS_threat_files) || ((GOTMLS_get_ext($file) == "gotmls" && isset($_GET["eli"]) && $_GET["eli"] == "quarantine")?(substr(GOTMLS_decode(array_pop(explode(".", '.'.substr($file, strlen(dirname($file))+1, -7))))."e", (-1 * strlen($GOTMLS_threat_files[$threat_level]."e"))) == $GOTMLS_threat_files[$threat_level]."e"):(substr($file."e", (-1 * strlen($GOTMLS_threat_files[$threat_level]."e"))) == $GOTMLS_threat_files[$threat_level]."e"))) && ($found = GOTMLS_check_threat($GOTMLS_definitions_array[$threat_level],$file)))
					$className = $threat_level;
	} else {
		$GOTMLS_file_contents = 'Failed to read file contents! '.(is_readable($file)?'(file_is_readable)':(file_exists($file)?(isset($_GET["eli"])?(@chmod($file, $GOTMLS_chmod_file)?'chmod':'read-only'):'(file_not_readable)'):'(does_not_exist)'));
//		$threat_link = GOTMLS_error_link($GOTMLS_file_contents, $file);
		$className = "errors";
	}
	if (count($GOTMLS_threats_found)) {
		$threat_link = "";
		if (isset($_POST["GOTMLS_fix"][$clean_file]) && $_POST["GOTMLS_fix"][$clean_file] > 0) {
			$file_date = explode(".", array_pop(GOTMLS_explode_dir($file)));
			if (GOTMLS_get_ext($file) == "gotmls" && GOTMLS_trailingslashit($GOTMLS_quarantine_dir) == substr($file, 0, strlen(GOTMLS_trailingslashit($GOTMLS_quarantine_dir)))) {
				if (count($file_date) > 1 && $GOTMLS_new_contents = @file_get_contents($file))
					$file = GOTMLS_decode($file_date[count($file_date)-2]);
				else
					$GOTMLS_file_contents = "";
			} elseif (isset($GOTMLS_threat_files[$className]) && GOTMLS_get_ext($GOTMLS_threat_files[$className]) == "php") {
				$project = str_replace("_", "-", $className);
				$source = wp_remote_get("http://$project.googlecode.com/svn/trunk/$project.php");
				if (is_array($source) && isset($source["body"]) && strlen($source["body"]) > 500)
					$GOTMLS_new_contents = $source["body"].$GOTMLS_new_contents;
				else
					$GOTMLS_file_contents = "";
			} else
				$GOTMLS_new_contents = trim(preg_replace('/<\?(php)?[\r\n \t]*\?>/i', "", $GOTMLS_new_contents));//preg_replace('/[\r\n]+/', "\n",
			if (strlen($GOTMLS_file_contents) > 0 && (@file_put_contents(GOTMLS_quarantine($file), $GOTMLS_file_contents) || ((is_writable(dirname(GOTMLS_quarantine($file))) || ($chmoded_quarantine = @chmod(dirname(GOTMLS_quarantine($file)), 0777))) && @file_put_contents(GOTMLS_quarantine($file), $GOTMLS_file_contents) && !($chmoded_quarantine && !@chmod(dirname(GOTMLS_quarantine($file)), $GOTMLS_chmod_dir)))) && ((strlen($GOTMLS_new_contents)==0 && @unlink($file)) || (@file_put_contents($file, $GOTMLS_new_contents) || ((is_writable(dirname($file)) || ($chmoded_dir = @chmod(dirname($file), 0777))) && (is_writable($file) || ($chmoded_file = @chmod($file, 0666))) && @file_put_contents($file, $GOTMLS_new_contents) && !($chmoded_dir && !@chmod(dirname($file), $GOTMLS_chmod_dir)) && !($chmoded_file && !@chmod($file, $GOTMLS_chmod_file)))))) {
				echo ' Success!';
				return "/*-->*/\nfixedFile('$clean_file');\n/**/\nfailedFile('$clean_file');\n/**/\nfixedFile('$clean_file');\n/**/\nfixedFile('$clean_file');\n/**/";
	if ($className != "scanned")
		$li_js .= "\n$className++;\ndivx=document.getElementById('found_$className');\nif (divx) {\n\tvar newli = document.createElement('li');\n\tnewli.innerHTML='".GOTMLS_strip4java($link).$fileNameJS.($link?"';\n\tdivx.display='block';":"';")."\n\tdivx.appendChild(newli);\n}";
	if ($className == "errors")
		$li_js .= "\ndivx=document.getElementById('wait_$fileName64');\nif (divx) {\n\tdivx.src='$GOTMLS_images_path"."blocked.gif';\n\tdirerrors++;\n}";
	elseif (is_file($fileName))
	 	$li_js .= "\nscanned++;\n";
	if ($className == "dir")
		$li_js .= "\ndivx=document.getElementById('wait_$fileName64');\nif (divx)\n\tdivx.src='$GOTMLS_images_path"."checked.gif';";
	return $li_js."\n/**/\nupdate_status('".GOTMLS_strip4java($status)."', $microtime, $percent);\n/**/");
		}
		echo "$output\n</$tag>";
	}
	if (@ob_get_length())
		@ob_flush();
	if ($tag)
		echo "\n<$tag>\n/**/\ndocument.getElementById('status_text').innerHTML='Checking ".GOTMLS_strip4java($file)." ($filesize bytes)';\n/**/\ndocument.getElementById('status_text').innerHTML='Checked ".GOTMLS_strip4java($file)."';\n/**/\nscanfilesArKeys.push('".GOTMLS_encode($dir)."&GOTMLS_only_file=".GOTMLS_encode($file)."');\nscanfilesArNames.push('Re-Checking ".GOTMLS_strip4java($path)."');\n/*


text:
import Vue from 'vue'
import Router from 'vue-router'
import Meta from 'vue-meta'

import { routes as intro } from '@/app/intro'
import { routes as overview } from '@/app/overview'
import { routes as register } from '@/app/register'
import { routes as plant } from '@/app/plant'
import { routes as gallery } from '@/app/gallery'
import { routes as settings } from '@/app/settings'
import { routes as notfound } from '@/app/not-found'

Vue.use(Router)
Vue.use(Meta, { keyName: 'meta' })

const router = new Router({
  mode: 'history',

  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    }
    return { x: 0, y: 0 }
  },

  routes: [
    ...intro,
    ...overview,
    ...register,
    ...plant,
    ...gallery,
    ...settings,
    ...notfound
  ]
})

export default router