text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Used to render the footer of PMA's pages
 *
 * @package PhpMyAdmin
 */
namespace PhpMyAdmin;

use PhpMyAdmin\Config;
use PhpMyAdmin\Core;
use PhpMyAdmin\Message;
use PhpMyAdmin\Relation;
use PhpMyAdmin\Response;
use PhpMyAdmin\Sanitize;
use PhpMyAdmin\Scripts;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use Traversable;

/**
 * Class used to output the footer
 *
 * @package PhpMyAdmin
 */
class Footer
{
    /**
     * Scripts instance
     *
     * @access private
     * @var Scripts
     */
    private $_scripts;
    /**
     * Whether we are servicing an ajax request.
     *
     * @access private
     * @var bool
     */
    private $_isAjax;
    /**
     * Whether to only close the BODY and HTML tags
     * or also include scripts, errors and links
     *
     * @access private
     * @var bool
     */
    private $_isMinimal;
    /**
     * Whether to display anything
     *
     * @access private
     * @var bool
     */
    private $_isEnabled;

    /**
     * @var Relation $relation
     */
    private $relation;

    /**
     * Creates a new class instance
     */
    public function __construct()
    {
        $this->_isEnabled = true;
        $this->_scripts   = new Scripts();
        $this->_isMinimal = false;
        $this->relation = new Relation();
    }

    /**
     * Returns the message for demo server to error messages
     *
     * @return string
     */
    private function _getDemoMessage()
    {
        $message = '' . __('phpMyAdmin Demo Server') . ': ';
        if (@file_exists('./revision-info.php')) {
            include './revision-info.php';
            $message .= sprintf(
                __('Currently running Git revision %1$s from the %2$s branch.'),
                ''
                . htmlspecialchars($revision) . '',
                ''
                . htmlspecialchars($branch) . ''
            );
        } else {
            $message .= __('Git information missing!');
        }

        return Message::notice($message)->getDisplay();
    }

    /**
     * Remove recursions and iterator objects from an object
     *
     * @param object|array &$object Object to clean
     * @param array        $stack   Stack used to keep track of recursion,
     *                              need not be passed for the first time
     *
     * @return object Reference passed object
     */
    private static function _removeRecursion(&$object, array $stack = array())
    {
        if ((is_object($object) || is_array($object)) && $object) {
            if ($object instanceof Traversable) {
                $object = "***ITERATOR***";
            } elseif (!in_array($object, $stack, true)) {
                $stack[] = $object;
                foreach ($object as &$subobject) {
                    self::_removeRecursion($subobject, $stack);
                }
            } else {
                $object = "***RECURSION***";
            }
        }
        return $object;
    }

    /**
     * Renders the debug messages
     *
     * @return string
     */
    public function getDebugMessage()
    {
        $retval = '\'null\'';
        if ($GLOBALS['cfg']['DBG']['sql']
            && empty($_REQUEST['no_debug'])
            && !empty($_SESSION['debug'])
        ) {
            // Remove recursions and iterators from $_SESSION['debug']
            self::_removeRecursion($_SESSION['debug']);

            $retval = JSON_encode($_SESSION['debug']);
            $_SESSION['debug'] = array();
            return json_last_error() ? '\'false\'' : $retval;
        }
        $_SESSION['debug'] = array();
        return $retval;
    }

    /**
     * Returns the url of the current page
     *
     * @return string
     */
    public function getSelfUrl()
    {
        $db = isset($GLOBALS['db']) && strlen($GLOBALS['db']) ? $GLOBALS['db'] : '';
        $table = isset($GLOBALS['table']) && strlen($GLOBALS['table']) ? $GLOBALS['table'] : '';
        $target = isset($_REQUEST['target']) && strlen($_REQUEST['target']) ? $_REQUEST['target'] : '';
        $params = array(
            'db' => $db,
            'table' => $table,
            'server' => $GLOBALS['server'],
            'target' => $target
        );
        // needed for server privileges tabs
        if (isset($_GET['viewing_mode'])
            && in_array($_GET['viewing_mode'], array('server', 'db', 'table'))
        ) {
            $params['viewing_mode'] = $_GET['viewing_mode'];
        }
        /*
         * @todo    coming from server_privileges.php, here $db is not set,
         *          add the following condition below when that is fixed
         *          && $_GET['checkprivsdb'] == $db
         */
        if (isset($_GET['checkprivsdb'])
        ) {
            $params['checkprivsdb'] = $_GET['checkprivsdb'];
        }
        /*
         * @todo    coming from server_privileges.php, here $table is not set,
         *          add the following condition below when that is fixed
         *          && $_REQUEST['checkprivstable'] == $table
         */
        if (isset($_GET['checkprivstable'])
        ) {
            $params['checkprivstable'] = $_GET['checkprivstable'];
        }
        if (isset($_REQUEST['single_table'])
            && in_array($_REQUEST['single_table'], array(true, false))
        ) {
            $params['single_table'] = $_REQUEST['single_table'];
        }
        return basename(Core::getenv('SCRIPT_NAME')) . Url::getCommonRaw($params);
    }

    /**
     * Renders the link to open a new page
     *
     * @param string $url The url of the page
     *
     * @return string
     */
    private function _getSelfLink($url)
    {
        $retval  = '';
        $retval .= '
';
        $retval .= '';
        if (Util::showIcons('TabsMode')) {
            $retval .= Util::getImage(
                'window-new',
                __('Open new phpMyAdmin window')
            );
        } else {
            $retval .=  __('Open new phpMyAdmin window');
        }
        $retval .= '';
        $retval .= '
';
        return $retval;
    }

    /**
     * Renders the link to open a new page
     *
     * @return string
     */
    public function getErrorMessages()
    {
        $retval = '';
        if ($GLOBALS['error_handler']->hasDisplayErrors()) {
            $retval .= $GLOBALS['error_handler']->getDispErrors();
        }

        /**
         * Report php errors
         */
        $GLOBALS['error_handler']->reportErrors();

        return $retval;
    }

    /**
     * Saves query in history
     *
     * @return void
     */
    private function _setHistory()
    {
        if (! Core::isValid($_REQUEST['no_history'])
            && empty($GLOBALS['error_message'])
            && ! empty($GLOBALS['sql_query'])
            && isset($GLOBALS['dbi'])
            && $GLOBALS['dbi']->isUserType('logged')
        ) {
            $this->relation->setHistory(
                Core::ifSetOr($GLOBALS['db'], ''),
                Core::ifSetOr($GLOBALS['table'], ''),
                $GLOBALS['cfg']['Server']['user'],
                $GLOBALS['sql_query']
            );
        }
    }

    /**
     * Disables the rendering of the footer
     *
     * @return void
     */
    public function disable()
    {
        $this->_isEnabled = false;
    }

    /**
     * Set the ajax flag to indicate whether
     * we are servicing an ajax request
     *
     * @param bool $isAjax Whether we are servicing an ajax request
     *
     * @return void
     */
    public function setAjax($isAjax)
    {
        $this->_isAjax = (boolean) $isAjax;
    }

    /**
     * Turn on minimal display mode
     *
     * @return void
     */
    public function setMinimal()
    {
        $this->_isMinimal = true;
    }

    /**
     * Returns the Scripts object
     *
     * @return Scripts object
     */
    public function getScripts()
    {
        return $this->_scripts;
    }

    /**
     * Renders the footer
     *
     * @return string
     */
    public function getDisplay()
    {
        $retval = '';
        $this->_setHistory();
        if ($this->_isEnabled) {
            if (! $this->_isAjax) {
                $retval .= "
";
            }
            if (! $this->_isAjax && ! $this->_isMinimal) {
                if (Core::getenv('SCRIPT_NAME')
                    && empty($_POST)
                    && ! $this->_isAjax
                ) {
                    $url = $this->getSelfUrl();
                    $header = Response::getInstance()->getHeader();
                    $scripts = $header->getScripts()->getFiles();
                    $menuHash = $header->getMenu()->getHash();
                    // prime the client-side cache
                    $this->_scripts->addCode(
                        sprintf(
                            'if (! (history && history.pushState)) '
                            . 'PMA_MicroHistory.primer = {'
                            . ' url: "%s",'
                            . ' scripts: %s,'
                            . ' menuHash: "%s"'
                            . '};',
                            Sanitize::escapeJsString($url),
                            json_encode($scripts),
                            Sanitize::escapeJsString($menuHash)
                        )
                    );
                }
                if (Core::getenv('SCRIPT_NAME')
                    && ! $this->_isAjax
                ) {
                    $url = $this->getSelfUrl();
                    $retval .= $this->_getSelfLink($url);
                }
                $this->_scripts->addCode(
                    'var debugSQLInfo = ' . $this->getDebugMessage() . ';'
                );
                $retval .= '
';
                $retval .= $this->getErrorMessages();
                $retval .= '
';
                $retval .= $this->_scripts->getDisplay();
                if ($GLOBALS['cfg']['DBG']['demo']) {
                    $retval .= '
';
                    $retval .= $this->_getDemoMessage();
                    $retval .= '
';
                }

                $retval .= Config::renderFooter();
            }
            if (! $this->_isAjax) {
                $retval .= "";
            }
        }

        return $retval;
    }
}


text:
require 'net/http'
require 'json'

search_term = URI::encode('#todayilearned')

SCHEDULER.every '10m', :first_in => 0 do |job|
  http = Net::HTTP.new('search.twitter.com')
  response = http.request(Net::HTTP::Get.new("/search.json?q=#{search_term}"))
  tweets = JSON.parse(response.body)["results"]
  if tweets
    tweets.map! do |tweet|
      { name: tweet['from_user'], body: tweet['text'], avatar: tweet['profile_image_url_https'] }
    end

    send_event('twitter_mentions', comments: tweets)
  end
end

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Rhus glutinosa Hochst. ex A.Rich.

### Remarks
null


text:
"""Tests for the REGF Windows Registry back-end."""

import unittest

from plaso.dfwinreg import regf

from tests.dfwinreg import test_lib

class REGFWinRegTestCase(test_lib.WinRegTestCase):
  """The unit test case for REGF Windows Registry related object."""

  def _OpenREGFRegistryFile(self, filename):
    """Opens a REGF Windows Registry file.

    Args:
      filename: the name of the file relative to the test file path.

    Returns:
      The Windows Registry file object (instance of REGFWinRegistryFileTest) or
      None.
    """
    test_file = self._GetTestFilePath([filename])
    file_entry = self._GetTestFileEntry(test_file)
    file_object = file_entry.GetFileObject()

    registry_file = regf.REGFWinRegistryFile()
    registry_file.Open(file_object)

    return registry_file

