text:
package turnpike

import (
	"errors"
	"net/http"
	"runtime"
	"testing"
	"time"
)

func TestClient_CallResult(t *testing.T) {
	s := NewServer()
	s.RegisterRPC("rpc:test_result",
		func(client, uri string, args ...interface{}) (interface{}, error) {
			return "ok", nil
		})
	http.Handle("/ws1", s.Handler)
	// TODO: needs better way of running multiple listen and serve.
	// Currently there is no way of closing the listener. A cusom server and
	// handler will work but requires more work. TBD.
	go func() {
		err := http.ListenAndServe(":8001", nil)
		if err != nil {
			t.Fatal("ListenAndServe: " + err.Error())
		}
	}()

	// Let the server goroutine start.
	runtime.Gosched()

	c := NewClient()
	err := c.Connect("ws://127.0.0.1:8001/ws1", "http://localhost/")
	if err != nil {
		t.Fatal("error connecting: " + err.Error())
	}

	resultCh := c.Call("rpc:test_result")
	r := <-resultCh
	if r.Error != nil {
		t.Error(r.Error)
	}
	if r.Result != "ok" {
		t.Fail()
	}
}

func TestClient_CallRestultGenericError(t *testing.T) {
	s := NewServer()
	s.RegisterRPC("rpc:test_generic_error",
		func(client, uri string, args ...interface{}) (interface{}, error) {
			return nil, errors.New("error")
		})
	http.Handle("/ws2", s.Handler)
	go func() {
		err := http.ListenAndServe(":8002", nil)
		if err != nil {
			t.Fatal("ListenAndServe: " + err.Error())
		}
	}()

	runtime.Gosched()

	c := NewClient()
	err := c.Connect("ws://127.0.0.1:8002/ws2", "http://localhost/")
	if err != nil {
		t.Fatal("error connecting: " + err.Error())
	}

	resultCh := c.Call("rpc:test_generic_error")
	r := <-resultCh
	if r.Result != nil {
		t.Fail()
	}
	if r.Error.Error() != "turnpike: RPC error with URI rpc:test_generic_error#generic-error: error" {
		t.Fail()
	}
}

func TestClient_CallRestultCustomError(t *testing.T) {
	s := NewServer()
	s.RegisterRPC("rpc:test_custom_error",
		func(client, uri string, args ...interface{}) (interface{}, error) {
			return nil, RPCError{uri, "custom error", nil}
		})
	http.Handle("/ws3", s.Handler)
	go func() {
		err := http.ListenAndServe(":8003", nil)
		if err != nil {
			t.Fatal("ListenAndServe: " + err.Error())
		}
	}()

	runtime.Gosched()

	c := NewClient()
	err := c.Connect("ws://127.0.0.1:8003/ws3", "http://localhost/")
	if err != nil {
		t.Fatal("error connecting: " + err.Error())
	}

	resultCh := c.Call("rpc:test_custom_error")
	r := <-resultCh
	if r.Result != nil {
		t.Fail()
	}
	if r.Error.Error() != "turnpike: RPC error with URI rpc:test_custom_error: custom error" {
		t.Fail()
	}
}

func TestClient_Event(t *testing.T) {
	s := NewServer()
	http.Handle("/ws4", s.Handler)
	// TODO: needs better way of running multiple listen and serve.
	// Currently there is no way of closing the listener. A cusom server and
	// handler will work but requires more work. TBD.
	go func() {
		err := http.ListenAndServe(":8004", nil)
		if err != nil {
			t.Fatal("ListenAndServe: " + err.Error())
		}
	}()

	// Let the server goroutine start.
	runtime.Gosched()

	c := NewClient()
	err := c.Connect("ws://127.0.0.1:8004/ws4", "http://localhost/")
	if err != nil {
		t.Fatal("error connecting: " + err.Error())
	}

	eventCh := make(chan bool)
	c.Subscribe("event:test", func(uri string, event interface{}) {
		eventCh <- true
	})

	c.Publish("event:test", "test")

	select {
	case <-eventCh:
		return
	case <-time.After(time.Second):
		t.Fail()
	}
}


text:
@implementation GoldPriceTableViewCell

- (void)setValuesForData:(NSArray *)data
{
    self.dateLabel.text = data.firstObject;
    self.valueLabel.text = [NSString stringWithFormat:@"%@", data.lastObject];
}

@end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace SubscribePro\Tests\Service\Customer;

use SubscribePro\Service\Customer\CustomerInterface;
use SubscribePro\Service\Customer\CustomerService;

class CustomerServiceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \SubscribePro\Service\Customer\CustomerService
     */
    protected $customerService;

    /**
     * @var \SubscribePro\Service\DataFactoryInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $customerFactoryMock;

    /**
     * @var \SubscribePro\Http|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $httpClientMock;

    protected function setUp()
    {
        $this->httpClientMock = $this->getMockBuilder('SubscribePro\Http')
            ->disableOriginalConstructor()
            ->getMock();

        $this->customerFactoryMock = $this->getMockBuilder('SubscribePro\Service\DataFactoryInterface')->getMock();

        $this->customerService = new CustomerService($this->httpClientMock, $this->customerFactoryMock);
    }

    public function testCreateCustomer()
    {
        $customerMock = $this->createCustomerMock();
        $customerData = [
            CustomerInterface::EMAIL => 'email@example.com',
            CustomerInterface::ID => 123,
        ];

        $this->customerFactoryMock->expects($this->once())
            ->method('create')
            ->with($customerData)
            ->willReturn($customerMock);

        $this->assertSame($customerMock, $this->customerService->createCustomer($customerData));
    }

    /**
     * @expectedException \SubscribePro\Exception\EntityInvalidDataException
     * @expectedExceptionMessage Not all required fields are set.
     */
    public function testFailToSaveCustomerIfNotValid()
    {
        $customerMock = $this->createCustomerMock();
        $customerMock->expects($this->once())
            ->method('isValid')
            ->willReturn(false);

        $this->httpClientMock->expects($this->never())->method('post');

        $this->customerService->saveCustomer($customerMock);
    }

    /**
     * @param string $url
     * @param string $itemId
     * @param bool $isNew
     * @param array $formData
     * @param array $resultData
     * @dataProvider saveCustomerDataProvider
     */
    public function testSaveCustomer($url, $itemId, $isNew, $formData, $resultData)
    {
        $customerMock = $this->createCustomerMock();
        $customerMock->expects($this->once())->method('isValid')->willReturn(true);
        $customerMock->expects($this->once())->method('isNew')->willReturn($isNew);
        $customerMock->expects($this->once())->method('getFormData')->willReturn($formData);
        $customerMock->expects($this->any())->method('getId')->willReturn($itemId);
        $customerMock->expects($this->once())
            ->method('importData')
            ->with($resultData)
            ->willReturnSelf();

        $this->httpClientMock->expects($this->once())
            ->method('post')
            ->with($url, [CustomerService::API_NAME_CUSTOMER => $formData])
            ->willReturn([CustomerService::API_NAME_CUSTOMER => $resultData]);

        $this->assertSame($customerMock, $this->customerService->saveCustomer($customerMock));
    }

    /**
     * @return array
     */
    public function saveCustomerDataProvider()
    {
        return [
            'Save new customer' => [
                'url' => '/services/v2/customer.json',
                'itemId' => null,
                'isNew' => true,
                'formData' => [CustomerInterface::EMAIL => 'email@example.com'],
                'resultData' => [CustomerInterface::ID => 11],
            ],
            'Update existing customer' => [
                'url' => '/services/v2/customers/22.json',
                'itemId' => 22,
                'isNew' => false,
                'formData' => [CustomerInterface::EMAIL => 'email@example.com'],
                'resultData' => [CustomerInterface::ID => 22],
            ],
        ];
    }

    public function testLoadCustomer()
    {
        $itemId = 111;
        $itemData = [
            CustomerInterface::ID => $itemId,
            CustomerInterface::EMAIL => 'email@example.com',
        ];
        $customerMock = $this->createCustomerMock();

        $this->httpClientMock->expects($this->once())
            ->method('get')
            ->with("/services/v2/customers/{$itemId}.json")
            ->willReturn([CustomerService::API_NAME_CUSTOMER => $itemData]);

        $this->customerFactoryMock->expects($this->once())
            ->method('create')
            ->with($itemData)
            ->willReturn($customerMock);

        $this->assertSame($customerMock, $this->customerService->loadCustomer($itemId));
    }

    /**
     * @expectedException \SubscribePro\Exception\InvalidArgumentException
     * @expectedExceptionMessageRegExp /Only \[[a-z,_ ]+\] query filters are allowed./
     */
    public function testFailToLoadCustomersIfFilterIsNotValid()
    {
        $filters = ['invalid_key' => 'value'];

        $this->httpClientMock->expects($this->never())->method('get');

        $this->customerService->loadCustomers($filters);
    }

    /**
     * @param array $filters
     * @param array $itemsData
     * @dataProvider loadCustomersDataProvider
     */
    public function testLoadCustomers($filters, $itemsData)
    {
        $this->httpClientMock->expects($this->once())
            ->method('get')
            ->with('/services/v2/customers.json', $filters)
            ->willReturn([CustomerService::API_NAME_CUSTOMERS => $itemsData]);

        $customers = [];
        $customerFactoryMap = [];
        foreach ($itemsData as $itemData) {
            $customer = $this->createCustomerMock();
            $customerFactoryMap[] = [$itemData, $customer];
            $customers[] = $customer;
        }
        $this->customerFactoryMock->expects($this->exactly(count($itemsData)))
            ->method('create')
            ->willReturnMap($customerFactoryMap);

        $this->assertSame($customers, $this->customerService->loadCustomers($filters));
    }

    /**
     * @return array
     */
    public function loadCustomersDataProvider()
    {
        return [
            'Loading without filter' => [
                'filters' => [],
                'itemsData' => [[CustomerInterface::ID => 111], [CustomerInterface::ID => 222]],
            ],
            'Loading by first name' => [
                'filters' => [CustomerInterface::FIRST_NAME => 'John'],
                'itemsData' => [[CustomerInterface::ID => 333, CustomerInterface::FIRST_NAME => 'John']],
            ],
        ];
    }

    /**
     * @return \SubscribePro\Service\Customer\CustomerInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    private function createCustomerMock()
    {
        return $this->getMockBuilder('SubscribePro\Service\Customer\CustomerInterface')->getMock();
    }
}


text:
namespace org {
  namespace apache {
    namespace lucene {
      namespace search {
        class BooleanQuery;
      }
    }
  }
}
namespace java {
  namespace lang {
    class Class;
  }
}
template<class T> class JArray;

namespace org {
  namespace apache {
    namespace lucene {
      namespace search {

        class MultiTermQuery$ConstantScoreAutoRewrite : public ::org::apache::lucene::search::ConstantScoreAutoRewrite {
        public:
          enum {
            mid_init$_54c6a166,
            max_mid
          };

          static ::java::lang::Class *class$;
          static jmethodID *mids$;
          static bool live$;
          static jclass initializeClass(bool);

          explicit MultiTermQuery$ConstantScoreAutoRewrite(jobject obj) : ::org::apache::lucene::search::ConstantScoreAutoRewrite(obj) {
            if (obj != NULL)
              env->getClass(initializeClass);
          }
          MultiTermQuery$ConstantScoreAutoRewrite(const MultiTermQuery$ConstantScoreAutoRewrite& obj) : ::org::apache::lucene::search::ConstantScoreAutoRewrite(obj) {}

          MultiTermQuery$ConstantScoreAutoRewrite();
        };
      }
    }
  }
}

#include <Python.h>

namespace org {
  namespace apache {
    namespace lucene {
      namespace search {
        extern PyTypeObject PY_TYPE(MultiTermQuery$ConstantScoreAutoRewrite);

        class t_MultiTermQuery$ConstantScoreAutoRewrite {
        public:
          PyObject_HEAD
          MultiTermQuery$ConstantScoreAutoRewrite object;
          PyTypeObject *parameters[1];
          static PyTypeObject **parameters_(t_MultiTermQuery$ConstantScoreAutoRewrite *self)
          {
            return (PyTypeObject **) &(self->parameters);
          }
          static PyObject *wrap_Object(const MultiTermQuery$ConstantScoreAutoRewrite&);
          static PyObject *wrap_jobject(const jobject&);
          static PyObject *wrap_Object(const MultiTermQuery$ConstantScoreAutoRewrite&, PyTypeObject *);
          static PyObject *wrap_jobject(const jobject&, PyTypeObject *);
          static void install(PyObject *module);
          static void initialize(PyObject *module);
        };
      }
    }
  }
}

#endif


text:
package com.zrz.demo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class JsonConverter {
    private static ObjectMapper objectMapper = new ObjectMapper();

    public static Map<String, Object> convertJson2Map(String json) {
        return convertJson2Map(json, Object.class);
    }

    public static <T> Map<String, T> convertJson2Map(String json, final Class<T> classType) {
        Map<String, T> extensions = Maps.newHashMap();
        if (StringUtils.isEmpty(json)) {
            return extensions;
        }
        try {
            TypeReference<HashMap<String, T>> typeRef = createMapTypeRef(classType);
            extensions = objectMapper.readValue(json, typeRef);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return extensions;
    }

    public static <T> List<T> convertJson2List(String json, final Class<T> classType) {
        List<T> extensions = Lists.newArrayList();
        if (StringUtils.isEmpty(json)) {
            return extensions;
        }
        try {
            TypeReference<ArrayList<T>> typeRef = createListTypeRef(classType);
            extensions = objectMapper.readValue(json, typeRef);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return extensions;
    }

    public static String convertMap2Json(Map<String, Object> extension) {
        return convertMap2Json(extension, Object.class);
    }

    public static <T> String convertMap2Json(Map<String, T> extension, final Class<T> classType) {
        String attributes = null;
        if (extension == null) {
            return attributes;
        }
        try {
            attributes = objectMapper.writerWithType(createMapTypeRef(classType)).writeValueAsString(extension);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return attributes;
    }

    public static <T> String convertList2Json(List<T> list) {
        String attributes = null;
        if (list == null) {
            return attributes;
        }
        try {
            attributes = objectMapper.writerWithType(createListTypeRef(Object.class)).writeValueAsString(list);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return attributes;
    }

    private static <T> TypeReference<HashMap<String, T>> createMapTypeRef(
            @SuppressWarnings("unused") final Class<T> classType) {
        TypeReference<HashMap<String, T>> typeRef = new TypeReference<HashMap<String, T>>() {
            // empty
        };
        return typeRef;
    }

    private static <T> TypeReference<ArrayList<T>> createListTypeRef(
            @SuppressWarnings("unused") final Class<T> classType) {
        TypeReference<ArrayList<T>> typeRef = new TypeReference<ArrayList<T>>() {
            // empty
        };
        return typeRef;
    }
}


text:
const path = require('path');
const utils = require('./utils');
const coverageUpdater = require('./coverage-updater');

const JSON_SUMMARY_REPORTER = {
  type: 'json-summary',
  file: 'coverage-summary.json',
  dir: 'coverage',
};

function getBrowserDir(coverageDir) {
// solution for karma browser
  const directories = utils.getDirectories(coverageDir);
  directories.filter(dir => !/lib|spec|src|node_modules/.test(dir));
  return directories.length ? directories[0] : '';
}

function getJsonSummaryPath(jsonSummaryReporter) {
  const fileName = jsonSummaryReporter.file || JSON_SUMMARY_REPORTER.file;
  const dirName = jsonSummaryReporter.dir || JSON_SUMMARY_REPORTER.dir;
  const browserDir = getBrowserDir(dirName);
  return path.join(dirName, browserDir, fileName);
}

function getJsonSummary(coverageReporter) {
  if (coverageReporter.type === JSON_SUMMARY_REPORTER.type) {
    return getJsonSummaryPath(coverageReporter);
  }
  const reporters = coverageReporter.reporters || [];
  for (let i = 0; i < reporters.length; i++) {
    if (reporters[i].type === JSON_SUMMARY_REPORTER.type) {
      return getJsonSummaryPath(reporters[i]);
    }
  }
  return undefined;
}

/* eslint no-unused-vars: "warn" */
const incrementReporter = function (rootConfig, helper, logger) {
  const reporters = (rootConfig.reporters || []);
  if (!reporters.includes('coverage')) {
    throw new Error('coverage reporter should be used');
  }

  const coverageReporter = rootConfig.coverageReporter || {};

  // TODO get this from Istanbul - don't depend on json-summary
  const jsonSummary = getJsonSummary(coverageReporter);
  if (!jsonSummary) {
    throw new Error('json-summary coverage-reporter should be used');
  }

  const config = rootConfig.incrementConfig || {};

  this.onExit = function (done) {
    coverageUpdater.updateCodeCoverage(getJsonSummary(coverageReporter), config)
      .then(done);
  };
};