class REGFWinRegistryFileTest(REGFWinRegTestCase):
  """Tests for the REGF Windows Registry file object."""

  def testOpenClose(self):
    """Tests the Open and Close functions."""
    registry_file = self._OpenREGFRegistryFile(u'NTUSER.DAT')
    registry_file.Close()

  def testGetRootKey(self):
    """Tests the GetRootKey function."""
    registry_file = self._OpenREGFRegistryFile(u'NTUSER.DAT')

    registry_key = registry_file.GetRootKey()
    self.assertIsNotNone(registry_key)
    self.assertEqual(registry_key.path, u'\\')

    registry_file.Close()

    registry_file = self._OpenREGFRegistryFile(u'ntuser.dat.LOG')

    root_key = registry_file.GetRootKey()
    self.assertIsNone(root_key)

  def testGetKeyByPath(self):
    """Tests the GetKeyByPath function."""
    registry_file = self._OpenREGFRegistryFile(u'NTUSER.DAT')

    key_path = u'\\'
    registry_key = registry_file.GetKeyByPath(key_path)
    self.assertIsNotNone(registry_key)
    self.assertEqual(registry_key.path, key_path)

    key_path = u'\\Software'
    registry_key = registry_file.GetKeyByPath(key_path)
    self.assertIsNotNone(registry_key)
    self.assertEqual(registry_key.path, key_path)

    key_path = u'\\Bogus'
    registry_key = registry_file.GetKeyByPath(key_path)
    self.assertIsNone(registry_key)

    registry_file.Close()

  def testRecurseKeys(self):
    """Tests the RecurseKeys function."""
    registry_file = self._OpenREGFRegistryFile(u'NTUSER.DAT')

    registry_keys = list(registry_file.RecurseKeys())
    registry_file.Close()

    self.assertEqual(len(registry_keys), 1127)

    registry_file = self._OpenREGFRegistryFile(u'ntuser.dat.LOG')

    registry_keys = list(registry_file.RecurseKeys())
    registry_file.Close()

    self.assertEqual(len(registry_keys), 0)

class REGFWinRegistryKeyTest(REGFWinRegTestCase):
  """Tests for the REGF Windows Registry key object."""

  def testProperties(self):
    """Tests the properties functions."""
    registry_file = self._OpenREGFRegistryFile(u'NTUSER.DAT')

    key_path = u'\\Software'
    registry_key = registry_file.GetKeyByPath(key_path)
    self.assertIsNotNone(registry_key)
    self.assertEqual(registry_key.last_written_time, 128938728930133750)
    self.assertEqual(registry_key.name, u'Software')
    self.assertEqual(registry_key.number_of_subkeys, 7)
    self.assertEqual(registry_key.number_of_values, 0)
    self.assertEqual(registry_key.offset, 82652)
    self.assertEqual(registry_key.path, key_path)

    registry_file.Close()

  def testGetSubkeyByName(self):
    """Tests the GetSubkeyByName function."""
    registry_file = self._OpenREGFRegistryFile(u'NTUSER.DAT')

    registry_key = registry_file.GetRootKey()

    key_name = u'Software'
    subkey = registry_key.GetSubkeyByName(key_name)
    self.assertIsNotNone(subkey)
    self.assertEqual(subkey.name, key_name)

    key_name = u'Bogus'
    subkey = registry_key.GetSubkeyByName(key_name)
    self.assertIsNone(subkey)

    registry_file.Close()

  def testGetSubkeys(self):
    """Tests the GetSubkeys function."""
    registry_file = self._OpenREGFRegistryFile(u'NTUSER.DAT')

    key_path = u'\\Software'
    registry_key = registry_file.GetKeyByPath(key_path)

    subkeys = list(registry_key.GetSubkeys())
    self.assertEqual(len(subkeys), 7)

    registry_file.Close()

  def testGetValueByName(self):
    """Tests the GetValueByName function."""
    registry_file = self._OpenREGFRegistryFile(u'NTUSER.DAT')

    registry_key = registry_file.GetKeyByPath(u'\\Console')

    value_name = u'ColorTable14'
    registry_value = registry_key.GetValueByName(value_name)
    self.assertIsNotNone(registry_value)
    self.assertEqual(registry_value.name, value_name)

    value_name = u'Bogus'
    registry_value = registry_key.GetValueByName(value_name)
    self.assertIsNone(registry_value)

    # Test retrieving the default (or nameless) value.
    registry_key = registry_file.GetKeyByPath(
        u'\\AppEvents\\EventLabels\\.Default')

    registry_value = registry_key.GetValueByName(u'')
    self.assertIsNotNone(registry_value)
    self.assertIsNone(registry_value.name)

    registry_file.Close()

  def testGetValues(self):
    """Tests the GetValues function."""
    registry_file = self._OpenREGFRegistryFile(u'NTUSER.DAT')

    key_path = u'\\Console'
    registry_key = registry_file.GetKeyByPath(key_path)

    values = list(registry_key.GetValues())
    self.assertEqual(len(values), 31)

    registry_file.Close()

  def testRecurseKeys(self):
    """Tests the RecurseKeys function."""
    registry_file = self._OpenREGFRegistryFile(u'NTUSER.DAT')

    key_path = u'\\Software'
    registry_key = registry_file.GetKeyByPath(key_path)
    registry_keys = list(registry_key.RecurseKeys())
    registry_file.Close()

    self.assertEqual(len(registry_keys), 797)

class REGFWinRegistryValueTest(REGFWinRegTestCase):
  """Tests for the REGF Windows Registry value object."""

  def testProperties(self):
    """Tests the properties functions."""
    registry_file = self._OpenREGFRegistryFile(u'NTUSER.DAT')

    registry_key = registry_file.GetKeyByPath(u'\\Console')
    value_name = u'ColorTable14'
    registry_value = registry_key.GetValueByName(value_name)
    expected_raw_data = b'\xff\xff\x00\x00'

    self.assertIsNotNone(registry_value)
    self.assertEqual(registry_value.data_type, 4)
    self.assertEqual(registry_value.data_type_string, u'REG_DWORD_LE')
    self.assertEqual(registry_value.data, 65535)
    self.assertEqual(registry_value.name, value_name)
    self.assertEqual(registry_value.offset, 29516)
    self.assertEqual(registry_value.raw_data, expected_raw_data)

    registry_key = registry_file.GetKeyByPath(
        u'\\AppEvents\\EventLabels\\CriticalBatteryAlarm')
    value_name = u'DispFileName'
    registry_value = registry_key.GetValueByName(value_name)
    expected_raw_data = (
        b'@\x00m\x00m\x00s\x00y\x00s\x00.\x00c\x00p\x00l\x00,\x00-\x005\x008'
        b'\x002\x007\x00\x00\x00')

    self.assertIsNotNone(registry_value)
    self.assertEqual(registry_value.data_type, 1)
    self.assertEqual(registry_value.data_type_string, u'REG_SZ')
    self.assertEqual(registry_value.data, u'@mmsys.cpl,-5827')
    self.assertEqual(registry_value.name, value_name)
    self.assertEqual(registry_value.offset, 6012)
    self.assertEqual(registry_value.raw_data, expected_raw_data)

    registry_key = registry_file.GetKeyByPath(
        u'\\Software\\Microsoft\\Windows\\ShellNoRoam\\BagMRU')
    value_name = u'0'
    registry_value = registry_key.GetValueByName(value_name)
    expected_raw_data = (
        b'\x14\x00\x1fP\xe0O\xd0 \xea:i\x10\xa2\xd8\x08\x00+00\x9d\x00\x00')

    self.assertIsNotNone(registry_value)
    self.assertEqual(registry_value.data_type, 3)
    self.assertEqual(registry_value.data_type_string, u'REG_BINARY')
    self.assertEqual(registry_value.data, expected_raw_data)
    self.assertEqual(registry_value.name, value_name)
    self.assertEqual(registry_value.offset, 625588)
    self.assertEqual(registry_value.raw_data, expected_raw_data)

    registry_file.Close()

    registry_file = self._OpenREGFRegistryFile(u'NTUSER-WIN7.DAT')

    registry_key = registry_file.GetKeyByPath(
        u'\\Software\\Microsoft\\Cryptography\\CertificateTemplateCache\\User')
    value_name = u'SupportedCSPs'
    registry_value = registry_key.GetValueByName(value_name)
    expected_data = [
        u'Microsoft Enhanced Cryptographic Provider v1.0',
        u'Microsoft Base Cryptographic Provider v1.0']
    expected_raw_data = (
        b'M\x00i\x00c\x00r\x00o\x00s\x00o\x00f\x00t\x00 \x00E\x00n\x00h\x00a'
        b'\x00n\x00c\x00e\x00d\x00 \x00C\x00r\x00y\x00p\x00t\x00o\x00g\x00r'
        b'\x00a\x00p\x00h\x00i\x00c\x00 \x00P\x00r\x00o\x00v\x00i\x00d\x00e'
        b'\x00r\x00 \x00v\x001\x00.\x000\x00\x00\x00M\x00i\x00c\x00r\x00o'
        b'\x00s\x00o\x00f\x00t\x00 \x00B\x00a\x00s\x00e\x00 \x00C\x00r\x00y'
        b'\x00p\x00t\x00o\x00g\x00r\x00a\x00p\x00h\x00i\x00c\x00 \x00P\x00r'
        b'\x00o\x00v\x00i\x00d\x00e\x00r\x00 \x00v\x001\x00.\x000\x00\x00'
        b'\x00\x00\x00')

    self.assertIsNotNone(registry_value)
    self.assertEqual(registry_value.data_type, 7)
    self.assertEqual(registry_value.data_type_string, u'REG_MULTI_SZ')
    self.assertEqual(registry_value.data, expected_data)
    self.assertEqual(registry_value.name, value_name)
    self.assertEqual(registry_value.offset, 241452)
    self.assertEqual(registry_value.raw_data, expected_raw_data)

    registry_file.Close()

if __name__ == '__main__':
  unittest.main()


text:
{% extends "registration/base.html" %}
{% block title %}Logged out{% endblock %}
{%block registration_content%}

Successfully logged out!

{% endblock %}


text:
namespace webmlive {

bool BufferQueue::EnqueueBuffer(const std::string& id,
                                const uint8* data, int length) {
  Buffer* buffer = new (std::nothrow) Buffer;
  if (!buffer) {
    LOG(ERROR) << "No memory in BufferQueue::EnqueueBuffer";
    return false;
  }
  buffer->id = id;
  buffer->data.insert(buffer->data.begin(), data, data + length);
  std::lock_guard<std::mutex> lock(mutex_);
  buffer_q_.push(buffer);
  return true;
}

BufferQueue::Buffer* BufferQueue::DequeueBuffer() {
  BufferQueue::Buffer* buffer = NULL;
  std::unique_lock<std::mutex> lock(mutex_, std::try_to_lock);
  if (lock.owns_lock() && !buffer_q_.empty()) {
    buffer = buffer_q_.front();
    buffer_q_.pop();
  }
  return buffer;
}

// Attempts to obtain lock on |mutex_|. Returns value of |locked_| if the lock
// is obtained, assumes locked and returns true otherwise.
bool LockableBuffer::IsLocked() {
  std::unique_lock<std::mutex> lock(mutex_, std::try_to_lock);
  if (lock.owns_lock()) {
    return locked_;
  }
  return true;
}

// Confirms buffer is unlocked via call to |IsLocked|, obtains lock on
// |mutex_|, and copies the user data into |buffer_|.
int LockableBuffer::Init(const uint8* const ptr_data, int length) {
  if (IsLocked()) {
    return kLocked;
  }
  std::lock_guard<std::mutex> lock(mutex_);
  if (!ptr_data || length <= 0) {
    LOG(ERROR) << "invalid arg(s).";
    return kInvalidArg;
  }
  buffer_.clear();
  buffer_.assign(ptr_data, ptr_data + length);
  return kSuccess;
}

// Confirms buffer is locked via call to |IsLocked|, obtains lock on
// |mutex_|, and copies the user data into |buffer_|.
int LockableBuffer::GetBuffer(uint8** ptr_buffer, int* ptr_length) {
  if (!ptr_length) {
    return kInvalidArg;
  }
  if (!IsLocked()) {
    LOG(ERROR) << "buffer not locked!";
    return kNotLocked;
  }
  *ptr_buffer = &buffer_[0];
  *ptr_length = buffer_.size();
  return kSuccess;
}

// Obtains lock on |mutex_| and sets |locked_| to true.
int LockableBuffer::Lock() {
  std::lock_guard<std::mutex> lock(mutex_);
  int status = kSuccess;
  if (locked_) {
    status = kLocked;
  }
  locked_ = true;
  return status;
}

// Obtains lock on |mutex_| and sets |locked_| to false.
int LockableBuffer::Unlock() {
  std::lock_guard<std::mutex> lock(mutex_);
  int status = kSuccess;
  if (!locked_) {
    status = kNotLocked;
    LOG(ERROR) << "buffer was not locked!";
  }
  locked_ = false;
  return status;
}

}  // namespace webmlive


text:
package org.springframework.cloud.task.configuration;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.task.repository.TaskRepository;
import org.springframework.cloud.task.repository.support.SimpleTaskRepository;
import org.springframework.cloud.task.repository.support.TaskExecutionDaoFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

@RunWith(Suite.class)
@SuiteClasses({
		TaskPropertiesTests.CloseContextEnableTest.class,
		TaskPropertiesTests.CloseContextEnabledTest.class,

})

@DirtiesContext
public class TaskPropertiesTests {
	@Autowired
	TaskProperties taskProperties;

	@Test
	public void test() {
		assertThat(taskProperties.getClosecontextEnabled(), is(false));
	}

	@RunWith(SpringRunner.class)
	@SpringBootTest(classes={TaskPropertiesTests.Config.class}, properties = { "spring.cloud.task.closecontextEnable=false" })
	@DirtiesContext
	public static class CloseContextEnableTest extends TaskPropertiesTests {
	}

	@RunWith(SpringRunner.class)
	@SpringBootTest(classes={TaskPropertiesTests.Config.class}, properties = { "spring.cloud.task.closecontextEnabled=false" })
	@DirtiesContext
	public static class CloseContextEnabledTest extends TaskPropertiesTests {}

	@Configuration
	@EnableTask
	public static class Config {
		@Bean
		TaskExecutionDaoFactoryBean taskExecutionDaoFactoryBean() {
			return new TaskExecutionDaoFactoryBean();
		}
		@Bean
		public TaskRepository taskRepository(TaskExecutionDaoFactoryBean tefb) {
			return new SimpleTaskRepository(tefb);
		}
	}
}


text:
namespace DLaB.Xrm.Entities
{

	[System.Runtime.Serialization.DataContractAttribute()]
	[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9154")]
	public enum Queue_OutgoingEmailDeliveryMethod
	{

		[System.Runtime.Serialization.EnumMemberAttribute()]
		None = 0,

		[System.Runtime.Serialization.EnumMemberAttribute()]
		ServerSideSynchronizationorEmailRouter = 2,
	}
}


text:
package com.googlecode.pondskum.gui.swing.notifyer;

import java.awt.Color;

public final class DownloadRenderer extends AbstractRenderer {

    DownloadRenderer(final double displayRatio) {
        super(displayRatio);
    }

    @Override
    protected Color getProgressColor() {
        return Color.CYAN;
    }

    @Override
    protected Color getTextColor() {
        return Color.BLACK;
    }

    @Override
    protected boolean isRaised() {
        return false;
    }

    @Override
    protected String getText() {
        return "Downloads (" + getDisplayRatio() + ") GB";
    }
}


text:
package org.softeg.slartus.forpdaplus.emotic;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.preference.PreferenceManager;

import org.softeg.slartus.forpdaplus.App;
import org.softeg.slartus.forpdaplus.classes.BbImage;
import org.softeg.slartus.forpdaplus.classes.common.ExtBitmap;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: slinkin
 * Date: 17.10.12
 * Time: 9:27
 * To change this template use File | Settings | File Templates.
 */
public class Smiles extends ArrayList<Smile> {

    protected Smiles() {
        fill();

    }

    public static Smiles createSmiles() {
        return new Smiles();
//        String cssFilePath = MyApp.getInstance().getThemeCssFileName();
//        if (cssFilePath.startsWith("/android_asset/"))
//            return new Smiles();
//        return new SmilesPack(cssFilePath);
    }

    public void setWeights() {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(App.getContext());
        String weights = preferences.getString("smiles.weights", "");
        Matcher m = Pattern.compile("(.*?):(\\d+);").matcher(weights);
        while (m.find()) {
            Smile smile = findByFileName(m.group(1));
            if (smile == null) continue;
            smile.Weight = Integer.parseInt(m.group(2));
        }
    }

    private void saveWeights() {
        normalizeWights();
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(App.getContext());
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("smiles.weights", getWeightString());
        editor.commit();

    }

    private String getWeightString() {
        StringBuilder sb = new StringBuilder();
        for (Smile smile : this) {
            sb.append(smile.FileName + ":" + smile.Weight + ";");
        }
        return sb.toString();
    }

    private void normalizeWights() {
        int minWeight = Integer.MAX_VALUE;
        for (Smile smile : this) {
            minWeight = Math.min(minWeight, smile.Weight);
        }
        if (minWeight > 0)
            for (Smile smile : this) {
                smile.Weight -= 1;
            }
    }

    public void sortByWeights() {
        Collections.sort(this, new Comparator<Smile>() {
            @Override
            public int compare(Smile lhs, Smile rhs) {
                if (lhs.Weight == rhs.Weight)
                    return 0;
                return lhs.Weight > rhs.Weight ? -1 : 1;
            }
        });
    }

    public void addWeight(Smile smile) {
        smile.Weight += 1;
        saveWeights();
    }

    public Smile findByFileName(String fileName) {
        for (Smile smile : this) {
            if (smile.FileName.equals(fileName))
                return smile;
        }
        return null;
    }

    public String getDirPath() {
        return "forum/style_emoticons/default/";
    }

    public String getCssPath() {
        return "file:///android_asset/forum/style_emoticons";
    }

    public BbImage[] getFilesList() {
        setWeights();
        sortByWeights();

        BbImage[] res = new BbImage[size()];
        String path = getDirPath();
        for (int i = 0; i < size(); i++) {
            res[i] = new BbImage(path, this.get(i).FileName, this.get(i).HtmlText);
        }
        return res;
    }

    public static String getPattern(String value, Hashtable<String, String> emoticsDict, String path) {

        SmilesComparator bvc = new SmilesComparator(emoticsDict);
        TreeMap<String, String> sorted_map = new TreeMap<String, String>(bvc);
        sorted_map.putAll(emoticsDict);
        StringBuilder sb=new StringBuilder();
        for (Map.Entry<String, String> entry : sorted_map.entrySet()) {
            String emo = entry.getKey();
            if (!emo.startsWith(":") || !emo.endsWith(":")) {
                value = value.replaceAll("(^|\\s+)" + Pattern.quote(emo) + "($|\\s+)", String.format("$1$2", path, entry.getValue()));
            } else
                value = value.replaceAll("(^|.)" + Pattern.quote(emo) + "($|.)", String.format("$1$2", path, entry.getValue()));

        }
        return value;

    }