incrementReporter.$inject = ['config', 'helper', 'logger'];

module.exports = {
  'reporter:increment': ['type', incrementReporter],
};


text:
<?php

namespace Oro\Bundle\EntityExtendBundle\Migration;

use Oro\Component\PhpUtils\ArrayUtil;

class ExtendOptionsManager
{
    const ENTITY_CLASS_OPTION = '_entity_class';
    const FIELD_NAME_OPTION   = '_field';
    const TYPE_OPTION         = '_type';
    const MODE_OPTION         = '_mode';
    const TARGET_OPTION       = '_target';
    const NEW_NAME_OPTION     = '_new_name';
    const APPEND_SECTION      = '_append';

    /**
     * Example of usage: sprintf('%s!%s', $tableName, $columnName)
     */
    const COLUMN_OPTION_FORMAT = '%s!%s';

    /**
     * @var array
     * [
     *      {table name} => [...],
     *      {table name}!{column name} => [...],
     *      self::APPEND_SECTION => [
     *          {table name} => [...],
     *          {table name}!{column name} => [...],
     *      ]
     * ]
     */
    protected $options = [];

    /**
     * Sets table options
     *
     * @param string $tableName
     * @param array  $options
     * @throws \InvalidArgumentException
     */
    public function setTableOptions($tableName, array $options)
    {
        $this->setOptions($tableName, $options);
    }

    /**
     * Sets table mode
     *
     * @param string $tableName
     * @param string $mode
     * @throws \InvalidArgumentException
     */
    public function setTableMode($tableName, $mode)
    {
        $this->setOptions($tableName, [self::MODE_OPTION => $mode]);
    }

    /**
     * Removes table options from the options manager
     *
     * @param string $tableName
     */
    public function removeTableOptions($tableName)
    {
        unset($this->options[$tableName], $this->options[self::APPEND_SECTION][$tableName]);
    }

    /**
     * Sets column options
     *
     * @param string $tableName
     * @param string $columnName
     * @param array  $options
     * @throws \InvalidArgumentException
     */
    public function setColumnOptions($tableName, $columnName, array $options)
    {
        $this->setOptions(sprintf(static::COLUMN_OPTION_FORMAT, $tableName, $columnName), $options);
    }

    /**
     * Sets column mode
     *
     * @param string $tableName
     * @param string $columnName
     * @param string $mode
     * @throws \InvalidArgumentException
     */
    public function setColumnMode($tableName, $columnName, $mode)
    {
        $this->setOptions(sprintf(static::COLUMN_OPTION_FORMAT, $tableName, $columnName), [self::MODE_OPTION => $mode]);
    }

    /**
     * @param string $tableName
     * @param string $columnName
     * @param array  $options
     */
    public function mergeColumnOptions($tableName, $columnName, array $options)
    {
        $objectKey = sprintf(static::COLUMN_OPTION_FORMAT, $tableName, $columnName);
        if (!isset($this->options[$objectKey])) {
            $this->options[$objectKey] = [];
        }
        $this->options[$objectKey] = ArrayUtil::arrayMergeRecursiveDistinct($this->options[$objectKey], $options);
    }

    /**
     * @param string $tableName
     * @param string $columnName
     * @return bool
     */
    public function hasColumnOptions(string $tableName, string $columnName): bool
    {
        $objectKey = sprintf(static::COLUMN_OPTION_FORMAT, $tableName, $columnName);

        return isset($this->options[$objectKey]);
    }

    /**
     * @param string $tableName
     * @param string $columnName
     * @return array
     */
    public function getColumnOptions(string $tableName, string $columnName): array
    {
        $objectKey = sprintf(static::COLUMN_OPTION_FORMAT, $tableName, $columnName);

        return $this->options[$objectKey] ?? [];
    }

    /**
     * Sets column type
     *
     * @param string $tableName
     * @param string $columnName
     * @param string $columnType
     * @throws \InvalidArgumentException
     */
    public function setColumnType($tableName, $columnName, $columnType)
    {
        $this->setOptions(
            sprintf(static::COLUMN_OPTION_FORMAT, $tableName, $columnName),
            [self::TYPE_OPTION => $columnType]
        );
    }

    /**
     * Removes column options from the options manager
     *
     * @param string $tableName
     * @param string $columnName
     */
    public function removeColumnOptions($tableName, $columnName)
    {
        $objectKey = sprintf(static::COLUMN_OPTION_FORMAT, $tableName, $columnName);
        unset($this->options[$objectKey], $this->options[self::APPEND_SECTION][$objectKey]);
    }

    /**
     * Gets all options
     *
     * @return array
     */
    public function getExtendOptions()
    {
        return $this->options;
    }

    /**
     * @param string $objectKey
     * @param array  $options
     * @throws \InvalidArgumentException
     */
    protected function setOptions($objectKey, array $options)
    {
        if (!isset($this->options[$objectKey])) {
            $this->options[$objectKey] = [];
        }
        $this->handleAppendSection($objectKey, $options);
        foreach ($options as $scope => $values) {
            $this->validateOption($objectKey, $scope, $values);
            if (isset($this->options[$objectKey][$scope]) && is_array($values)) {
                foreach ($values as $attrName => $val) {
                    if ($this->isAppend($objectKey, $scope, $attrName)
                        && isset($this->options[$objectKey][$scope][$attrName])
                    ) {
                        $this->options[$objectKey][$scope][$attrName] = array_merge(
                            (array)$this->options[$objectKey][$scope][$attrName],
                            (array)$val
                        );
                    } else {
                        $this->options[$objectKey][$scope][$attrName] = $val;
                    }
                }
            } else {
                $this->options[$objectKey][$scope] = $values;
            }
        }
    }

    /**
     * Gets a value of an option with the given name and then remove the option from $options array
     *
     * @param array  $options
     * @param string $name
     * @return mixed
     */
    protected function getAndRemoveOption(array &$options, $name)
    {
        $value = null;
        if (isset($options[$name])) {
            $value = $options[$name];
            unset($options[$name]);
        }

        return $value;
    }