    public static Hashtable<String, String> getSmilesDict() {
        Hashtable<String, String> res = new Hashtable<String, String>();
        res.put(":happy:", "happy.gif");
        res.put(";)", "wink.gif");
        res.put(":P", "tongue.gif");
        res.put(":-D", "biggrin.gif");
        res.put(":lol:", "laugh.gif");
        res.put(":rolleyes:", "rolleyes.gif");
        res.put(":)", "smile_good.gif");
        res.put(":beee:", "beee.gif");
        res.put(":rofl:", "rofl.gif");
        res.put(":sveta:", "sveta.gif");
        res.put(":thank_you:", "thank_you.gif");
        res.put("}-)", "devil.gif");
        res.put(":girl_cray:", "girl_cray.gif");
        res.put(":D", "biggrin.gif");
        res.put("o.O", "blink.gif");
        res.put(":blush:", "blush.gif");
        res.put(":yes2:", "yes.gif");
        res.put(":mellow:", "mellow.gif");
        res.put(":huh:", "huh.gif");
        res.put(":o", "ohmy.gif");
        res.put("B)", "cool.gif");
        res.put("-_-", "sleep.gif");
        res.put("<_<", "dry.gif");
        res.put(":wub:", "wub.gif");
        res.put(":angry:", "angry.gif");
        res.put(":(", "sad.gif");
        res.put(":unsure:", "unsure.gif");
        res.put(":wacko:", "wacko.gif");
        res.put(":blink:", "blink.gif");
        res.put(":ph34r:", "ph34r.gif");
        res.put(":banned:", "banned.gif");
        res.put(":antifeminism:", "antifeminism.gif");
        res.put(":beta:", "beta.gif");
        res.put(":boy_girl:", "boy_girl.gif");
        res.put(":butcher:", "butcher.gif");
        res.put(":bubble:", "bubble.gif");
        res.put(":censored:", "censored.gif");
        res.put(":clap:", "clap.gif");
        res.put(":close_tema:", "close_tema.gif");
        res.put(":clapping:", "clapping.gif");
        res.put(":coldly:", "coldly.gif");
        res.put(":comando:", "comando.gif");
        res.put(":congratulate:", "congratulate.gif");
        res.put(":dance:", "dance.gif");
        res.put(":daisy:", "daisy.gif");
        res.put(":dancer:", "dancer.gif");
        res.put(":derisive:", "derisive.gif");
        res.put(":dinamo:", "dinamo.gif");
        res.put(":dirol:", "dirol.gif");
        res.put(":diver:", "diver.gif");
        res.put(":drag:", "drag.gif");
        res.put(":download:", "download.gif");
        res.put(":drinks:", "drinks.gif");
        res.put(":first_move:", "first_move.gif");
        res.put(":feminist:", "feminist.gif");
        res.put(":flood:", "flood.gif");
        res.put(":fool:", "fool.gif");
        res.put(":friends:", "friends.gif");
        res.put(":foto:", "foto.gif");
        res.put(":girl_blum:", "girl_blum.gif");
        res.put(":girl_crazy:", "girl_crazy.gif");
        res.put(":girl_curtsey:", "girl_curtsey.gif");
        res.put(":girl_dance:", "girl_dance.gif");
        res.put(":girl_flirt:", "girl_flirt.gif");
        res.put(":girl_hospital:", "girl_hospital.gif");
        res.put(":girl_hysterics:", "girl_hysterics.gif");
        res.put(":girl_in_love:", "girl_in_love.gif");
        res.put(":girl_kiss:", "girl_kiss.gif");
        res.put(":girl_pinkglassesf:", "girl_pinkglassesf.gif");
        res.put(":girl_parting:", "girl_parting.gif");
        res.put(":girl_prepare_fish:", "girl_prepare_fish.gif");
        res.put(":good:", "good.gif");
        res.put(":girl_spruce_up:", "girl_spruce_up.gif");
        res.put(":girl_tear:", "girl_tear.gif");
        res.put(":girl_tender:", "girl_tender.gif");
        res.put(":girl_teddy:", "girl_teddy.gif");
        res.put(":girl_to_babruysk:", "girl_to_babruysk.gif");
        res.put(":girl_to_take_umbrage:", "girl_to_take_umbrage.gif");
        res.put(":girl_triniti:", "girl_triniti.gif");
        res.put(":girl_tongue:", "girl_tongue.gif");
        res.put(":girl_wacko:", "girl_wacko.gif");
        res.put(":girl_werewolf:", "girl_werewolf.gif");
        res.put(":girl_witch:", "girl_witch.gif");
        res.put(":grabli:", "grabli.gif");
        res.put(":good_luck:", "good_luck.gif");
        res.put(":guess:", "guess.gif");
        res.put(":hang:", "hang.gif");
        res.put(":heart:", "heart.gif");
        res.put(":help:", "help.gif");
        res.put(":helpsmilie:", "helpsmilie.gif");
        res.put(":hemp:", "hemp.gif");
        res.put(":heppy_dancing:", "heppy_dancing.gif");
        res.put(":hysterics:", "hysterics.gif");
        res.put(":indeec:", "indeec.gif");
        res.put(":i-m_so_happy:", "i-m_so_happy.gif");
        res.put(":kindness:", "kindness.gif");
        res.put(":king:", "king.gif");
        res.put(":laugh_wild:", "laugh_wild.gif");
        res.put(":4PDA:", "love_4PDA.gif");
        res.put(":nea:", "nea.gif");
        res.put(":moil:", "moil.gif");
        res.put(":no:", "no.gif");
        res.put(":nono:", "nono.gif");
        res.put(":offtopic:", "offtopic.gif");
        res.put(":ok:", "ok.gif");
        res.put(":papuas:", "papuas.gif");
        res.put(":party:", "party.gif");
        res.put(":pioneer_smoke:", "pioneer_smoke.gif");
        res.put(":pipiska:", "pipiska.gif");
        res.put(":protest:", "protest.gif");
        res.put(":popcorm:", "popcorm.gif");
        res.put(":rabbi:", "rabbi.gif");
        res.put(":resent:", "resent.gif");
        res.put(":roll:", "roll.gif");
        res.put(":rtfm:", "rtfm.gif");
        res.put(":russian_garmoshka:", "russian_garmoshka.gif");
        res.put(":russian:", "russian.gif");
        res.put(":russian_ru:", "russian_ru.gif");
        res.put(":scratch_one-s_head:", "scratch_one-s_head.gif");
        res.put(":scare:", "scare.gif");
        res.put(":search:", "search.gif");
        res.put(":secret:", "secret.gif");
        res.put(":skull:", "skull.gif");
        res.put(":shok:", "shok.gif");
        res.put(":sorry:", "sorry.gif");
        res.put(":smoke:", "smoke.gif");
        res.put(":spiteful:", "spiteful.gif");
        res.put(":stop_flood:", "stop_flood.gif");
        res.put(":suicide:", "suicide.gif");
        res.put(":stop_holywar:", "stop_holywar.gif");
        res.put(":superman:", "superman.gif");
        res.put(":superstition:", "superstition.gif");
        res.put(":tablet_za:", "tablet_protiv.gif");
        res.put(":tablet_protiv:", "tablet_za.gif");
        res.put(":this:", "this.gif");
        res.put(":tomato:", "tomato.gif");
        res.put(":to_clue:", "to_clue.gif");
        res.put(":tommy:", "tommy.gif");
        res.put(":tongue3:", "tongue3.gif");
        res.put(":umnik:", "umnik.gif");
        res.put(":victory:", "victory.gif");
        res.put(":vinsent:", "vinsent.gif");
        res.put(":wallbash:", "wallbash.gif");
        res.put(":whistle:", "whistle.gif");
        res.put(":wink_kind:", "wink_kind.gif");
        res.put(":yahoo:", "yahoo.gif");
        res.put(":yes:", "yes.gif");
        res.put(":[", "confusion.gif");
        res.put("]-:{", "girl_devil.gif");
        res.put(":*", "kiss.gif");
        res.put("@}-'-,-", "give_rose.gif");
        res.put(":'(", "cry.gif");
        res.put(":-{", "mad.gif");
        res.put("=^.^=", "kitten.gif");
        res.put("(-=", "girl_hide.gif");
        res.put("(-;", "girl_wink.gif");
        res.put(")-:{", "girl_angry.gif");
        res.put("*-:", "girl_chmok.gif");
        res.put(")-:", "girl_sad.gif");
        res.put(":girl_mad:", "girl_mad.gif");
        res.put("(-:", "girl_smile.gif");
        res.put(":acute:", "acute.gif");
        res.put(":aggressive:", "aggressive.gif");
        res.put(":air_kiss:", "air_kiss.gif");
        res.put("o_O", "blink.gif");
        res.put(":-[", "confusion.gif");
        res.put(":'-(", "cry.gif");
        res.put(":lol_girl:", "girl_haha.gif");
        res.put(")-':", "girl_cray.gif");
        res.put("(;", "girl_wink.gif");
        res.put(":-*", "kiss.gif");
        res.put(":laugh:", "laugh.gif");
        res.put(":ohmy:", "ohmy.gif");
        res.put(":-(", "sad.gif");
        res.put("8-)", "rolleyes.gif");
        res.put(":-)", "smile.gif");
        res.put(":smile:", "smile.gif");
        res.put(":-P", "tongue.gif");
        res.put(";-)", "wink.gif");
        return res;
    }

    private void fill() {
        Hashtable<String, String> dict = getSmilesDict();

        for (Map.Entry<String, String> entry : dict.entrySet()) {
            add(new Smile(entry.getKey()
                    .replace("]", "]")
                    .replace("[", "[")
                    .replace("<", "<")
                    , entry.getValue()));
        }
    }

    public static Bitmap getBitmap(Context context, String filePath) throws IOException {
        return ExtBitmap.getBitmapFromAsset(context, filePath);
    }

}


text:
package com.thoughtworks.inproctester.htmlunit.exceptions;

public class UriRetrievalException extends RuntimeException {

	private static final long serialVersionUID = 6880840561805978802L;

	public UriRetrievalException(Exception e) {
		super(e);
	}
}


text:
class BuoyancyController : public PickingSceneController
{
private:
    typedef PickingSceneController Parent;

    /// The fluid area.
    b2AABB mFluidArea;

    /// The fluid density.
    F32 mFluidDensity;

    /// Fluid flow velocity for drag calculations.
    Vector2 mFlowVelocity;

    /// Linear drag co-efficient.
    F32 mLinearDrag;

    /// Linear drag co-efficient.
    F32 mAngularDrag;

    /// Gravity to use inside the fluid.
    Vector2 mFluidGravity;

    /// Whether to use the collision shape densities or assume a uniform density.
    bool mUseShapeDensity;

    /// The outer fluid surface normal.
    Vector2 mSurfaceNormal;

protected:
    F32 ComputeCircleSubmergedArea( const b2Transform& bodyTransform, const b2CircleShape* pShape, Vector2& center );
    F32 ComputePolygonSubmergedArea( const b2Transform& bodyTransform, const b2PolygonShape* pShape, Vector2& center );

public:
    BuoyancyController();
    virtual ~BuoyancyController();

    static void initPersistFields();
    virtual void copyTo(SimObject* object);

    /// Integration.
    virtual void integrate( Scene* pScene, const F32 totalTime, const F32 elapsedTime, DebugStats* pDebugStats );

    // Scene render.
    virtual void renderOverlay( Scene* pScene, const SceneRenderState* pSceneRenderState, BatchRender* pBatchRenderer );

    /// Declare Console Object.
    DECLARE_CONOBJECT( BuoyancyController );
};

#endif // _BUOYANCY_CONTROLLER_H_


text:
'use strict';

function main(projectId, location, sessionId) {
  // [START videostitcher_list_vod_ad_tag_details]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // projectId = 'my-project-id';
  // location = 'us-central1';
  // sessionId = 'my-session-id';

  // Imports the Video Stitcher library
  const {VideoStitcherServiceClient} =
    require('@google-cloud/video-stitcher').v1;
  // Instantiates a client
  const stitcherClient = new VideoStitcherServiceClient();

  async function listVodAdTagDetails() {
    // Construct request
    const request = {
      parent: stitcherClient.vodSessionPath(projectId, location, sessionId),
    };
    const iterable = await stitcherClient.listVodAdTagDetailsAsync(request);
    console.log('VOD ad tag details:');
    for await (const response of iterable) {
      console.log(response.name);
    }
  }

  listVodAdTagDetails();
  // [END videostitcher_list_vod_ad_tag_details]
}

// node listVodAdTagDetails.js <projectId> <location> <sessionId>
process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));


text:
package fc

import (
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"strings"

	"github.com/golang/glog"
	"k8s.io/kubernetes/pkg/volume"
)

type ioHandler interface {
	ReadDir(dirname string) ([]os.FileInfo, error)
	Lstat(name string) (os.FileInfo, error)
	EvalSymlinks(path string) (string, error)
	WriteFile(filename string, data []byte, perm os.FileMode) error
}

type osIOHandler struct{}

func (handler *osIOHandler) ReadDir(dirname string) ([]os.FileInfo, error) {
	return ioutil.ReadDir(dirname)
}
func (handler *osIOHandler) Lstat(name string) (os.FileInfo, error) {
	return os.Lstat(name)
}
func (handler *osIOHandler) EvalSymlinks(path string) (string, error) {
	return filepath.EvalSymlinks(path)
}
func (handler *osIOHandler) WriteFile(filename string, data []byte, perm os.FileMode) error {
	return ioutil.WriteFile(filename, data, perm)
}

// given a disk path like /dev/sdx, find the devicemapper parent
// TODO #23192 Convert this code to use the generic code in ../util
// which is used by the iSCSI implementation
func findMultipathDeviceMapper(disk string, io ioHandler) string {
	sys_path := "/sys/block/"
	if dirs, err := io.ReadDir(sys_path); err == nil {
		for _, f := range dirs {
			name := f.Name()
			if strings.HasPrefix(name, "dm-") {
				if _, err1 := io.Lstat(sys_path + name + "/slaves/" + disk); err1 == nil {
					return "/dev/" + name
				}
			}
		}
	}
	return ""
}

// given a wwn and lun, find the device and associated devicemapper parent
func findDisk(wwn, lun string, io ioHandler) (string, string) {
	fc_path := "-fc-0x" + wwn + "-lun-" + lun
	dev_path := "/dev/disk/by-path/"
	if dirs, err := io.ReadDir(dev_path); err == nil {
		for _, f := range dirs {
			name := f.Name()
			if strings.Contains(name, fc_path) {
				if disk, err1 := io.EvalSymlinks(dev_path + name); err1 == nil {
					arr := strings.Split(disk, "/")
					l := len(arr) - 1
					dev := arr[l]
					dm := findMultipathDeviceMapper(dev, io)
					return disk, dm
				}
			}
		}
	}
	return "", ""
}

// rescan scsi bus
func scsiHostRescan(io ioHandler) {
	scsi_path := "/sys/class/scsi_host/"
	if dirs, err := io.ReadDir(scsi_path); err == nil {
		for _, f := range dirs {
			name := scsi_path + f.Name() + "/scan"
			data := []byte("- - -")
			io.WriteFile(name, data, 0666)
		}
	}
}

// make a directory like /var/lib/kubelet/plugins/kubernetes.io/pod/fc/target-lun-0
func makePDNameInternal(host volume.VolumeHost, wwns []string, lun string) string {
	return path.Join(host.GetPluginDir(fcPluginName), wwns[0]+"-lun-"+lun)
}

type FCUtil struct{}

func (util *FCUtil) MakeGlobalPDName(fc fcDisk) string {
	return makePDNameInternal(fc.plugin.host, fc.wwns, fc.lun)
}

func searchDisk(wwns []string, lun string, io ioHandler) (string, string) {
	disk := ""
	dm := ""

	rescaned := false
	// two-phase search:
	// first phase, search existing device path, if a multipath dm is found, exit loop
	// otherwise, in second phase, rescan scsi bus and search again, return with any findings
	for true {
		for _, wwn := range wwns {
			disk, dm = findDisk(wwn, lun, io)
			// if multipath device is found, break
			if dm != "" {
				break
			}
		}
		// if a dm is found, exit loop
		if rescaned || dm != "" {
			break
		}
		// rescan and search again
		// rescan scsi bus
		scsiHostRescan(io)
		rescaned = true
	}
	return disk, dm
}

func (util *FCUtil) AttachDisk(b fcDiskMounter) error {
	devicePath := ""
	wwns := b.wwns
	lun := b.lun
	io := b.io
	disk, dm := searchDisk(wwns, lun, io)
	// if no disk matches input wwn and lun, exit
	if disk == "" && dm == "" {
		return fmt.Errorf("no fc disk found")
	}

	// if multipath devicemapper device is found, use it; otherwise use raw disk
	if dm != "" {
		devicePath = dm
	} else {
		devicePath = disk
	}
	// mount it
	globalPDPath := b.manager.MakeGlobalPDName(*b.fcDisk)
	noMnt, err := b.mounter.IsLikelyNotMountPoint(globalPDPath)
	if !noMnt {
		glog.Infof("fc: %s already mounted", globalPDPath)
		return nil
	}

	if err := os.MkdirAll(globalPDPath, 0750); err != nil {
		return fmt.Errorf("fc: failed to mkdir %s, error", globalPDPath)
	}

	err = b.mounter.FormatAndMount(devicePath, globalPDPath, b.fsType, nil)
	if err != nil {
		return fmt.Errorf("fc: failed to mount fc volume %s [%s] to %s, error %v", devicePath, b.fsType, globalPDPath, err)
	}

	return err
}

func (util *FCUtil) DetachDisk(c fcDiskUnmounter, mntPath string) error {
	if err := c.mounter.Unmount(mntPath); err != nil {
		return fmt.Errorf("fc detach disk: failed to unmount: %s\nError: %v", mntPath, err)
	}
	return nil
}


text:
package org.spongycastle.openpgp.operator;

import org.spongycastle.openpgp.PGPException;

public interface PGPContentVerifierBuilderProvider
{
    public PGPContentVerifierBuilder get(int keyAlgorithm, int hashAlgorithm)
        throws PGPException;
}


text:
@interface HMMapViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (weak, nonatomic) IBOutlet UIView *bottomControlView;
- (void)showUsers:(NSArray *)users;
@end


text:
package org.kie.dmn.feel.runtime.functions.twovaluelogic;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.kie.dmn.api.feel.runtime.events.FEELEvent;
import org.kie.dmn.feel.runtime.events.InvalidParametersEvent;
import org.kie.dmn.feel.runtime.functions.BaseFEELFunction;
import org.kie.dmn.feel.runtime.functions.FEELFnResult;
import org.kie.dmn.feel.runtime.functions.ParameterName;
import org.kie.dmn.feel.runtime.functions.SqrtFunction;
import org.kie.dmn.feel.util.EvalHelper;
import org.kie.dmn.model.api.GwtIncompatible;

// based on the examples of calculations, stddev is supposed to return sample standard deviation, not population standard deviation
@GwtIncompatible
public class NNStddevFunction
        extends BaseFEELFunction {
    public static final NNStddevFunction INSTANCE = new NNStddevFunction();

    NNStddevFunction() {
        super("nn stddev");
    }

    public FEELFnResult<BigDecimal> invoke(@ParameterName("list") List<?> list) {
        if ( list == null ) {
            return FEELFnResult.ofResult( null );
        }
        List<BigDecimal> numbers = new ArrayList<>( list.size() );
        for ( int i = 0; i < list.size(); i++ ) {
            Object value = list.get(i);
            if( value == null ) {
                // ignore null elements
                continue;
            }
            final BigDecimal val = EvalHelper.getBigDecimalOrNull(value);
            if ( val == null ) {
                // coercion to number failed
                return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "list", "an element in the list is not suitable for the stddev" ) );
            }
            numbers.add( val );
        }
        if( numbers.isEmpty() ) {
            return FEELFnResult.ofResult( null );
        }
        int count = numbers.size();
        BigDecimal total = BigDecimal.ZERO;
        for ( int i = 0; i < count; i++ ) {
            total = total.add( numbers.get( i ) );
        }
        BigDecimal mean = total.divide( BigDecimal.valueOf( numbers.size() ), MathContext.DECIMAL128 );
        total = BigDecimal.ZERO;
        for ( int i = 0; i < count; i++ ) {
            BigDecimal distanceSquared = numbers.get(i).subtract( mean ).pow( 2, MathContext.DECIMAL128 );
            total = total.add( distanceSquared );
        }
        mean = total.divide( BigDecimal.valueOf( count - 1L ), MathContext.DECIMAL128 );
        return FEELFnResult.ofResult( SqrtFunction.sqrt( mean ) );
    }

    public FEELFnResult<BigDecimal> invoke(@ParameterName("list") Object sole) {
        if ( sole == null ) {
            return FEELFnResult.ofResult( null );
        } else if( EvalHelper.getBigDecimalOrNull( sole ) == null ) {
            return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "list",
                    "the value can not be converted to a number" ) );
        }
        return FEELFnResult.ofError(new InvalidParametersEvent(FEELEvent.Severity.ERROR, "list",
                                                               "sample standard deviation of a single sample is undefined"));
    }

    public FEELFnResult<BigDecimal> invoke(@ParameterName("n") Object[] list) {
        if ( list == null ) {
            return FEELFnResult.ofResult( null );
        }

        return invoke( Arrays.asList( list ) );
    }
}


text:
typedef enum : NSUInteger {
  AXTabBarStyleDefault = 0,
  AXTabBarStyleVariableWidthButton,
} AXTabBarStyle;

@class AXTabBar;

@protocol AXTabBarDelegate <NSObject>
@optional
- (BOOL)tabBar:(AXTabBar *)tabBar shouldSelectItem:(UITabBarItem *)item;
- (void)tabBar:(AXTabBar *)tabBar didSelectItem:(UITabBarItem *)item;
@end

@interface AXTabBar : UIView
@property (copy, nonatomic) NSArray *items;
@property (assign, nonatomic) UITabBarItem *selectedItem;
@property (assign, nonatomic) id<AXTabBarDelegate> delegate;
@property (strong, nonatomic) UIFont *tabBarButtonFont;

// TODO: implement this style option.
//@property (nonatomic) AXTabBarStyle tabBarStyle;
@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>com.hotfixs.books.thinking-in-java</groupId>
        <artifactId>thinking-in-java</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>containers</artifactId>

    <dependencies>
        <dependency>
            <groupId>com.hotfixs.books.thinking-in-java</groupId>
            <artifactId>common</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>

</project>


text:
namespace mozc {

class ConversionRequest;
class POSMatcher;

class VariantsRewriter : public RewriterInterface {
 public:
  // Annotation constants.
  static const char *kHiragana;
  static const char *kKatakana;
  static const char *kNumber;
  static const char *kAlphabet;
  static const char *kKanji;
  static const char *kFullWidth;
  static const char *kHalfWidth;
  static const char *kPlatformDependent;
  static const char *kDidYouMean;
  static const char *kYenKigou;

  explicit VariantsRewriter(const POSMatcher *pos_matcher);
  virtual ~VariantsRewriter();
  virtual int capability(const ConversionRequest &request) const;
  virtual bool Rewrite(const ConversionRequest &request,
                       Segments *segments) const;
  virtual void Finish(const ConversionRequest &request, Segments *segments);
  virtual void Clear();

  // Used by UserSegmentHistoryRewriter.
  // TODO(noriyukit): I'd be better to prepare some utility for rewriters.
  static void SetDescriptionForCandidate(const POSMatcher &pos_matcher,
                                         Segment::Candidate *candidate);
  static void SetDescriptionForTransliteration(const POSMatcher &pos_matcher,
                                               Segment::Candidate *candidate);
  static void SetDescriptionForPrediction(const POSMatcher &pos_matcher,
                                          Segment::Candidate *candidate);

 private:
  // 1) Full width / half width description
  // 2) CharForm (hiragana/katakana) description
  // 3) Platform dependent char (JISX0213..etc) description
  // 4) Zipcode description (XXX-XXXX)
  //     * note that this overrides other descriptions
  enum DescriptionType {
    FULL_HALF_WIDTH = 1,   // automatically detect full/haflwidth.
    FULL_HALF_WIDTH_WITH_UNKNOWN = 2,  // set half/full widith for symbols.
    // This flag must be used together with FULL_HALF_WIDTH.
    // If WITH_UNKNOWN is specified, assign FULL/HALF width annotation
    // more aggressively.
    HALF_WIDTH = 4,        // always set half width description.
    FULL_WIDTH = 8,        // always set full width description.
    CHARACTER_FORM = 16,    // Hiragana/Katakana..etc
    PLATFORM_DEPENDENT_CHARACTER = 32,
    ZIPCODE = 64,
    SPELLING_CORRECTION = 128
  };

  enum RewriteType {
    EXPAND_VARIANT = 0,  // Expand variants
    SELECT_VARIANT = 1,  // Select preferred form
  };

  static void SetDescription(const POSMatcher &pos_matcher,
                             int description_type,
                             Segment::Candidate *candidate);
  bool RewriteSegment(RewriteType type, Segment *seg) const;

  const POSMatcher *pos_matcher_;
};

}  // namespace mozc

#endif  // MOZC_REWRITER_VARIANTS_REWRITER_H_


text:
class Episode
  include Mongoid::Document

  belongs_to :show
  has_many :releases, as: :releasable

  field :season, type: Integer
  field :number, type: Integer
  field :identifier

  field :title
  field :overview
  field :images, type: Hash

  field :trakt

  after_create :denormalize

  def denormalize
    self.update_attributes identifier: "#{show.title} S#{'%02d' % season}E#{'%02d' % number}"
  end
end


text:
package erogenousbeef.bigreactors.common.block;

import java.util.List;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import erogenousbeef.bigreactors.common.BigReactors;

public class BlockBROre extends Block {
	private IIcon iconYellorite;

	public BlockBROre()
	{
		super(Material.rock);
		this.setCreativeTab(BigReactors.TAB);
		this.setBlockName("brOre");
		this.setBlockTextureName(BigReactors.TEXTURE_NAME_PREFIX + "oreYellorite");
		this.setHardness(2f);
	}

	@Override
	public IIcon getIcon(int side, int metadata)
	{
		return this.iconYellorite;
	}

	@Override
	public void registerBlockIcons(IIconRegister par1IconRegister)
	{
		this.iconYellorite = par1IconRegister.registerIcon(BigReactors.TEXTURE_NAME_PREFIX + "oreYellorite");
	}

	@Override
	public int damageDropped(int metadata)
	{
		return metadata;
	}

	@Override
	public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List par3List)
	{
		par3List.add(new ItemStack(item, 1, 0));
	}
}