    /**
     * @param string $objectKey
     * @param array  $options
     */
    protected function handleAppendSection($objectKey, array &$options)
    {
        $appendSection = $this->getAndRemoveOption($options, OroOptions::APPEND_SECTION);
        if (!empty($appendSection)) {
            foreach ($appendSection as $scope => $attrNames) {
                foreach ($attrNames as $attrName) {
                    if (!isset($this->options[self::APPEND_SECTION])) {
                        $this->options[self::APPEND_SECTION] = [];
                    }
                    if (!isset($this->options[self::APPEND_SECTION][$objectKey])) {
                        $this->options[self::APPEND_SECTION][$objectKey] = [];
                    }
                    if (!isset($this->options[self::APPEND_SECTION][$objectKey][$scope])) {
                        $this->options[self::APPEND_SECTION][$objectKey][$scope] = [];
                    }
                    if (!in_array($attrName, $this->options[self::APPEND_SECTION][$objectKey][$scope], true)) {
                        $this->options[self::APPEND_SECTION][$objectKey][$scope][] = $attrName;
                    }
                }
            }
        }
    }

    /**
     * @param string $objectKey
     * @param string $scope
     * @param string $attrName
     * @return bool
     */
    protected function isAppend($objectKey, $scope, $attrName)
    {
        return
            isset($this->options[self::APPEND_SECTION][$objectKey][$scope]) &&
            in_array($attrName, $this->options[self::APPEND_SECTION][$objectKey][$scope], true);
    }

    /**
     * @param $objectKey
     * @param $scope
     * @param $values
     * @throws \InvalidArgumentException
     */
    private function validateOption($objectKey, $scope, $values)
    {
        if (!is_string($scope) || empty($scope)) {
            throw new \InvalidArgumentException(
                sprintf('A scope name must be non empty string. Key: %s.', $objectKey)
            );
        }

        // a scope which name starts with '_' is a temporary and it should be removed in ExtendOptionsBuilder
        if (!is_array($values) && strpos($scope, '_') !== 0) {
            throw new \InvalidArgumentException(
                sprintf('A value of "%s" scope must be an array. Key: %s.', $scope, $objectKey)
            );
        }
    }
}


text:
<?php

namespace app\modules\v1\models;

use Yii;

/**
 * This is the model class for table "concerns".
 *
 * @property integer $id
 * @property integer $myid
 * @property integer $concernid
 * @property integer $created_at
 * @property Users $concern
 * @property Users $my
 */
class Concerns extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'concerns';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['myid', 'concernid'], 'required'],
            [['myid', 'concernid','created_at'], 'integer']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'myid' => '自己',
            'concernid' => '对方',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getConcern()
    {
        return $this->hasOne(Users::className(), ['id' => 'concernid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMy()
    {
        return $this->hasOne(Users::className(), ['id' => 'myid']);
    }
}


text:
import json
from decimal import Decimal
from datetime import datetime

from sqlalchemy import Column, DateTime, Integer, Numeric, String

from piper import utils
from piper.api.search import S as Search
from piper.database import Model

class Budget(Model):
    """A saved search with a limit."""
    __tablename__ = 'budget'

    id = Column(Integer, primary_key=True)
    name = Column(String(128), nullable=False)
    search = Column(String(10240), nullable=False)
    limit = Column(utils.DecimalString(Numeric(15, 2)), nullable=False)
    start = Column(DateTime, nullable=True)
    end = Column(DateTime, nullable=True)

    def serialize(self, detail=False):
        data = super(Budget, self).serialize()

        data['remaining'] = '%.2f' % self.remaining
        if detail:
            data['transactions'] = self.transactions

        return data

    def update(self, **kwargs):
        for key in ['transactions', 'remaining']:
            kwargs.pop(key, None)

        for field in ['start', 'end']:
            if field in kwargs:
                kwargs[field] = utils.coerce_datetime(kwargs[field])

        super(Budget, self).update(**kwargs)

    @property
    def search_parsed(self):
        if not hasattr(self, '_search_parsed'):
            parsed = json.loads(self.search)
            self._search_parsed = {"and": [parsed]}

            if self.start:
                self._search_parsed['and'].append({
                    'greater-equal': {'date': self.start},
                })
            if self.end:
                self._search_parsed['and'].append({
                    'less': {'date': self.end},
                })

        return self._search_parsed

    @property
    def transactions(self):
        if not hasattr(self, '_transactions'):
            self._transactions = Search(self.search_parsed)
        return self._transactions

    @property
    def remaining(self):
        if not hasattr(self, '_remaining'):
            total = Decimal(0)
            # Expenses are negative.
            for t in self.transactions:
                total += sum(Decimal(s.amount) for s in t['splits'])
            self._remaining = self.limit + total
        return self._remaining


text:
angular.module('myApp.services')
	.service('api', ['$http','storage','redirection','$location',
		function($http,storage,redirection,$location) {
			'use strict';

			this.url = null;
			this.getApiUrl = function () {
				if (this.url !== null) {
					return this.url;
				}
				var host = $location.host();

				this.url = 'http://apidev.esbattle.com/app_dev.php/';

				if(host === 'lfg.esbattle.com'){
					this.url = 'http://apiv2.esbattle.com/';
				}

				return this.url;
			};

			this.call = function (path) {
				return $http.get(this.getApiUrl() + path).error(function (data, status, headers, config) {

					switch (status) {
						case 401 :
							storage.erasePersistant('user');
							redirection.goToLogin();
							break;

						case 403:
							//on ne fait rien, la requete n'est pas authorisée
							break;

						case 308:
							redirection.goHome();
							break;

						case 404:
							redirection.notFound(data.msg);
							break;

						default:
							break;
					}
				});
			};

			this.post = function (path, params,currentUser) {

				var url = this.getApiUrl() + path;

				var userId = '';
				var token = '';
				if(currentUser !== null && typeof currentUser !== 'undefined'){
					userId = currentUser.id;
					token = currentUser.token;
				}

				return $http({
					method: 'POST',
					url: url,
					data: params,
					headers: {
						'User' : userId,
						'Token': token
					}
				}).error(function (data, status, headers, config) {

					switch (status) {
						case 401 :
							storage.erasePersistant('user');
							redirection.goToLogin();
							break;

						case 403:
							//on ne fait rien, la requete n'est pas authorisée
							break;

						case 308:
							redirection.goHome();
							break;

						case 404:
							redirection.notFound(data.msg);
							break;

						default:
							break;
					}
				});
			};
		}
	]
);


text:
<?php
$v = new SplTempFileObject();


text:
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.pjaygroup</groupId>
  <artifactId>restfulapp2</artifactId>
  <packaging>war</packaging>
  <version>1.0.0-SNAPSHOT</version>
  <name>restfulapp2 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>

  	<!-- https://jersey.java.net/documentation/latest/modules-and-dependencies.html
  		 https://jersey.java.net/documentation/latest/appendix-properties.html
  		 http://howtodoinjava.com/jersey/jersey-2-hello-world-application-tutorial -->

	<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
	<dependency>
	    <groupId>javax.servlet</groupId>
	    <artifactId>javax.servlet-api</artifactId>
	    <version>3.1.0</version>
	    <scope>provided</scope>
	</dependency>

	<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
	<dependency>
	    <groupId>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>5.1.39</version>
	</dependency>

	<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-client -->
	<dependency>
	    <groupId>org.glassfish.jersey.core</groupId>
	    <artifactId>jersey-client</artifactId>
	    <version>2.23.1</version>
	</dependency>

	<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-server -->
	<dependency>
	    <groupId>org.glassfish.jersey.core</groupId>
	    <artifactId>jersey-server</artifactId>
	    <version>2.23.1</version>
	</dependency>

	<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.containers/jersey-container-servlet -->
	<dependency>
	    <groupId>org.glassfish.jersey.containers</groupId>
	    <artifactId>jersey-container-servlet</artifactId>
	    <version>2.23.1</version>
	</dependency>

	<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
	<dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-core</artifactId>
	    <version>2.8.0</version>
	</dependency>

	<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-json-jackson -->
	<dependency>
	    <groupId>org.glassfish.jersey.media</groupId>
	    <artifactId>jersey-media-json-jackson</artifactId>
	    <version>2.23.1</version>
	</dependency>

	<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-jaxb -->
	<dependency>
	    <groupId>org.glassfish.jersey.media</groupId>
	    <artifactId>jersey-media-jaxb</artifactId>
	    <version>2.23.1</version>
	</dependency>

	<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-multipart -->
	<dependency>
	    <groupId>org.glassfish.jersey.media</groupId>
	    <artifactId>jersey-media-multipart</artifactId>
	    <version>2.23.1</version>
	</dependency>

	<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<!-- 	<dependency> -->
<!-- 	    <groupId>com.fasterxml.jackson.core</groupId> -->
<!-- 	    <artifactId>jackson-annotations</artifactId> -->
<!-- 	    <version>2.8.0</version> -->
<!-- 	</dependency> -->

	<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<!-- 	<dependency> -->
<!-- 	    <groupId>com.fasterxml.jackson.core</groupId> -->
<!-- 	    <artifactId>jackson-annotations</artifactId> -->
<!-- 	    <version>2.6.3</version> -->
<!-- 	</dependency> -->

	<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
	<dependency>
	    <groupId>org.hibernate</groupId>
	    <artifactId>hibernate-core</artifactId>
	    <version>5.1.0.Final</version>
	</dependency>

	<!-- http://mvnrepository.com/artifact/junit/junit -->
	<dependency>
	    <groupId>junit</groupId>
	    <artifactId>junit</artifactId>
	    <version>4.12</version>
	    <scope>test</scope>
	</dependency>
  </dependencies>
  <build>
    <finalName>restfulapp2</finalName>
	  <plugins>
		  <plugin>
			  <groupId>org.apache.maven.plugins</groupId>
		      <artifactId>maven-compiler-plugin</artifactId>
		      <version>3.1</version>
		      <configuration>
		      	<source>1.7</source>
		      	<target>1.7</target>
		      </configuration>
		  </plugin>
	  </plugins>
  </build>
</project>


text:
#region License

#endregion License

using System;
using UnityEngine;

namespace eDriven.Core.Events
{
    /// <summary>
    /// Plugin that is a gesture recognizer
    /// Dispatches events from TouchEventDispatcher
    /// </summary>
    public interface ITouchEventDispatcherPlugin : IDisposable
    {
        /// <summary>
        /// Initializes the plugin
        /// </summary>
        /// <param name="component"></param>
        void Initialize(IEventDispatcher component);

        /// <summary>
        /// Processes touches
        /// </summary>
        /// <param name="touches"></param>
        void Process(Touch[] touches);
    }
}


text:
package org.mvel2.util;

import org.mvel2.ParserContext;
import org.mvel2.compiler.PropertyVerifier;

import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;

import static java.lang.String.valueOf;
import static java.lang.reflect.Modifier.PUBLIC;
import static java.lang.reflect.Modifier.STATIC;
import static java.lang.reflect.Modifier.isPublic;
import static org.mvel2.DataConversion.canConvert;
import static org.mvel2.util.ParseTools.boxPrimitive;

public class PropertyTools {
  public static boolean isEmpty(Object o) {
    if (o != null) {
      if (o instanceof Object[]) {
        return ((Object[]) o).length == 0 ||
            (((Object[]) o).length == 1 && isEmpty(((Object[]) o)[0]));
      }
      else {
        return ("".equals(valueOf(o)))
            || "null".equals(valueOf(o))
            || (o instanceof Collection && ((Collection) o).size() == 0)
            || (o instanceof Map && ((Map) o).size() == 0);
      }
    }
    return true;
  }

  public static Method getSetter(Class clazz, String property) {
    property = ReflectionUtil.getSetter(property);

    for (Method meth : clazz.getMethods()) {
      if ((meth.getModifiers() & PUBLIC) != 0 && meth.getParameterTypes().length == 1
          && property.equals(meth.getName())) {
        return meth;
      }
    }

    return null;
  }

  public static Method getSetter(Class clazz, String property, Class type) {
    String simple = "set" + property;
    property = ReflectionUtil.getSetter(property);

    for (Method meth : clazz.getMethods()) {
      if ((meth.getModifiers() & PUBLIC) != 0 && meth.getParameterTypes().length == 1 &&
          (property.equals(meth.getName()) || simple.equals(meth.getName()))
          && (type == null || canConvert(meth.getParameterTypes()[0], type))) {
        return meth;
      }
    }

    return null;
  }

  public static boolean hasGetter(Field field) {
    Method meth = getGetter(field.getDeclaringClass(), field.getName());
    return meth != null && field.getType().isAssignableFrom(meth.getReturnType());
  }

  public static boolean hasSetter(Field field) {
    Method meth = getSetter(field.getDeclaringClass(), field.getName());
    return meth != null && meth.getParameterTypes().length == 1 &&
        field.getType().isAssignableFrom(meth.getParameterTypes()[0]);
  }

  public static Method getGetter(Class clazz, String property) {
    String simple = "get" + property;
    String simpleIsGet = "is" + property;
    String isGet = ReflectionUtil.getIsGetter(property);
    String getter = ReflectionUtil.getGetter(property);

    Method candidate = null;
    for (Method meth : clazz.getMethods()) {
      if ((meth.getModifiers() & PUBLIC) != 0 && (meth.getModifiers() & STATIC) == 0 && meth.getParameterTypes().length == 0
          && (getter.equals(meth.getName()) || property.equals(meth.getName()) || ((isGet.equals(meth.getName()) || simpleIsGet.equals(meth.getName())) && meth.getReturnType() == boolean.class)
          || simple.equals(meth.getName()))) {
        if (candidate == null || candidate.getReturnType().isAssignableFrom(meth.getReturnType())) {
          candidate = meth;
        }
      }
    }
    return candidate;
  }

  public static Class getReturnType(Class clazz, String property, ParserContext ctx) {
    return new PropertyVerifier(property, ctx, clazz).analyze();
  }

  public static Member getFieldOrAccessor(Class clazz, String property) {
    for (Field f : clazz.getFields()) {
      if (property.equals(f.getName())) {
        if ((f.getModifiers() & PUBLIC) != 0) return f;
        break;
      }
    }
    return getGetter(clazz, property);
  }

  public static Member getFieldOrWriteAccessor(Class clazz, String property) {
    Field field;
    try {
      if ((field = clazz.getField(property)) != null &&
          isPublic(field.getModifiers())) {
        return field;
      }
    }
    catch (NullPointerException e) {
      return null;
    }
    catch (NoSuchFieldException e) {
      // do nothing.
    }

    return getSetter(clazz, property);
  }

  public static Member getFieldOrWriteAccessor(Class clazz, String property, Class type) {
    for (Field f : clazz.getFields()) {
      if (property.equals(f.getName()) && (type == null || canConvert(f.getType(), type))) {
        return f;
      }
    }

    return getSetter(clazz, property, type);
  }

  public static boolean contains(Object toCompare, Object testValue) {
    if (toCompare == null)
      return false;
    else if (toCompare instanceof String)
      return ((String) toCompare).contains(valueOf(testValue));
      //    return ((String) toCompare).indexOf(valueOf(testValue)) > -1;
    else if (toCompare instanceof Collection)
      return ((Collection) toCompare).contains(testValue);
    else if (toCompare instanceof Map)
      return ((Map) toCompare).containsKey(testValue);
    else if (toCompare.getClass().isArray()) {
      for (Object o : ((Object[]) toCompare)) {
        if (testValue == null && o == null) return true;
        else if (o != null && o.equals(testValue)) return true;
      }
    }
    return false;
  }

  public static Object getPrimitiveInitialValue(Class type) {
    if (type == int.class) {
      return 0;
    }
    else if (type == boolean.class) {
      return false;
    }
    else if (type == char.class) {
      return (char) 0;
    }
    else if (type == double.class) {
      return 0d;
    }
    else if (type == long.class) {
      return 0l;
    }
    else if (type == float.class) {
      return 0f;
    }
    else if (type == short.class) {
      return (short) 0;
    }
    else if (type == byte.class) {
      return (byte) 0;
    }
    else {
      return 0;
    }
  }

  public static boolean isAssignable(Class to, Class from) {
    return (to.isPrimitive() ? boxPrimitive(to) : to).isAssignableFrom(from.isPrimitive() ? boxPrimitive(from) : from);
  }

  /**
   * Get the JVM version
   * @return first mvel.java.version, then java.version
   * @see System.getProperty("mvel.java.version");
   * @see System.getProperty("java.version");
   */
  public static String getJavaVersion() {
    return System.getProperty("mvel.java.version")!=null ?
            System.getProperty("mvel.java.version") :
            System.getProperty("java.version");
  }
}


text:
import { Openflame } from '../src/core';
import { Database } from '@openflame/database';

declare module '../src/core' {
  interface Openflame {
    readonly database: Database;
  }
}

Object.defineProperty(Openflame.prototype, 'database', {
  get: function (): Database {
    return this._instances['database'] || (this._instances['database'] = new Database(this));
  }
});


text:
**Let start with a Naive approach**
----------------------------------------------
Words are just a group of letters. You can represent a letter in Haskell as a char

```haskell
Prelude> 'k'
'k'
Prelude> :t 'k'
'k' :: Char
```
since we can represent letter in Haskell a char and a word is a group of letters we can represent a word as a list of chars

```haskell
Prelude> ['s','v','d','a','h']
"svdah"
```
Haskell has operations on lists leverage them

```haskell
Prelude> length "svdah"
5
Prelude> head "svdah"
s
Prelude> :t head
head :: [a] -> a
Prelude> :t tail
???????? guess
Prelude> tail "svdah"
"vdah"
Prelude> reverse "svdah"
"hadvs"
```
we can represent sentences in a list of a lists and i can use operations on lists
```haskell
Prelude> ["birds","requiem"]
["birds","requiem"]
Prelude> head["birds","requiem"]
"birds"
Prelude> head $ head ["birds","requiem"]
'b'
:t ($)
($) :: (a -> b) -> a -> b

Prelude> :t length
length :: Foldable t => t a -> Int
```
**we will cover how to turn a text into list of list later ;)**
we can't use length since it is going to give us the length of the list it is checking in the example above
but we might be able to map the length function on the list
```haskell
Prelude> :t map
map :: (a -> b) -> [a] -> [b]
map length ["birds","requiem"]
[5,7]
:t
```
but we only get a list of the lengths of the words we don't get the length of the sentence easy lets change that
```haskell
:t sum
sum :: (Num a, Foldable t) => t a -> a
sum $ map length ["birds","requiem"]
```
haskell has a a function named lines
```haskell
Prelude> :t lines
lines :: String -> [String]
```
lines will create  break strings that end with break lines
```haskell
Prelude> lines "all names used so far are songs by dafher yousef\n. He is a jazz / sufi musician"
["all names used so far are songs by dafher yousef",". He is a jazz / sufi musician"]
```
haskell has a function named words lets look at it's type
```haskell
Prelude> words "blending souls & shades ."
["blending","souls","&","shades","."]
```
lets map the function words on the output of the function lines applied on text
```haskell
Prelude> map words $ lines "all names used so far are songs by dafher yousef. He is a jazz / sufi musician"
[["all","names","used","so","far","are","songs","by","dafher","yousef.","He","is","a","jazz","/","sufi", "musician" ]]

```
after tokenizing i think i **maybe** able to make a word frequency we can represent a word frequency list in something like
```haskell
Whirling Birds Ceremony "Birds Requiem" Suite
[(	"Whirling Birds Ceremony",1 ),("Birds",2),("Ceremony",1),("Requiem",1)]
```
i can use the a map data structure from Data.map.Empty but i am lazy can some one do it for me :)
```haskell
Prelude> Data.Map.fromList[("Whirling Birds Ceremony",1 ),("Birds",2),("Ceremony",1),("Requiem",1)]
```
to insert new entries we can
```haskell
Data.Map.insert
```
to look stuff you can use
```haskell
Data.map.lookup
```