text:
title: spring容器的DefaultListableBeanFactory
tags: [spring]
---

该类是真正第一个可以独立的IOC容器,并且ApplicationContext也是依据它来建立。

1)介绍(查看类的英文注释)

只继承了一个抽象类,同时把集大成的接口ConfigurableListableBeanFactory给实现了,同时还有BeanDefinitionRegistry接口,从名字上看就知道是BeanDefinition的注册接口。

该类除了实现ConfigurableListableBeanFactory接口,间接实现了ListableBeanFactory子接口提供容器内bean实例的枚举功能,AutowireCapableBeanFactory子接口提供容器的自动配置功能,ConfigurableBeanFactory子接口提供了定义BeanFactory的配置,如类加载器,类型转化,属性编辑器等。

2)该类的继承体系

如果要在一个类中实现所有的接口是不现实的,也不方便代码的复用,因此DefaultListableBeanFactory继承了多个基类。

```
//AbstractAutowireCapableBeanFactory类实现了AutowireCapableBeanFactory接口,对自动装配接口进行了基本的实现

DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory(实现了AutowireCapableBeanFactory接口)

//AbstractBeanFactory类实现了ConfigurableBeanFactory接口,即对容器的配置信息进行基本实现。
AbstractAutowireCapableBeanFactory extends AbstractBeanFactory(实现了ConfigurableBeanFactory接口)

//FactoryBeanRegistrySupport具备了Register功能(该类也实现了很多接口)
AbstractBeanFactory extends FactoryBeanRegistrySupport
```

注:仔细理解类的继承体系,以及如何实现接口实现类的复用功能(很多接口都提供了abstract的实现模板),通过将这些abstract类按层次组合起来使用,从而达到代码实现的分离和复用,能够更方便的实现接口最小化原则(接口隔离原则)。


text:
package com.ciaoshen.thinkinjava.chapter14.pets;
import java.util.*;
import java.lang.reflect.*;

public class Manx extends Cat {
    public Manx(String name) { super(name); }
    public Manx() { super(); }
}


text:
"""

    wind.reactor
    ~~~~~~~~~~~~

    Handles io loop for serving client request.

"""

import errno
import socket
import select
import threading

from wind.exceptions import EWOULDBLOCK
from wind.driver import pick, PollEvents

class PollReactor(object):
    """Event reactor powering io multiplexing.

    Methods for the caller.

    - __init__(driver=None)
    - instance()
    - attach_handler()
    - update_handler()
    - remove_handler()
    - attach_callback()
    - run(poll_timeout=500)
    - stop()

    Methods can be overrided

    - initialize()

    """
    _NO_TIMEOUT = 0.0
    _DEFAULT_POLL_TIMEOUT = 500.0
    _singleton_lock = threading.Lock()

    def __init__(self, driver=None):
        """Event driven io loop using `poll`

        @param driver: Actual unix system call implementing io multiplexing

        """
        self._running = False
        self._handlers = {}
        self._events = {}
        self._driver = driver or pick()
        self._callbacks = []
        self.initialize()

    def initialize(self):
        """Initialize hook. Can be overrided"""
        self._setup_heartbeat()

    def _setup_heartbeat(self):
        """Initialize heartbeat for reactor instance and
        attach one byte handler.

        """
        self._heartbeat = Heartbeat()
        self.attach_handler(
            self._heartbeat.reader.fileno(), PollEvents.READ,
            self._heartbeat.read_handler)

    @staticmethod
    def exist():
        return hasattr(PollReactor, '_instance')

    @staticmethod
    def instance():
        """Initialize singleton instance of Reactor
        with double-checked locking

        Returns singleton reactor in `main thread`
        """
        if not PollReactor.exist():
            with PollReactor._singleton_lock:
                if not PollReactor.exist():
                    # Choose suitable driver here.
                    PollReactor._instance = PollReactor(driver=pick())
        return PollReactor._instance

    def attach_handler(self, fd, event_mask, handler):
        """Attach event handler to given fd.
        @param fd: file descriptor to be observed.
        @param event_mask: event to be observed.
        @param handler: handler to be executed when given event happens.

        """
        self._handlers[fd] = handler
        self._driver.register(fd, event_mask)

    def update_handler(self, fd, event_mask):
        """Update event handler to given fd.
        @param fd: file descriptor to be observed.
        @param event_mask: event to be observed.

        """
        self._driver.modify(fd, event_mask)

    def remove_handler(self, fd):
        """Remove event handler to given fd.
        @param fd: file descriptor to be observed.
        @param event_mask: event to be observed.

        """
        self._driver.unregister(fd)
        self._handlers.pop(fd, None)

    def attach_callback(self, callback):
        """Attach callback to `reactor`.
        Callback would be run in the next loop.
        If main thread is pending in `poll`, our heartbeat
        will force it to bypass `poll` immediately.

        """
        self._callbacks.append(callback)
        if hasattr(self, '_heartbeat'):
            self._heartbeat.begin()

    def _run_callback(self):
        for callback in self._callbacks:
            try:
                callback()
            except Exception:
                # TODO: Log exception.
                # We are eatting error!
                pass
        self._callbacks = []

    def run(self, poll_timeout=_DEFAULT_POLL_TIMEOUT):
        self._running = True
        while True:
            if not self._running:
                break
            timeout = poll_timeout
            self._run_callback()
            if self._callbacks:
                # If another callback is attached while running callback.
                timeout = self._NO_TIMEOUT

            # Poll returns `List` of (fd, event) tuple
            try:
                events = self._driver.poll(timeout)
            except (OSError, select.error) as e:
                if e.args[0] != errno.EINTR:
                    raise

            self._events.update(events)
            while self._events:
                fd, event_mask = self._events.popitem()
                handler = self._handlers.get(fd, None)
                if handler is None:
                    # XXX: should be handled properly
                    pass
                try:
                    handler(fd, event_mask)
                except TypeError:
                    # XXX: should be handled properly
                    raise

    def stop(self):
        self._running = False

Reactor = PollReactor

class Heartbeat(object):
    """Heartbeat for reactor.
    if another thread tries to attach callback while `reactor`
    is hanging inside the poll, we should bypass poll and rush
    into a next loop because callback may be executed in the next loop.
    We will force it by sending one byte request.

    Methods for the caller.

    - __init__()
    - begin()
    - end()
    - die()

    """
    def __init__(self):
        self._sock = None
        self._reader = None
        self._writer = None
        self._setup()

    @property
    def reader(self):
        return self._reader

    @property
    def writer(self):
        return self._writer

    @property
    def read_handler(self):
        return lambda fd, event_mask: self.end()

    def _setup(self):
        """Setup instant server for one byte communication.
        We don't care about a port number of instant server because
        it's not for accepting connection. OS will pick it up for us.

        """
        try:
            self._sock = socket.socket()
            self._sock.bind(('localhost', 0))
            self._sock.listen(1)
            self._writer = socket.socket()
            self._writer.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
            self._writer.connect(self._sock.getsockname())
            self._reader = self._sock.accept()[0]
            self._writer.setblocking(0)
            self._reader.setblocking(0)
            # Close instant socket because we don't need it anymore.
        except Exception:
            pass

    def begin(self):
        """Start new heartbeat, which will force reactor to run"""
        try:
            self._writer.send(b'q')
        except socket.error as e:
            if e.args[0] in EWOULDBLOCK:
                pass
            else:
                raise e

    def end(self):
        """This method is attached to reactor to finish one hearbeat cycle
        by receiving one byte from heartbeat writer.

        """
        try:
            while True:
                blood = self._reader.recv(1)
                if not blood:
                    # end of read
                    break
        except socket.error as e:
            if e.args[0] in EWOULDBLOCK:
                pass
            else:
                raise e

    def die(self):
        """Close all sockets"""
        self._sock.close()
        self._writer.close()
        self._reader.close()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SpaceTraffic.Entities;

namespace SpaceTraffic.Dao
{
    public class PlanItemEntityDAO : AbstractDAO, IPlanItemEntityDAO
    {
        public List<Entities.PlanItemEntity> GetPlanItemsByPathPlanId(int pathPlanId)
        {
            using (var contextDB = CreateContext())
            {
                var items = (from x in contextDB.PlanItem
						where x.PathPlanId.Equals(pathPlanId)
						select x);

                if (items == null)
                    return null;

                return items.OrderBy(x => x.SequenceNumber).ToList<PlanItemEntity>();
            }
        }

        public Entities.PlanItemEntity GetPlanItemById(int planItemID)
        {
            using (var contextDB = CreateContext())
            {
                return contextDB.PlanItem.FirstOrDefault(p => p.PlanItemId.Equals(planItemID));
            }
        }

        public int InsertPlanItem(Entities.PlanItemEntity planItem)
        {
            using (var contextDB = CreateContext())
            {
                try
                {
                    // add base to context
                    var itemDB = contextDB.PlanItem.Add(planItem);
                    // save context to database
                    contextDB.SaveChanges();
                    return itemDB.PlanItemId;
                }
                catch (Exception)
                {
                    return -1;
                }
            }
        }

        public bool RemovePlanItem(int planItemID)
        {
            using (var contextDB = CreateContext())
            {
                try
                {
                    var planItem = contextDB.PlanItem.FirstOrDefault(x => x.PlanItemId.Equals(planItemID));
                    // remove base to context
                    contextDB.PlanItem.Remove(planItem);
                    // save context to database
                    contextDB.SaveChanges();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
        }

        public bool UpdatePlanItemById(Entities.PlanItemEntity planItem)
        {
            using (var contextDB = CreateContext())
            {
                try
                {
                    var planItemDB = contextDB.PlanItem.FirstOrDefault(x => x.PlanItemId.Equals(planItem.PlanItemId));

                    planItemDB.SolarSystem = planItem.SolarSystem;
                    planItemDB.Index = planItem.Index;
                    planItemDB.IsPlanet = planItem.IsPlanet;
                    planItemDB.SequenceNumber = planItem.SequenceNumber;

                    // save context to database
                    contextDB.SaveChanges();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
        }
    }
}


text:
This inspection reports any uses Thread.dumpStack().
These are often temporary debugging statements, and should probably be either removed from production code,
or replaced by a more robust logging facility.

  Powered by InspectionGadgets


text:
require "daisybill_api/data/url"
require "daisybill_api/data/client"

module DaisybillApi
  module Data
  end
end


text:
using namespace std;
using namespace cnn::expr;
using namespace cnn;

namespace cnn {

enum { X2H=0, H2H, HB, L2H };

RNNBuilder::~RNNBuilder() {}

SimpleRNNBuilder::SimpleRNNBuilder(unsigned layers,
                       unsigned input_dim,
                       unsigned hidden_dim,
                       Model* model,
                       bool support_lags) : layers(layers), lagging(support_lags) {
  unsigned layer_input_dim = input_dim;
  for (unsigned i = 0; i < layers; ++i) {
    Parameters* p_x2h = model->add_parameters({hidden_dim, layer_input_dim});
    Parameters* p_h2h = model->add_parameters({hidden_dim, hidden_dim});
    Parameters* p_hb = model->add_parameters({hidden_dim});
    vector<Parameters*> ps = {p_x2h, p_h2h, p_hb};
    if (lagging)
        ps.push_back(model->add_parameters({hidden_dim, hidden_dim}));
    params.push_back(ps);
    layer_input_dim = hidden_dim;
  }
}

void SimpleRNNBuilder::new_graph_impl(ComputationGraph& cg) {
  param_vars.clear();
  for (unsigned i = 0; i < layers; ++i) {
    Parameters* p_x2h = params[i][X2H];
    Parameters* p_h2h = params[i][H2H];
    Parameters* p_hb = params[i][HB];
    Expression i_x2h =  parameter(cg,p_x2h);
    Expression i_h2h =  parameter(cg,p_h2h);
    Expression i_hb =  parameter(cg,p_hb);
    vector<Expression> vars = {i_x2h, i_h2h, i_hb};

    if (lagging) {
        Parameters* p_l2h = params[i][L2H];
        Expression i_l2h =  parameter(cg,p_l2h);
        vars.push_back(i_l2h);
    }

    param_vars.push_back(vars);
  }
}

void SimpleRNNBuilder::start_new_sequence_impl(const vector<Expression>& h_0) {
  h.clear();
  h0 = h_0;
  if (h0.size()) { assert(h0.size() == layers); }
}

Expression SimpleRNNBuilder::add_input_impl(int prev, const Expression &in) {
  const unsigned t = h.size();
  h.push_back(vector<Expression>(layers));

  Expression x = in;

  for (unsigned i = 0; i < layers; ++i) {
    const vector<Expression>& vars = param_vars[i];

    Expression y = affine_transform({vars[2], vars[0], x});

    if (prev == -1 && h0.size() > 0)
      y = y + vars[1] * h0[i];
    else if (prev >= 0)
      y = y + vars[1] * h[prev][i];

    x = h[t][i] = tanh(y);
  }
  return h[t].back();
}

Expression SimpleRNNBuilder::add_auxiliary_input(const Expression &in, const Expression &aux) {
  const unsigned t = h.size();
  h.push_back(vector<Expression>(layers));

  Expression x = in;

  for (unsigned i = 0; i < layers; ++i) {
    const vector<Expression>& vars = param_vars[i];
    assert(vars.size() >= L2H + 1);

    Expression y = affine_transform({vars[HB], vars[X2H], x, vars[L2H], aux});

    if (t == 0 && h0.size() > 0)
      y = y + vars[H2H] * h0[i];
    else if (t >= 1)
      y = y + vars[H2H] * h[t-1][i];

    x = h[t][i] = tanh(y);
  }
  return h[t].back();
}

void SimpleRNNBuilder::copy(const RNNBuilder & rnn) {
  const SimpleRNNBuilder & rnn_simple = (const SimpleRNNBuilder&)rnn;
  assert(params.size() == rnn_simple.params.size());
  for(size_t i = 0; i < rnn_simple.params.size(); ++i) {
      params[i][0]->copy(*rnn_simple.params[i][0]);
      params[i][1]->copy(*rnn_simple.params[i][1]);
      params[i][2]->copy(*rnn_simple.params[i][2]);
  }
}

} // namespace cnn


text:
import postcss from 'postcss'
import {join} from 'path'
import fs from 'fs'
import atImport from 'postcss-import'
import syntax from 'postcss-scss'
import calc from 'postcss-calc'
import simpleVars from 'postcss-simple-vars'

import { dirname } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));

const processor = postcss([
  atImport({path: ['src']}),
  collectVariables(),
  simpleVars({includePaths: [join(__dirname, '../src/support/variables')]})
])

async function analyzeVariables(fileName) {
  const contents = fs.readFileSync(fileName, 'utf8')

  const result = await processor.process(contents, {from: fileName, map: false, syntax})
  for (const message of result.messages) {
    if (message.plugin === 'postcss-simple-vars' && message.type === 'variable') {
      if (!result.variables[`$${message.name}`].values.includes(message.value)) {
        result.variables[`$${message.name}`].values.push(message.value)
      }
      let computed = message.value
      try {
        const c = `--temp-property: calc(${message.value})`.replace('round(', '(')
        computed = postcss().use(calc()).process(c).css
        computed = computed.replace('--temp-property: ', '')
      } catch (e) {
        // Couldn't calculate because value might not be a number
      }
      result.variables[`$${message.name}`].computed = computed
    }
  }
  return result.variables
}

function checkNode(node) {
  const allowedFuncts = ['var', 'round', 'cubic-bezier']
  const functMatch = node.value.match(/([^\s]*)\(/)
  let approvedMatch = true
  if (functMatch && !allowedFuncts.includes(functMatch[1])) {
    approvedMatch = false
  }
  return node.variable && approvedMatch
}

function collectVariables() {
  return {
    postcssPlugin: 'prepare-contents',
    prepare(result) {
      const variables = {}
      return {
        AtRule(atRule) {
          atRule.remove()
        },
        Comment(comment) {
          comment.remove()
        },
        Declaration(node) {
          if (checkNode(node)) {
            node.value = node.value.replace(' !default', '')
            const fileName = node.source.input.file.replace(`${process.cwd()}/`, '')
            variables[node.prop] = {
              // computed: value,
              values: [node.value],
              source: {
                path: fileName,
                line: node.source.start.line
              }
            }
          } else {
            node.remove()
          }
        },
        OnceExit() {
          result.variables = variables
        }
      }
    }
  }
}

export default analyzeVariables

;(async () => {
  const args = process.argv.slice(2)
  const file = args.length ? args.shift() : 'src/support/index.scss'
  const variables = await analyzeVariables(file)
  JSON.stringify(variables, null, 2)
})()


text:
<?php
namespace Hooloovoo\ORM\Generator\Persistence\TypeMapping\FieldDef;

/**
 * Interface FieldDefInterface
 */
interface FieldDefInterface
{
    /**
     * @return array
     */
    public function getImports() : array ;

    /**
     * @param string $name
     * @return string
     */
    public function getAnnotation($name) : string ;

    /**
     * @param string $name
     * @return string
     */
    public function getDeclaration(string $name) : string ;

    /**
     * @param string $name
     * @return string
     */
    public function getInstanceCreation(string $name) : string ;
}


text:
package net.nemerosa.ontrack.model.security;

@CoreFunction
public interface BranchDelete extends ProjectFunction {
}


text:
/// <reference path="../../Scripts/typings/requirejs/require.d.ts"/>
require(["../config"], () => {
    require(["../Samples/GraphFromJson/app"]), () => {
    }
});


text:
"use strict";

// This test suite covers various handshake patterns.
// Making an object live demands a connection to an uplink.
// A connection starts with a handshake synchronizing versions on both ends.
// Depending on who has state and who does not, versions on both ends,
// also various concurrency/asynchrony issues, handshakes proceed in different
// ways.

var env = require('../lib/env');
var Spec = require('../lib/Spec');
var Host = require('../lib/Host');
var Model = require('../lib/Model');
var Storage = require('../lib/Storage');
require('./model/Mice');

env.multihost = true;

/** Must be constructed from String, serialized into a String.
    JSON string is OK :) */
function FullName (name) {
    var m = name.match(/(\S+)\s+(.*)/);
    this.first = m[1];
    this.last = m[2];
}
FullName.prototype.toString = function () {
    return this.first + ' ' + this.last;
};

var Mouse = Model.extend('Mouse', {
    defaults: {
        x: 0,
        y: 0
        //name: FullName
    },
    // adapted to handle the $$move op
    /*TODO_distillLog: function () {
        // explain
        var sets = [],
            cumul = {},
            heads = {},
            spec;
        for(spec in this._oplog) {
            if (Spec.get(spec, '.') === '.set') {
                sets.push(spec);
            }
        }
        sets.sort();
        for(var i=sets.length-1; i>=0; i--) {
            spec = sets[i];
            var val = this._oplog[spec], notempty=false;
            for(var key in val) {
                if (key in cumul) {
                    delete val[key];
                } else {
                    notempty = cumul[key] = true;
                }
            }
            var source = new Spec(key).source();
            notempty || (heads[source] && delete this._oplog[spec]);
            heads[source] = true;
        }
        return cumul;
    },*/
    ops: {
        move: function (spec,d) {
            // To implement your own ops you must understand implications
            // of partial order; in this case, if an op comes later than
            // an op that overwrites it then we skip it.
            var version = spec.version();
            if (version<this._version) {
                for(var opspec in this._oplog) {
                    if (opspec > '!' + version) {
                        var os = new Spec(opspec);
                        if (os.op() === 'set' && os.version() > version) {
                            return; // overwritten in the total order
                        }
                    }
                }
            }
            // Q if set is late => move is overwritten!
            this.x += d.x||0;
            this.y += d.y||0;
        }
    }
});

//    S O  I T  F I T S

asyncTest('6.a Handshake K pattern', function () {
    console.warn(QUnit.config.current.testName);

    var storage = new Storage(true);
    var uplink = new Host('uplink~K',0,storage);
    var downlink = new Host('downlink~K',100);
    uplink.getSources = function () {return [storage];};
    downlink.getSources = function () {return [uplink];};
    uplink.on(downlink);

    env.localhost = uplink;
    var uprepl = new Mouse({x:3,y:3});
    downlink.on(uprepl.spec()+'.init',function(sp,val,obj){
        //  ? register ~ on ?
        //  host ~ event hub
        //    the missing signature: x.emit('event',value),
        //      x.on('event',fn)
        //    host.on(Mouse,fn)
        //    host.on(Mouse) -- is actually a value
        //  on() with a full filter:
        //    /Mouse#Mickey!now.on   !since.event   callback
        //  host's completely specd filter
        //    /Host#local!now.on   /Mouse#Mickey!since.event   callback
        equal(obj.x,3);
        equal(obj.y,3);
        equal(obj._version,uprepl._version);
        // TODO this happens later ok(storage..init[uprepl.spec()]);
        start();
    });
    //var dlrepl = downlink.objects[uprepl.spec()];

    // here we have sync retrieval, so check it now
    //equal(dlrepl.x,3);
    //equal(dlrepl.y,3);
    //equal(dlrepl._version,dlrepl._id);
    // NO WAY, storage is async
});

asyncTest('6.b Handshake D pattern', function () {
    console.warn(QUnit.config.current.testName);

    var storage = new Storage(true);
    var uplink = new Host('uplink~D',0,storage);
    var downlink = new Host('downlink~D',10000);
    uplink.getSources = function () {return [storage];};
    downlink.getSources = function () {return [uplink];};
    uplink.on(downlink);
    env.localhost = downlink;

    storage.states['/Mouse#Mickey'] = JSON.stringify({
        x:7,
        y:7,
        _version: '!0eonago',
        _oplog:{
            '!0eonago.set': {x:7,y:7}
        }
    });

    // TODO
    //  * _version: !v1!v2
    //    v * add Spec.Map.toString(trim) {rot:ts,top:count}
    //      * if new op !vid was trimmed => add manually
    //      * if new op vid < _version => check the log (.indexOf(src))
    //    v * sort'em
    //  * clean $$set
    //  * add testcase: Z-rotten
    //      * old replica with no changes (no rot)
    //      * old repl one-side changes
    //      * old repl two-side changes (dl is rotten)
    //  * document it
    //  * "can't remember whether this was applied" situation
    //      * high concurrency offline use
    //
    //  The underlying assumption: either less than 5 entities
    //  touch it or they don't do it at once (if your case is
    //  different consider RPC impl)
    //  Model.ROTSPAN
    //  Model.COAUTH

    downlink.on('/Mouse#Mickey.init',function(spec,val,obj){
        equal(obj._id,'Mickey');
        equal(obj.x,7);
        equal(obj.y,7);
        equal(obj._version,'!0eonago');
        start();
    });
    var dlrepl = downlink.objects['/Mouse#Mickey'];

    // storage is async, waits a tick
    ok(!dlrepl.x);
    ok(!dlrepl.y);

});

// both uplink and downlink have unsynchronized changes
asyncTest('6.c Handshake Z pattern', function () {
    console.warn(QUnit.config.current.testName);

    var storage = new Storage(false);
    var oldstorage = new Storage(false);
    var uplink = new Host('uplink~Z',0,storage);
    var downlink = new Host('downlink~Z');
    uplink.getSources = function () {return [storage];};
    downlink.getSources = function () {return [oldstorage];};

    var oldMickeyState = {
        x:7,
        y:7,
        _version: '!0eonago',
        _oplog:{
            '!0eon+ago.set' : {y:7},
            '!000ld+old.set': {x:7}
        }
    };
    storage.states['/Mouse#Mickey'] = JSON.stringify(oldMickeyState);
    oldstorage.states['/Mouse#Mickey'] = JSON.stringify(oldMickeyState);

    // new ops at the uplink' storage
    storage.tails['/Mouse#Mickey'] =
        {
            '!1ail+old.set': JSON.stringify({y:10})
        };

    env.localhost = downlink;

    var dlrepl = new Mouse('Mickey',oldMickeyState);
    uplink.on('/Mouse#Mickey');
    var uprepl = uplink.objects[dlrepl.spec()];

    // offline changes at the downlink
    dlrepl.set({x:12});

    // ...we see the tail applied, downlink changes not here yet
    equal(uprepl.x,7);
    equal(uprepl.y,10);

    // Two uplinks! The "server" and the "cache".
    downlink.getSources = function () { return [oldstorage,uplink]; };
    console.warn('connect');
    uplink.on(downlink);

    // their respective changes must merge
    equal(dlrepl.x,12);
    equal(dlrepl.y,10);
    equal(uprepl.x,12);
    equal(uprepl.y,10);

    start();

});

asyncTest('6.d Handshake R pattern', function () {
    console.warn(QUnit.config.current.testName);

    var storage = new Storage(false);
    var uplink = new Host('uplink~R');
    var downlink = new Host('downlink~R');
    uplink.getSources = function () {return [storage];};
    downlink.getSources = function () {return [uplink];};
    uplink.on(downlink);
    env.localhost = downlink;

    downlink.on('/Mouse#Mickey.init',function(spec,val,dlrepl){
        // there is no state in the uplink, dl provided none as well
        ok(!dlrepl.x);
        ok(!dlrepl.y);
        equal(dlrepl._version,'!0'); // auth storage has no state

        dlrepl.set({x:18,y:18}); // FIXME this is not R
        var uprepl = uplink.objects['/Mouse#Mickey'];
        equal(uprepl.x,18);

        start();
    });

});

asyncTest('6.e Handshake A pattern', function () {
    console.warn(QUnit.config.current.testName);

    var storage = new Storage(false);
    var uplink = new Host('uplink~A');
    var downlink = new Host('downlink~A');
    uplink.getSources = function () {return [storage];};
    downlink.getSources = function () {return [uplink];};
    uplink.on(downlink);
    env.localhost = downlink;

    var mickey = new Mouse({x:20,y:20});
    equal(mickey._id, mickey._version.substr(1));

    // FIXME no value push; this is R actually
    setTimeout(function check(){
        var uprepl = uplink.objects[mickey.spec()];
        var dlrepl = downlink.objects[mickey.spec()];
        equal(uprepl.x,20);
        equal(uprepl.y,20);
        equal(dlrepl.x,20);
        equal(dlrepl.y,20);
        start();
    }, 100);

});

test('6.f Handshake and sync', function () {
    console.warn(QUnit.config.current.testName);

    var storage = new Storage(false);
    var uplink = new Host('uplink~F',0,storage);
    var downlink1 = new Host('downlink~F1');
    var downlink2 = new Host('downlink~F2');
    uplink.getSources = function () {return [storage];};
    downlink1.getSources = function () {return [uplink];};
    downlink2.getSources = function () {return [uplink];};

    uplink.on(downlink1);

    env.localhost = downlink1;

    var miceA = downlink1.get('/Mice#mice');
    var miceB = downlink2.get('/Mice#mice');

    var mickey1 = downlink1.get('/Mouse');
    var mickey2 = downlink2.get('/Mouse');
    miceA.addObject(mickey1);

    uplink.on(downlink2);

    var mickey1at2 = miceB.objects[mickey1.spec()];
    ok(miceA.objects[mickey1.spec()]);
    ok(mickey1at2);
    miceB.addObject(mickey2);

    var mickey2at1 = miceA.objects[mickey2.spec()];
    ok(miceB.objects[mickey2.spec()]);
    ok(mickey2at1);

    mickey1.set({x:0xA});
    mickey2.set({x:0xB});
    equal(mickey1at2.x,0xA);
    equal(mickey2at1.x,0xB);

    mickey1at2.set({y:0xA});
    mickey2at1.set({y:0xB});
    equal(mickey1.y,0xA);
    equal(mickey2.y,0xB);
});

asyncTest('6.g Cache vs storage',function () {
    var storage = new Storage(true);
    var cache = new Storage(false);
    cache.isRoot = false;
    var uplink = new Host('uplink~G',0,storage);
    var downlink = new Host('downlink~G',0,cache);
    downlink.getSources = function () {return [uplink];};

    env.localhost = uplink;
    var mickey = new Mouse({x:1,y:2});

    //env.localhost = downlink;
    var copy = downlink.get(mickey.spec());
    copy.on('.init', function (){
        equal(copy.x,1);
        equal(copy.y,2);
        start();
    });

});


text:
/******************************************
Generated by Intentor.Yamapper Class Generator
http://intentor.com.br/projects/yamapper/
******************************************/
using System;
using System.Collections.Generic;
using Intentor.Examples.Model.Core.Entities;

namespace Intentor.Examples.Model.Core.DataInterfaces
{
	/// <summary>
	/// Data interface IProdutoRepository utilizada para métodos customizados.
	/// </summary>
	public partial interface IProdutoRepository
	{

	}
}


text:
int main(void)
{
    size_t failedTestCount = 0;
    RUN_TEST_SUITE(doublylinkedlist_unittests, failedTestCount);
    return failedTestCount;
}


text:
package com.bnade.wow.entity;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import javax.persistence.Entity;
import javax.persistence.Id;

/**
 * 服务器相关信息
 * Created by liufeng0103@163.com on 2017/6/16.
 */
@Entity
@JsonIgnoreProperties(value = {"url", "name"})
public class Realm {
    @Id
    private Integer id;
    private String name;
    private String type;
    private String url;
    private Long lastModified;
    private Long interval;
    private Integer auctionQuantity;
    private Integer ownerQuantity;
    private Integer itemQuantity;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Long getLastModified() {
        return lastModified;
    }

    public void setLastModified(Long lastModified) {
        this.lastModified = lastModified;
    }

    public Long getInterval() {
        return interval;
    }

    public void setInterval(Long interval) {
        this.interval = interval;
    }

    public Integer getAuctionQuantity() {
        return auctionQuantity;
    }

    public void setAuctionQuantity(Integer auctionQuantity) {
        this.auctionQuantity = auctionQuantity;
    }

    public Integer getOwnerQuantity() {
        return ownerQuantity;
    }

    public void setOwnerQuantity(Integer ownerQuantity) {
        this.ownerQuantity = ownerQuantity;
    }

    public Integer getItemQuantity() {
        return itemQuantity;
    }

    public void setItemQuantity(Integer itemQuantity) {
        this.itemQuantity = itemQuantity;
    }

    @Override
    public String toString() {
        return "Realm{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", type='" + type + '\'' +
                ", url='" + url + '\'' +
                ", lastModified=" + lastModified +
                ", interval=" + interval +
                ", auctionQuantity=" + auctionQuantity +
                ", ownerQuantity=" + ownerQuantity +
                ", itemQuantity=" + itemQuantity +
                '}';
    }
}


text:
$(function(){
    $(window).load(function(){
        "use strict";

        // set your google maps parameters
        var $latitude = -6.193948, //If you unable to find latitude and longitude of your address. Please visit http://www.latlong.net/convert-address-to-lat-long.html you can easily generate.
            $longitude = 106.849184,
            $map_zoom = 16; /* ZOOM SETTING */

        // google map custom marker icon
        var $marker_url = '../assets/img/map-marker.png';

        // we define here the style of the map
        var style = [{
            "stylers": [{
                "hue": "#00aaff"
            }, {
                "saturation": -100
            }, {
                "gamma": 2.15
            }, {
                "lightness": 12
            }]
        }];

        // set google map options
        var map_options = {
            center: new google.maps.LatLng($latitude, $longitude),
            zoom: $map_zoom,
            panControl: true,
            zoomControl: true,
            mapTypeControl: false,
            streetViewControl: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            scrollwheel: false,
            styles: style
        };

        // inizialize the map
        var map = new google.maps.Map(document.getElementById('google-container'), map_options);

        //add a custom marker to the map
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng($latitude, $longitude),
            map: map,
            visible: true,
            icon: $marker_url
        });
    });
});


text:
package com.facebook.buck.android;

import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.Step;
import com.google.common.base.Joiner;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;

/**
 * Takes in a list of files and outputs a
 * concatenation of them in the same directory. Used for solid compression
 * into a single .xz. Does NOT delete source files after concatenating.
 */
public class ConcatStep implements Step {