```haskell
Prelude> :t Data.Map.lookup
Data.Map.lookup
  :: Ord k =>
     k -> containers-0.5.6.2:Data.Map.Base.Map k a -> Maybe a
```
now that i now how to use Data.map i am going to try try a function to count the elements of list
```haskell
import qualified Data.Map

countStuff :: (Ord k) => Data.Map.Map k Int -> k -> Data.Map.Map k Int
countStuff m e = case (Data.Map.lookup e m) of
                    Just v -> Data.Map.insert e (v + 1) m
                    Nothing -> Data.Map.insert e 1 m
```
```haskell
foldl countStuff Data.Map.empty ["this", "is ", "cool" , "cool"]
```
the frequency list will be
```haskell
freqList :: (Ord N ) => [N] -> Data.Map.Map N Int
freqList = foldl countStuff Data.Map.empty
```

lets import a real word corpus instead of
```haskell
import System.IO
d <- openFile "rural.txt" ReadMode
y <- hGetContents d
```
```haskell
head $ words $ head $ lines y
```
okay nlp means i will need N-grams
```
an n-gram is a contiguous sequence of n items from a given sequence of text or speech. The items can be phonemes, syllables, letters, words or base pairs according to the application. The n-grams typically are collected from a text or speech corpus
```

okay lets create bigrams
```haskell
bigram :: [a] -> [[a]]
bigram [x] = []
bigram xs = take 2 xs : bigram (tail xs)
```


text:
  Ambleville est
       un village
       géographiquement positionné dans le département de Val-d'Oise en Île-de-France. Elle comptait 349 habitants en 2008.

Le nombre d'habitations, à Ambleville, se décomposait en 2011 en huit appartements et 185 maisons soit
 un marché relativement équilibré.

À coté de Ambleville sont localisées les communes de
Chaussy localisée à 3 km, 647 habitants,
Dampsmesnil située à 4 km, 212 habitants,
Berthenonville à 4 km, 228 habitants,
Fourges à 5 km, 805 habitants,
Saint-Gervais localisée à 5 km, 953 habitants,
Bray-et-Lû située à 2 km, 911 habitants,
 entre autres. De plus, Ambleville est située à seulement 27 km de Cergy.

Si vous pensez venir habiter à Ambleville, vous pourrez aisément trouver une maison à acheter.


text:
"""extenders tests."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np

from tensorflow.contrib.data.python.ops import dataset_ops
from tensorflow.contrib.estimator.python.estimator import extenders
from tensorflow.python.estimator import run_config
from tensorflow.python.estimator.canned import linear
from tensorflow.python.feature_column import feature_column as fc
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.ops import metrics as metrics_lib
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.training import training

def get_input_fn(x, y):

  def input_fn():
    dataset = dataset_ops.Dataset.from_tensor_slices({'x': x, 'y': y})
    iterator = dataset.make_one_shot_iterator()
    features = iterator.get_next()
    labels = features.pop('y')
    return features, labels

  return input_fn

class AddMetricsTest(test.TestCase):

  def test_should_add_metrics(self):
    input_fn = get_input_fn(
        x=np.arange(4)[:, None, None], y=np.ones(4)[:, None])
    estimator = linear.LinearClassifier([fc.numeric_column('x')])

    def metric_fn(features):
      return {'mean_x': metrics_lib.mean(features['x'])}

    estimator = extenders.add_metrics(estimator, metric_fn)

    estimator.train(input_fn=input_fn)
    metrics = estimator.evaluate(input_fn=input_fn)
    self.assertIn('mean_x', metrics)
    self.assertEqual(1.5, metrics['mean_x'])
    # assert that it keeps original estimators metrics
    self.assertIn('auc', metrics)

  def test_should_error_out_for_not_recognized_args(self):
    estimator = linear.LinearClassifier([fc.numeric_column('x')])

    def metric_fn(features, not_recognized):
      _, _ = features, not_recognized
      return {}

    with self.assertRaisesRegexp(ValueError, 'not_recognized'):
      estimator = extenders.add_metrics(estimator, metric_fn)

  def test_all_supported_args(self):
    input_fn = get_input_fn(x=[[[0.]]], y=[[[1]]])
    estimator = linear.LinearClassifier([fc.numeric_column('x')])

    def metric_fn(features, predictions, labels, config):
      self.assertIn('x', features)
      self.assertIsNotNone(labels)
      self.assertIn('logistic', predictions)
      self.assertTrue(isinstance(config, run_config.RunConfig))
      return {}

    estimator = extenders.add_metrics(estimator, metric_fn)

    estimator.train(input_fn=input_fn)
    estimator.evaluate(input_fn=input_fn)

  def test_all_supported_args_in_different_order(self):
    input_fn = get_input_fn(x=[[[0.]]], y=[[[1]]])
    estimator = linear.LinearClassifier([fc.numeric_column('x')])

    def metric_fn(labels, config, features, predictions):
      self.assertIn('x', features)
      self.assertIsNotNone(labels)
      self.assertIn('logistic', predictions)
      self.assertTrue(isinstance(config, run_config.RunConfig))
      return {}

    estimator = extenders.add_metrics(estimator, metric_fn)

    estimator.train(input_fn=input_fn)
    estimator.evaluate(input_fn=input_fn)

  def test_all_args_are_optional(self):
    input_fn = get_input_fn(x=[[[0.]]], y=[[[1]]])
    estimator = linear.LinearClassifier([fc.numeric_column('x')])

    def metric_fn():
      return {'two': metrics_lib.mean(constant_op.constant([2.]))}

    estimator = extenders.add_metrics(estimator, metric_fn)

    estimator.train(input_fn=input_fn)
    metrics = estimator.evaluate(input_fn=input_fn)
    self.assertEqual(2., metrics['two'])

  def test_overrides_existing_metrics(self):
    input_fn = get_input_fn(x=[[[0.]]], y=[[[1]]])
    estimator = linear.LinearClassifier([fc.numeric_column('x')])
    estimator.train(input_fn=input_fn)
    metrics = estimator.evaluate(input_fn=input_fn)
    self.assertNotEqual(2., metrics['auc'])

    def metric_fn():
      return {'auc': metrics_lib.mean(constant_op.constant([2.]))}

    estimator = extenders.add_metrics(estimator, metric_fn)
    metrics = estimator.evaluate(input_fn=input_fn)
    self.assertEqual(2., metrics['auc'])

class ClipGradientsByNormTest(test.TestCase):
  """Tests clip_gradients_by_norm."""

  def test_applies_norm(self):
    optimizer = extenders.clip_gradients_by_norm(
        training.GradientDescentOptimizer(1.0), clip_norm=3.)
    with ops.Graph().as_default():
      w = variables.Variable(1., name='weight')
      x = constant_op.constant(5.)
      y = -x * w
      grads = optimizer.compute_gradients(y, var_list=[w])[0]
      opt_op = optimizer.minimize(y, var_list=[w])
      with training.MonitoredSession() as sess:
        grads_value = sess.run(grads)
        self.assertEqual(-5., grads_value[0])
        sess.run(opt_op)
        new_w = sess.run(w)
        self.assertEqual(4., new_w)  # 1 + 1*3 (w - lr * clipped_grad)

  def test_name(self):
    optimizer = extenders.clip_gradients_by_norm(
        training.GradientDescentOptimizer(1.0), clip_norm=3.)
    self.assertEqual('ClipByNormGradientDescent', optimizer.get_name())

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


text:
package com.tribbloids.spookystuff.uav.planning

import com.tribbloids.spookystuff.actions.Trace

trait ResamplerInst {

  def apply(v: Map[Int, Seq[Trace]]): Map[Int, Seq[Trace]]
}


text:
#ifndef TENSORFLOW_CORE_KERNELS_RESOURCE_VARIABLE_OPS_H_
#define TENSORFLOW_CORE_KERNELS_RESOURCE_VARIABLE_OPS_H_

#include "tensorflow/core/framework/op_kernel.h"

namespace tensorflow {

class ReadVariableOp : public OpKernel {
 public:
  explicit ReadVariableOp(OpKernelConstruction* c);
  void Compute(OpKernelContext* ctx) override;

 private:
  DataType dtype_;
};

class ReadVariablesOp : public OpKernel {
 public:
  explicit ReadVariablesOp(OpKernelConstruction* c);
  void Compute(OpKernelContext* ctx) override;
  bool IsExpensive() override { return false; }

 private:
  DataTypeVector dtypes_;
};

class DestroyResourceOp : public OpKernel {
 public:
  explicit DestroyResourceOp(OpKernelConstruction* ctx);
  void Compute(OpKernelContext* ctx) override;

 private:
  bool ignore_lookup_error_;
};

}  // namespace tensorflow

#endif  // TENSORFLOW_CORE_KERNELS_RESOURCE_VARIABLE_OPS_H_


text:
package org.apache.ignite.internal.processors.cache.version;

import org.apache.ignite.cache.*;

/**
 *
 */
public class CacheVersionedEntryPartitionedAtomicSelfTest extends CacheVersionedEntryAbstractTest {
    /** {@inheritDoc} */
    @Override protected CacheMode cacheMode() {
        return CacheMode.PARTITIONED;
    }

    /** {@inheritDoc} */
    @Override protected CacheAtomicityMode atomicityMode() {
        return CacheAtomicityMode.ATOMIC;
    }
}


text:
"""
Module to test man page functionality of click-man package.
"""

from sure import expect

from click_man.man import ManPage

def test_simple_man_page():
    """
    Test creating most simple man page
    """
    man = ManPage('my-command')
    man.short_help = 'Command to test man pages for click.'
    man.date = '21-Feb-1994'
    expect(str(man)).to.be.equal(""".TH "MY-COMMAND" "1" "21-Feb-1994" "1.0.0" "my-command Manual"
.SH NAME
my-command \- Command to test man pages for click.
.SH SYNOPSIS
.B my-command
""")

def test_full_man_page():
    """
    Test creating man page with all options set
    """
    man = ManPage('my-command')
    man.short_help = 'Command to test man pages for click.'
    man.date = '21-Feb-1994'
    man.synopsis = '[--yolo] [--iambatman]'
    man.description = """This is my awesome

multi line description of a click-man test.

Boaa, richtig geili sach."""

    man.options = [
        ('--yolo', 'Do it in yolo style'),
        ('--iambatman', 'Make me think I am batman')
    ]
    man.commands = [
        ('start', 'Start it'),
        ('stop', 'Stop it'),
        ('test', 'Pretend you are testing your code')
    ]

    expect(str(man)).to.be.equal(r""".TH "MY-COMMAND" "1" "21-Feb-1994" "1.0.0" "my-command Manual"
.SH NAME
my-command \- Command to test man pages for click.
.SH SYNOPSIS
.B my-command
[\-\-yolo] [\-\-iambatman]
.SH DESCRIPTION
This is my awesome
.PP
multi line description of a click-man test.
.PP
Boaa, richtig geili sach.
.SH OPTIONS
.TP
\fB\-\-yolo\fP
Do it in yolo style
.TP
\fB\-\-iambatman\fP
Make me think I am batman
.SH COMMANDS
.PP
\fBstart\fP
  Start it
  See \fBmy-command-start(1)\fP for full documentation on the \fBstart\fP command.
.PP
\fBstop\fP
  Stop it
  See \fBmy-command-stop(1)\fP for full documentation on the \fBstop\fP command.
.PP
\fBtest\fP
  Pretend you are testing your code
  See \fBmy-command-test(1)\fP for full documentation on the \fBtest\fP command.