  public static final String SHORT_NAME = "cat";
  private final Supplier<ImmutableList<Path>> inputs;
  private final Path output;

  /**
   * Use this constructor if the files to concatenate are known at the time of step creation.
   * @param inputs The files to be concatenated
   * @param outputPath The desired output path.
   */
  public ConcatStep(ImmutableList<Path> inputs, Path outputPath) {
    this.inputs = Suppliers.ofInstance(inputs);
    output = outputPath;
  }

  /**
   * Use this constructor if the files to concatenate are not known at the time of step creation.
   * @param inputsBuilder The files to be concatenated, in builder form
   * @param outputPath The desired output path.
   */
  public ConcatStep(final ImmutableList.Builder<Path> inputsBuilder, Path outputPath) {
    this.inputs = Suppliers.memoize(new Supplier<ImmutableList<Path>>() {
                                      @Override
                                      public ImmutableList<Path> get() {
                                        return inputsBuilder.build();
                                      }
                                    });
    output = outputPath;
  }

  @Override
  public int execute(ExecutionContext context) {
    ImmutableList<Path> list = inputs.get();
    try (
        OutputStream out = context.getProjectFilesystem().newFileOutputStream(output);
    ) {
      for (Path p : list) {
        context.getProjectFilesystem().copyToOutputStream(p, out);
      }
      out.flush();
    } catch (IOException e) {
      context.logError(e, "There was an error in concat step");
      return 1;
    }
    return 0;
  }

  @Override
  public String getShortName() {
    return SHORT_NAME;
  }

  @Override
  public String getDescription(ExecutionContext context) {
    ImmutableList<Path> list = inputs.get();
    ImmutableList.Builder<String> desc = ImmutableList.builder();
    desc.add(getShortName());
    for (Path p : list) {
      desc.add(p.toString());
    }
    desc.add(">");
    desc.add(output.toString());
    return Joiner.on(" ").join(desc.build());

  }
}