""")


text:
module ApplicationHelper
	include Twitter::Extractor

	def tb_alert_name name
		tb_names = {'notice' => 'success'}
		tb_names[name.to_s] || name.to_s
	end

	def hovercard model
		render "#{model.class.to_s.downcase.pluralize}/hovercard", model: model
	end

	def list_tags tags
		render "tags/tags", tags: tags
	end

	def markdown(text)
		text ||= '' # markdown barfs on nil
		raw $markdown.render(text)
	end

	def tagged_markdown(text)
		text ||= ''

		usernames = extract_mentioned_screen_names(text).uniq
		tags = extract_hashtags(text).uniq

		usernames.each_with_index { |u, i| text = text.gsub(/@#{u}/, "ausrname#{i}") }
		tags.each_with_index { |t, i| text = text.gsub(/##{t}/, "ahshtag#{i}") }

		text = markdown text

		usernames.each_with_index { |u, i| text = text.gsub(/ausrname#{i}/, "@#{u}") }
		tags.each_with_index { |t, i| text = text.gsub(/ahshtag#{i}/, "##{t}") }

		raw text
	end

	def toggle_sort attribute, display_name, path, model_name
		if request.path != path
			session["#{model_name.downcase}_sort_attribute"] = nil
			session["#{model_name.downcase}_sort_direction"] = nil
		end

		current_sort_attribute = session["#{model_name.downcase}_sort_attribute"]
		current_sort_direction = session["#{model_name.downcase}_sort_direction"]

		if attribute != current_sort_attribute
			new_sort_direction = 'desc'
			arrow = " "
		elsif current_sort_direction == 'asc'
			new_sort_direction = 'desc'
			arrow = " "
		elsif current_sort_direction == 'desc'
			new_sort_direction = 'asc'
			arrow = " "
		end

		query = "?sort=#{attribute}&direction=#{new_sort_direction}"

		raw "#{link_to display_name, path + query, remote: true}#{arrow}"
	end
end


text:
namespace OPS
{
	namespace Core
	{
		class IPlugin
		{
		public:

			virtual void initialize() = 0;
			virtual void terminate() = 0;

		protected:

			inline ~IPlugin() {}
		};
	}
}

#endif // _I_PLUGIN_H_INCLUDED_


text:
var get;

get = require('../index').get;

describe('GET CLI', function() {
  return it('should show name', function(done) {
    return get("Hello World");
  });
});


text:
namespace Poco {

class Foundation_API ThreadImpl
{
public:
    typedef DWORD TIDImpl;
	typedef void (*Callable)(void*);
	typedef DWORD (WINAPI *Entry)(LPVOID);

	struct CallbackData
	{
		CallbackData(): callback(0), pData(0)
		{
		}

		Callable  callback;
		void*     pData;
	};

	enum Priority
	{
		PRIO_LOWEST_IMPL  = THREAD_PRIORITY_LOWEST,
		PRIO_LOW_IMPL     = THREAD_PRIORITY_BELOW_NORMAL,
		PRIO_NORMAL_IMPL  = THREAD_PRIORITY_NORMAL,
		PRIO_HIGH_IMPL    = THREAD_PRIORITY_ABOVE_NORMAL,
		PRIO_HIGHEST_IMPL = THREAD_PRIORITY_HIGHEST
	};

	ThreadImpl();
	~ThreadImpl();

	TIDImpl tidImpl() const;
	void setPriorityImpl(int prio);
	int getPriorityImpl() const;
	void setOSPriorityImpl(int prio);
	int getOSPriorityImpl() const;
	static int getMinOSPriorityImpl();
	static int getMaxOSPriorityImpl();
	void setStackSizeImpl(int size);
	int getStackSizeImpl() const;
	void startImpl(Runnable& target);
	void startImpl(Callable target, void* pData = 0);

	void joinImpl();
	bool joinImpl(long milliseconds);
	bool isRunningImpl() const;
	static void sleepImpl(long milliseconds);
	static void yieldImpl();
	static ThreadImpl* currentImpl();
	static TIDImpl currentTidImpl();

protected:
	static DWORD WINAPI runnableEntry(LPVOID pThread);
	static DWORD WINAPI callableEntry(LPVOID pThread);

	void createImpl(Entry ent, void* pData);
	void threadCleanup();

private:
	class CurrentThreadHolder
	{
	public:
		CurrentThreadHolder(): _slot(TlsAlloc())
		{
			if (_slot == TLS_OUT_OF_INDEXES)
				throw SystemException("cannot allocate thread context key");
		}
		~CurrentThreadHolder()
		{
			TlsFree(_slot);
		}
		ThreadImpl* get() const
		{
			return reinterpret_cast<ThreadImpl*>(TlsGetValue(_slot));
		}
		void set(ThreadImpl* pThread)
		{
			TlsSetValue(_slot, pThread);
		}

	private:
		DWORD _slot;
	};

	Runnable*    _pRunnableTarget;
	CallbackData _callbackTarget;
	HANDLE       _thread;
	DWORD        _threadId;
	int          _prio;
	int          _stackSize;

	static CurrentThreadHolder _currentThreadHolder;
};

//
// inlines
//
inline int ThreadImpl::getPriorityImpl() const
{
	return _prio;
}

inline int ThreadImpl::getOSPriorityImpl() const
{
	return _prio;
}

inline int ThreadImpl::getMinOSPriorityImpl()
{
	return PRIO_LOWEST_IMPL;
}

inline int ThreadImpl::getMaxOSPriorityImpl()
{
	return PRIO_HIGHEST_IMPL;
}

inline void ThreadImpl::sleepImpl(long milliseconds)
{
	Sleep(DWORD(milliseconds));
}

inline void ThreadImpl::yieldImpl()
{
	Sleep(0);
}

inline void ThreadImpl::setStackSizeImpl(int size)
{
	_stackSize = size;
}

inline int ThreadImpl::getStackSizeImpl() const
{
	return _stackSize;
}

inline ThreadImpl::TIDImpl ThreadImpl::tidImpl() const
{
	return _threadId;
}

} // namespace Poco

#endif // Foundation_Thread_WINCE_INCLUDED


text:
using EDDiscovery.DB;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace EDDiscovery.EliteDangerous.JournalEvents
{
    //When Written: detailed discovery scan of a star, planet or moon
    //Parameters(star)
    //•	Bodyname: name of body
    //•	DistanceFromArrivalLS
    //•	StarType: Stellar classification (for a star)
    //•	StellarMass: mass as multiple of Sol's mass
    //•	Radius
    //•	AbsoluteMagnitude
    //•	OrbitalPeriod (seconds)
    //•	RotationPeriod (seconds)
    //•	Rings: [ array ] - if present
    //
    //Parameters(Planet/Moon)
    //•	Bodyname: name of body
    //•	DistanceFromArrivalLS
    //•	TidalLock: 1 if tidally locked
    //•	TerraformState: Terraformable, Terraforming, Terraformed, or null
    //•	PlanetClass
    //•	Atmosphere
    //•	Volcanism
    //•	SurfaceGravity
    //•	SurfaceTemperature
    //•	SurfacePressure
    //•	Landable: true (if landable)
    //•	Materials: JSON object with material names and percentage occurrence
    //•	OrbitalPeriod (seconds)
    //•	RotationPeriod (seconds)
    //•	Rings [ array of info ] - if rings present
    //
    // Rings properties
    //•	Name
    //•	RingClass
    //•	MassMT - ie in megatons
    //•	InnerRad
    //•	OuterRad
    //
    public class JournalScan : JournalEntry
    {
        private const double solarRadius_m = 695700000;
        private const double oneAU_m = 149597870000;
        private const double oneDay_s = 86400;
        private const double oneMoon_MT = 73420000000000;

        public JournalScan(JObject evt) : base(evt, JournalTypeEnum.Scan)
        {
            BodyName = JSONHelper.GetStringDef(evt["BodyName"]);
            StarType = JSONHelper.GetStringNull(evt["StarType"]);

            DistanceFromArrivalLS = JSONHelper.GetDouble(evt["DistanceFromArrivalLS"]);

            nAge = JSONHelper.GetDoubleNull(evt["Age_MY"]);
            nStellarMass = JSONHelper.GetDoubleNull(evt["StellarMass"]);
            nRadius = JSONHelper.GetDoubleNull(evt["Radius"]);
            nAbsoluteMagnitude = JSONHelper.GetDoubleNull(evt["AbsoluteMagnitude"]);
            nRotationPeriod = JSONHelper.GetDoubleNull(evt["RotationPeriod"]);

            nOrbitalPeriod = JSONHelper.GetDoubleNull(evt["OrbitalPeriod"]);
            nSemiMajorAxis = JSONHelper.GetDoubleNull(evt["SemiMajorAxis"]);
            nEccentricity = JSONHelper.GetDoubleNull(evt["Eccentricity"]);
            nOrbitalInclination = JSONHelper.GetDoubleNull(evt["OrbitalInclination"]);
            nPeriapsis = JSONHelper.GetDoubleNull(evt["Periapsis"]);

            Rings = evt["Rings"]?.ToObject<StarPlanetRing[]>();

            nTidalLock = JSONHelper.GetBoolNull(evt["TidalLock"]);
            TerraformState = JSONHelper.GetStringNull(evt["TerraformState"]);
            PlanetClass = JSONHelper.GetStringNull(evt["PlanetClass"]);
            Atmosphere = JSONHelper.GetStringNull(evt["Atmosphere"]);
            Volcanism = JSONHelper.GetStringNull(evt["Volcanism"]);
            nMassEM = JSONHelper.GetDoubleNull(evt["MassEM"]);
            nSurfaceGravity = JSONHelper.GetDoubleNull(evt["SurfaceGravity"]);
            nSurfaceTemperature = JSONHelper.GetDoubleNull(evt["SurfaceTemperature"]);
            nSurfacePressure = JSONHelper.GetDoubleNull(evt["SurfacePressure"]);
            nLandable = JSONHelper.GetBoolNull(evt["Landable"]);

            Materials = evt["Materials"]?.ToObject<Dictionary<string, double>>();

            if (IsStar)
                StarTypeID = Bodies.StarStr2Enum(StarType);
            else
                PlanetTypeID = Bodies.PlanetStr2Enum(PlanetClass);

            AtmosphereID = Bodies.AtmosphereStr2Enum(Atmosphere, out AtmosphereProperty);
            VolcanismID = Bodies.VolcanismStr2Enum(Volcanism, out VolcanismProperty);
        }

        private void ConvertFromEDSMBodies()
        {
            EventTimeUTC = DateTime.UtcNow;
            throw new NotImplementedException();
        }

        public string BodyName { get; set; }
        public double DistanceFromArrivalLS { get; set; }
        public string StarType { get; set; }                            // null if no StarType
        public bool IsStar { get { return !String.IsNullOrEmpty(StarType); } }

        public double? nAge { get; set; }
        public double? nStellarMass { get; set; }
        public double? nRadius { get; set; }
        public double? nAbsoluteMagnitude { get; set; }
        public double? nRotationPeriod { get; set; }

        public double? nOrbitalPeriod { get; set; }
        public double? nSemiMajorAxis;
        public double? nEccentricity;
        public double? nOrbitalInclination;
        public double? nPeriapsis;

        public EDStar StarTypeID { get; }
        public EDPlanet PlanetTypeID { get; }

        public EDAtmosphereType AtmosphereID { get; }
        public EDAtmosphereProperty AtmosphereProperty;
        public EDVolcanism VolcanismID { get; }
        public EDVolcanismProperty VolcanismProperty;

        public class StarPlanetRing
        {
            public string Name;
            public string RingClass;
            public double MassMT;
            public double InnerRad;
            public double OuterRad;
        }

        public StarPlanetRing[] Rings { get; set; }
        public bool HasRings { get { return Rings != null && Rings.Length > 0; } }

        public bool? nTidalLock { get; set; }
        public string TerraformState { get; set; }
        public string PlanetClass { get; set; }
        public string Atmosphere { get; set; }
        public string Volcanism { get; set; }
        public double? nMassEM { get; set; } // not in description of event
        public double? nSurfaceGravity { get; set; } // not in description of event
        public double? nSurfaceTemperature { get; set; }
        public double? nSurfacePressure { get; set; }
        public bool? nLandable { get; set; }

        public bool IsLandable { get { return nLandable.HasValue && nLandable.Value; } }
        public bool HasMaterials { get { return Materials != null && Materials.Any(); } }
        public Dictionary<string, double> Materials { get; set; }

        //public string MaterialsString { get { return jEventData["Materials"].ToString(); } }

         public bool IsEDSMBody
        {
            get
            {
                return JSONHelper.GetBool(jEventData["EDDFromEDSMBodie"], false);
            }
        }

        public override void FillInformation(out string summary, out string info, out string detailed)
        {
            base.FillInformation(out summary, out info, out detailed);
            summary = $"Scan of {BodyName}";
        }

        public string DisplayString(bool printbodyname = true, int indent = 0)
        {
            string inds = new string(' ' , indent);

            StringBuilder scanText = new StringBuilder();

            scanText.Append(inds);

            if (printbodyname)
                scanText.AppendFormat("{0}\n\n", BodyName);

            if (IsStar)
            {
                scanText.AppendFormat(GetStarTypeImage().Item2);
            }
            else
            {
                scanText.AppendFormat("{0}", System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.
                                        ToTitleCase(PlanetClass.ToLower()).Replace("Ii", "II").Replace("Ii", "II").Replace("Iv", "IV"));
            }

            if (PlanetClass != null && !PlanetClass.ToLower().Contains("gas"))
            {
                scanText.AppendFormat((Atmosphere == null || Atmosphere == String.Empty) ? ", No Atmosphere" : ( ", " +
                                                            System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(Atmosphere.ToLower()) )
                                     );
            }

            if (IsLandable)
                scanText.AppendFormat(", Landable");

            scanText.AppendFormat("\n");

            if (nAge.HasValue)
                scanText.AppendFormat("Age: {0} million years\n", nAge.Value.ToString("N0"));

            if (nStellarMass.HasValue)
                scanText.AppendFormat("Solar Masses: {0:0.00}\n", nStellarMass.Value);

            if (nMassEM.HasValue)
                scanText.AppendFormat("Earth Masses: {0:0.0000}\n", nMassEM.Value);

            if (nRadius.HasValue)
            {
                if ( IsStar )
                    scanText.AppendFormat("Solar Radius: {0:0.00} Sols\n", (nRadius.Value / solarRadius_m));
                else
                    scanText.AppendFormat("Body Radius: {0:0.00}km\n", (nRadius.Value / 1000));
            }

            if (nSurfaceTemperature.HasValue)
                scanText.AppendFormat("Surface Temp: {0}K\n", nSurfaceTemperature.Value.ToString("N0"));

            if (nSurfaceGravity.HasValue)
                scanText.AppendFormat("Gravity: {0:0.0}g\n", nSurfaceGravity.Value / 9.8);

            if (nSurfacePressure.HasValue && nSurfacePressure.Value > 0.00 && !PlanetClass.ToLower().Contains("gas"))
                if (nSurfacePressure.Value > 1000) { scanText.AppendFormat("Surface Pressure: {0} Atmospheres\n", (nSurfacePressure.Value / 100000).ToString("N2")); }
                else { { scanText.AppendFormat("Surface Pressure: {0} Pa\n", (nSurfacePressure.Value).ToString("N2")); } }

            if (Volcanism != null)
                scanText.AppendFormat("Volcanism: {0}\n", Volcanism == String.Empty ? "No Volcanism" : System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.
                                                                                ToTitleCase(Volcanism.ToLower()));

            if (DistanceFromArrivalLS > 0)
                scanText.AppendFormat("Distance from Arrival Point {0:N1}ls\n", DistanceFromArrivalLS);

            if (nOrbitalPeriod.HasValue && nOrbitalPeriod > 0)
                scanText.AppendFormat("Orbital Period: {0} days\n", (nOrbitalPeriod.Value / oneDay_s).ToString("N1"));

            if (nSemiMajorAxis.HasValue)
            {
                if ( IsStar || nSemiMajorAxis.Value > oneAU_m/10 )
                    scanText.AppendFormat("Semi Major Axis: {0:0.00}AU\n", (nSemiMajorAxis.Value / oneAU_m));
                else
                    scanText.AppendFormat("Semi Major Axis: {0}km\n", (nSemiMajorAxis.Value / 1000).ToString("N1"));
            }

            if (nEccentricity.HasValue)
                scanText.AppendFormat("Orbital Eccentricity: {0:0.000}°\n", nEccentricity.Value);

            if (nOrbitalInclination.HasValue)
                scanText.AppendFormat("Orbital Inclination: {0:0.000}°\n", nOrbitalInclination.Value);

            if (nPeriapsis.HasValue)
                scanText.AppendFormat("Arg Of Periapsis: {0:0.000}°\n", nPeriapsis.Value);

            if (nAbsoluteMagnitude.HasValue)
                scanText.AppendFormat("Absolute Magnitude: {0:0.00}\n", nAbsoluteMagnitude.Value);

            if (nRotationPeriod.HasValue)
                scanText.AppendFormat("Rotation Period: {0} days\n", (nRotationPeriod.Value / oneDay_s).ToString("N1"));

            if (nTidalLock.HasValue && nTidalLock.Value)
                scanText.Append("Tidally locked\n");

            if ( TerraformState != null && TerraformState == "Terraformable")
                scanText.Append("Candidate for terraforming\n");

            if (HasRings)
            {
                scanText.Append("\n");
                if (IsStar)
                {
                    scanText.AppendFormat("Belt{0}", Rings.Count() == 1 ? ":" : "s:");
                    for (int i = 0; i < Rings.Length; i++)
                    {
                        if (Rings[i].MassMT > 7342000000) { scanText.Append("\n" + RingInformation(i, 1.0 / oneMoon_MT, " Moons")); }
                        else { scanText.Append("\n" + RingInformation(i)); }
                    }
                }
                else
                {
                    scanText.AppendFormat("Ring{0}", Rings.Count() == 1 ? ":" : "s:");
                    for (int i = 0; i < Rings.Length; i++)
                        scanText.Append("\n" + RingInformation(i));
                }
            }

            if (HasMaterials)
            {
                scanText.Append("\n" + DisplayMaterials(2) + "\n");
            }

            if (IsStar)
            {
                string hz = HabitableZone();
                if ( hz != null )
                    scanText.Append("\n" + hz);
            }

            if (scanText.Length > 0 && scanText[scanText.Length - 1] == '\n')
                scanText.Remove(scanText.Length - 1, 1);

            return scanText.ToNullSafeString().Replace("\n", "\n" + inds);
        }

        public string DisplayMaterials(int indent = 0)
        {
            StringBuilder scanText = new StringBuilder();
            string indents = new string(' ', indent);

            scanText.Append("Materials:\n");
            foreach (KeyValuePair<string, double> mat in Materials)
            {
                EDDiscovery2.DB.MaterialCommodities mc = EDDiscovery2.DB.MaterialCommodities.GetCachedMaterial(mat.Key);
                if (mc != null)
                    scanText.AppendFormat(indents + "{0} ({1}) {2} {3}%\n", mc.name, mc.shortname, mc.type, mat.Value.ToString("N1"));
                else
                    scanText.AppendFormat(indents + "{0} {1}%\n", System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(mat.Key.ToLower()),
                                                                mat.Value.ToString("N1"));
            }

            if (scanText.Length > 0 && scanText[scanText.Length - 1] == '\n')
                scanText.Remove(scanText.Length - 1, 1);

            return scanText.ToNullSafeString();
        }

        public string RingInformationMoons(int ringno)
        {
            return RingInformation(ringno, 1 / oneMoon_MT, " Moons");
        }

        public string RingInformation(int ringno, double scale = 1, string scaletype = " MT")
        {
            StarPlanetRing ring = Rings[ringno];
            StringBuilder scanText = new StringBuilder();
            scanText.AppendFormat("  {0} ({1})\n", ring.Name, DisplayStringFromRingClass(ring.RingClass));
            scanText.AppendFormat("  Mass: {0}{1}\n", (ring.MassMT * scale).ToString("N4"),scaletype );
            if (IsStar && ring.InnerRad > 3000000)
            {
                scanText.AppendFormat("  Inner Radius: {0:0.00}ls\n", (ring.InnerRad / 300000000));
                scanText.AppendFormat("  Outer Radius: {0:0.00}ls\n", (ring.OuterRad / 300000000));
            }
            else
            {
                scanText.AppendFormat("  Inner Radius: {0}km\n", (ring.InnerRad / 1000).ToString("N0"));
                scanText.AppendFormat("  Outer Radius: {0}km\n", (ring.OuterRad / 1000).ToString("N0"));
            }
            return scanText.ToNullSafeString();
        }

        internal string DisplayStringFromRingClass(string ringClass)
        {
            switch (ringClass)
            {
                case "eRingClass_Icy":
                    return "Icy";
                case "eRingClass_Rocky":
                    return "Rocky";
                case "eRingClass_MetalRich":
                    return "Metal Rich";
                case "eRingClass_Metalic":
                    return "Metallic";
                case "eRingClass_RockyIce":
                    return "Rocky Ice";
                default:
                    return ringClass.Replace("eRingClass_","");
            }
        }

        public Tuple<System.Drawing.Image, string> GetStarTypeImage()           // give image and description to star class
        {
            System.Drawing.Image ret = EDDiscovery.Properties.Resources.Star_K1IV;

            switch (StarTypeID)       // see journal, section 11.2
            {
                case EDStar.O:
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.O, string.Format("Luminous Hot Main Sequence star", StarType));

                case EDStar.B:
                    // also have an B1V
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.B6V_Blueish, string.Format("Luminous Blue Main Sequence star", StarType));

                case EDStar.A:
                    // also have an A3V..
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.A9III_White, string.Format("Bluish-White Main Sequence star", StarType));

                case EDStar.F:
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.F5VAB, string.Format("White Main Sequence star", StarType));

                case EDStar.G:
                    // also have a G8V
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.G1IV, string.Format("Yellow Main Sequence star", StarType));

                case EDStar.K:
                    // also have a K0V
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.Star_K1IV, string.Format("Orange Main Sequence {0} star", StarType));
                case EDStar.M:
                    // also have a M1VA
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.M5V, string.Format("Red Main Sequence {0} star", StarType));

                // dwarfs
                case EDStar.L:
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.L3V, string.Format("Dark Red Non Main Sequence {0} star", StarType));
                case EDStar.T:
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.T4V, string.Format("Methane Dwarf star", StarType));
                case EDStar.Y:
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.Y2, string.Format("Brown Dwarf star", StarType));

                // proto stars
                case EDStar.AeBe:    // Herbig
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.DefaultStar, "Herbig Ae/Be");
                case EDStar.TTS:     // seen in logs
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.DefaultStar, "T Tauri");

                // wolf rayet
                case EDStar.W:
                case EDStar.WN:
                case EDStar.WNC:
                case EDStar.WC:
                case EDStar.WO:
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.DefaultStar, string.Format("Wolf-Rayet {0} star", StarType));

                // Carbon
                case EDStar.CS:
                case EDStar.C:
                case EDStar.CN:
                case EDStar.CJ:
                case EDStar.CHd:
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.C7III, string.Format("Carbon {0} star", StarType));

                case EDStar.MS: //seen in log
                case EDStar.S:   // seen in log
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.DefaultStar, string.Format("Unknown Type {0} star", StarType));

                // white dwarf
                case EDStar.D:
                case EDStar.DA:
                case EDStar.DAB:
                case EDStar.DAO:
                case EDStar.DAZ:
                case EDStar.DAV:
                case EDStar.DB:
                case EDStar.DBZ:
                case EDStar.DBV:
                case EDStar.DO:
                case EDStar.DOV:
                case EDStar.DQ:
                case EDStar.DC:
                case EDStar.DCV:
                case EDStar.DX:
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.DA6VII_White, string.Format("White Dwarf ({0}) star", StarType));

                case EDStar.N:
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.Neutron_Star, "Neutron Star");

                case EDStar.H:

                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.Black_Hole, "Black Hole");

                case EDStar.X:
                    // currently speculative, not confirmed with actual data... in journal
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.DefaultStar, "Exotic");

                // Journal.. really?  need evidence these actually are formatted like this.

                //case EDStar.b"supermassiveblackhole":
                 //   return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.Black_Hole, "Super Massive Black Hole");
                case EDStar.A_BlueWhiteSuperGiant:
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.DefaultStar, "Blue White Giant");
                case EDStar.F_WhiteSuperGiant:
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.DefaultStar, "F White Super Giant");
                case EDStar.M_RedSuperGiant:
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.DefaultStar, "M Red Super Giant");
                case EDStar.M_RedGiant:
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.DefaultStar, "M Red Giant");
                case EDStar.K_OrangeGiant:
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.DefaultStar, "K Orange Giant");
                case EDStar.RoguePlanet:
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.DefaultStar, "Rouge Planet");

                default:
                    return new Tuple<System.Drawing.Image, string>(EDDiscovery.Properties.Resources.DefaultStar, string.Format("Class {0} star\n", StarType.Replace("_", " ")));
            }
        }

        static public System.Drawing.Image GetStarImageNotScanned()
        {
            return EDDiscovery.Properties.Resources.Globe_yellow;
        }

        public System.Drawing.Image GetPlanetClassImage()
        {
            string name = PlanetClass.ToLower();

            if (name.Contains("gas"))
            {
                if (name.Contains("helium"))
                    return EDDiscovery.Properties.Resources.Helium_Rich_Gas_Giant1;
                else if (name.Contains("water"))
                    return EDDiscovery.Properties.Resources.Gas_giant_water_based_life_Brown3;
                else if (name.Contains("ammonia"))
                    return EDDiscovery.Properties.Resources.Gas_giant_ammonia_based_life1;
                else if (name.Contains("iv"))
                    return EDDiscovery.Properties.Resources.Class_I_Gas_Giant_Brown2;               // MISSING.
                else if (name.Contains("iii"))
                    return EDDiscovery.Properties.Resources.Class_III_Gas_Giant_Blue3;
                else if (name.Contains("ii"))
                    return EDDiscovery.Properties.Resources.Class_II_Gas_Giant_Sand1;
                else if (name.Contains("v"))
                    return EDDiscovery.Properties.Resources.Class_I_Gas_Giant_Brown2;               // MISSING.
                else
                    return EDDiscovery.Properties.Resources.Class_I_Gas_Giant_Brown2;
            }
            else if (name.Contains("ammonia"))
                return EDDiscovery.Properties.Resources.Ammonia_Brown;      // also have orange.
            else if (name.Contains("earth"))
                return EDDiscovery.Properties.Resources.Earth_Like_Standard;
            else if (name.Contains("ice"))
                return EDDiscovery.Properties.Resources.Rocky_Ice_World_Sol_Titan;
            else if (name.Contains("icy"))
                return EDDiscovery.Properties.Resources.Icy_Body_Greenish1;
            else if (name.Contains("water"))
            {
                if (name.Contains("giant"))
                    return EDDiscovery.Properties.Resources.Water_Giant1;
                else
                    return EDDiscovery.Properties.Resources.Water_World_Poles_Cloudless4;
            }
            else if (name.Contains("metal"))
            {
                if (name.Contains("rich"))
                    return EDDiscovery.Properties.Resources.metal_rich;
                else if (nSurfaceTemperature > 400)
                    return EDDiscovery.Properties.Resources.High_metal_content_world_Lava1;
                else if (nSurfaceTemperature > 250)
                    return EDDiscovery.Properties.Resources.High_metal_content_world_Mix3;
                else
                    return EDDiscovery.Properties.Resources.High_metal_content_world_Orange8;
            }
            else if (name.Contains("rocky"))
                return EDDiscovery.Properties.Resources.Rocky_Body_Sand2;
            else
                return EDDiscovery.Properties.Resources.Globe;
        }

        static public System.Drawing.Image GetPlanetImageNotScanned()
        {
            return EDDiscovery.Properties.Resources.Globe;
        }

        static public System.Drawing.Image GetMoonImageNotScanned()
        {
            return EDDiscovery.Properties.Resources.Icy_Body_Greenish1;
        }

        internal double GetMaterial(string v)
        {
            if (Materials == null)
                return 0.0;

            if (!Materials.ContainsKey(v.ToLower()))
                return 0.0;

            return Materials[v.ToLower()];
        }

        public static System.Drawing.Bitmap Icon { get { return EDDiscovery.Properties.Resources.scan; } }

        public bool IsStarNameRelated(string starname)
        {
            if (BodyName.Length >= starname.Length)
            {
                string s = BodyName.Substring(0, starname.Length);
                return starname.Equals(s, StringComparison.InvariantCultureIgnoreCase);
            }
            else
                return false;
        }

        public string IsStarNameRelatedReturnRest(string starname)          // null if not related, else rest of string
        {
            if (BodyName.Length >= starname.Length)
            {
                string s = BodyName.Substring(0, starname.Length);
                if (starname.Equals(s, StringComparison.InvariantCultureIgnoreCase))
                    return BodyName.Substring(starname.Length).Trim();
            }

            return null;
        }

        // Habitable zone calculations, formulae cribbed from JackieSilver's HabZone Calculator with permission
        private double DistanceForBlackBodyTemperature(double targetTemp)
        {
            double top = Math.Pow(nRadius.Value, 2.0) * Math.Pow(nSurfaceTemperature.Value, 4.0);
            double bottom = 4.0 * Math.Pow(targetTemp, 4.0);
            double radius_metres = Math.Pow(top / bottom, 0.5);
            return radius_metres / 300000000;
        }

        private string HabitableZone()
        {
            if (nRadius.HasValue && nSurfaceTemperature.HasValue)
            {
                StringBuilder habZone = new StringBuilder();
                habZone.AppendFormat("Habitable Zone Approx. {0}ls to {1}ls\n",
                    DistanceForBlackBodyTemperature(315).ToString("N0"),
                    DistanceForBlackBodyTemperature(223).ToString("N0"));
                if (nSemiMajorAxis.HasValue && nSemiMajorAxis.Value > 0)
                {
                    habZone.AppendFormat(" (This star only, others not considered)\n");
                }
                return habZone.ToNullSafeString();
            }
            else
                return null;
        }

    }

}


text:
"""Package contenant le paramètre 'créer' de la commande 'éditeur'."""

from primaires.interpreteur.masque.parametre import Parametre

class PrmCreer(Parametre):

    """Paramètre 'créer de la commande 'éditeur'."""

    def __init__(self):
        """Constructeur du paramètre."""
        Parametre.__init__(self, "créer", "create")
        self.schema = "<cle>"
        self.aide_courte = "crée l'éditeur personnalisé"
        self.aide_longue = \
            "Cette commande permet de créer l'éditeur personnalisé " \
            "lié à une structure. Vous devez passer en paramètre la " \
            "clé de l'éditeur à créer, qui est également la clé " \
            "de la structure liée."

    def interpreter(self, personnage, dic_masques):
        """Méthode d'interprétation de commande"""
        cle = dic_masques["cle"].cle

        if cle in importeur.scripting.editeurs:
            personnage << "|err|L'éditeur {} existe déjà.|ff|".format(
                    repr(cle))
            return

        editeur = importeur.scripting.creer_editeur(cle)
        editeur = importeur.interpreteur.construire_editeur("editeur",
                personnage, editeur)
        personnage.contextes.ajouter(editeur)
        editeur.actualiser()


text:
<!DOCTYPE html>

	<TITLE> ZTREE DEMO - Radio chkDisabled</TITLE>
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<link rel="stylesheet" href="../../../css/demo.css" type="text/css">
	<link rel="stylesheet" href="../../../css/zTreeStyle/zTreeStyle.css" type="text/css">

Radio chkDisabled Demo

[ File Path: excheck/radio_chkDisabled.html ]

1, Explanation of 'setChkDisabled' method

'setChkDisabled' method can set the node's checkbox / radio to be disabled or abled. See the API documentation for more related contents.

Try:

					    [ be disabled ]
					    [ be abled ]

2, Explanation of setting

This Demo only shows how use the 'nocheck' attribute, detailed configuration information, please refer to 'Radio Operation'

3, Explanation of treeNode

1), If you need to initialize the node don't show radio, please set treeNode.chkDisabled attribute. See the API documentation for more related contents.

2), By the way, please see the 'Radio Operation' Demo.


text:
<?php

namespace sndsgd\http\data\decoder;

/**
 * A urlencoded content decoder
 */
class UrlDecoder extends DecoderAbstract
{
    /**
     * @inheritDoc
     */
    public function decode(): array
    {
        $querystring = @file_get_contents($this->path, true);
        if ($querystring === false) {
            throw new \RuntimeException(
                \sndsgd\Error::createMessage("failed to read input stream")
            );
        }

        $decoder = new QueryStringDecoder($this->contentLength, $this->values);
        return $decoder->decode($querystring);
    }
}


text:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.jys.bluetoothproj.activity.actifindbtdevice"
    android:background="@color/ricewhitegb">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <!-- top -->
        <!-- 开始:自己的actionbar -->

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/heightActiBar"
            android:orientation="vertical" >

            <TextView
                android:layout_width="match_parent"
                android:layout_height="@dimen/heightActiBarWord"
                android:gravity="center"
                android:text="蓝牙设备"
                android:textColor="@color/colorActionBarWord"
                android:textSize="@dimen/textsizeActiBarWord" />

            <View
                android:layout_width="match_parent"
                android:layout_height="1dip"
                android:background="#DCDCDC" >
            </View>
        </LinearLayout>

        <!-- 结束:自己的actionbar -->

        <!-- bottom -->

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <!-- EditText========================================================= -->

            <EditText
                android:id="@+id/actifindbtdevice_et_localbtinfo"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:enabled="false"
                android:hint="本机蓝牙信息"
                android:textSize="18sp" >
            </EditText>

            <EditText
                android:id="@+id/actifindbtdevice_et_alreadyconnectedbtinfo"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:enabled="false"
                android:hint="已配对蓝牙设备信息"
                android:textSize="18sp" >
            </EditText>

            <EditText
                android:id="@+id/actifindbtdevice_et_remotebtinfo"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:enabled="false"
                android:hint="搜索到的外围蓝牙设备信息"
                android:textSize="18sp" >
            </EditText>

            <!-- 搜索到的外围蓝牙设备显示在此处========================================================= -->

            <LinearLayout
                android:id="@+id/actifindbtdevice_ll_forshowdiscoveredBtDevices"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >
            </LinearLayout>
            <!-- Button========================================================= -->

            <Button
                android:id="@+id/actifindbtdevice_btn_getlocalbtinfo"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="获取本地蓝牙设备信息" />

            <Button
                android:id="@+id/actifindbtdevice_btn_getalreadyconnetctedbtinfo"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="获取已配对蓝牙设备信息" />

            <Button
                android:id="@+id/actifindbtdevice_btn_getremotebinfo"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="搜索" />

            <!-- ========================================================= -->
        </LinearLayout>
    </LinearLayout>

</ScrollView>


text:
<?php
declare(strict_types=1);

namespace ManaPHP\Http\Session;

use ManaPHP\Component;

/**
 * @property-read \ManaPHP\Http\SessionInterface $session
 */
class Bag extends Component implements BagInterface
{
    protected string $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function destroy(): void
    {
        $this->session->remove($this->name);
    }

    public function set(string $property, mixed $value): static
    {
        $data = $this->session->get($this->name, []);
        $data[$property] = $value;

        $this->session->set($this->name, $data);

        return $this;
    }

    public function all(): array
    {
        return $this->session->get($this->name, []);
    }

    public function get(string $property, mixed $default = null): mixed
    {
        $data = $this->session->get($this->name, []);

        return $data[$property] ?? $default;
    }

    public function has(string $property): bool
    {
        $data = $this->session->get($this->name, []);

        return isset($data[$property]);
    }

    public function remove(string $property): void
    {
        $data = $this->session->get($this->name, []);
        unset($data[$property]);

        $this->session->set($this->name, $data);
    }
}


text:
INSERT INTO [commands].[Server]
           ([ServerID]
           ,[Command]
           ,[Payload])
	OUTPUT INSERTED.[ID]
     VALUES
           (@ServerID
           ,@Command
           ,@Payload
		   );