text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->

<project name="camel-example-tracer" default="run" basedir=".">

  <import file="../common_build.xml"/>

  <fail unless="env.HIBERNATE_CORE_HOME" message="You must download hibernate core and set HIBERNATE_CORE_HOME to run this demo."/>
  <fail unless="env.HIBERNATE_EM_HOME" message="You must download hibernate entity manager and set HIBERNATE_EM_HOME to run this demo."/>
  <fail unless="env.HSQLDB_HOME" message="You must download HSQLDB and set HSQLDB_HOME to run this demo."/>

  <property name="project.name" value="camel-example-tracer"/>

  <path id="sample.build.classpath">
    <fileset dir="${camel.lib}">
      <include name="**/camel-jpa-*.jar"/>
      <include name="**/camel-stream-*.jar"/>
      <include name="**/commons-collections-*.jar"/>
      <exclude name="**/*-tests.jar"/>
    </fileset>
    <path refid="spring.classpath"/>
    <path refid="camel.spring.classpath"/>
    <path refid="hibernate.classpath"/>
  </path>

  <target name="run" depends="build" description="Compile and run the sample">
    <camelrun mainClass="org.apache.camel.example.tracer.Main"/>
  </target>

</project>


text:
<?php

namespace Simpletools\Db\Mysql;

class Driver extends \mysqli
{
	protected $_closed 	= false;
	protected $_db 		= '';

	public function isClosed()
	{
		return $this->_closed;
	}

	public function close()
	{
		$this->_closed = true;
		parent::close();
	}

	public function select_db($db)
	{
		$this->_db = $db;
		parent::select_db($db);
	}

	public function real_connect($host=NULL,$user=NULL,$password=NULL,$database=NULL,$port=NULL,$socket=NULL,$flags=NULL)
	{
		$this->_db = $database;
		parent::real_connect($host,$user,$password,$database,$port,$socket,$flags);
	}

	public function getDb()
	{
		return $this->_db;
	}

	public function __destruct()
	{
		$this->close();
	}
}

?>

redpajama_set_name: RedPajamaGithub


text:
package rabbithole

import (
	"encoding/json"
	"net/http"
	"net/url"
)

// UserLimitsValues are properties used to modify virtual host limits (max-connections, max-channels)
type UserLimitsValues map[string]int

// UserLimits are properties used to delete virtual host limits (max-connections, max-channels)
type UserLimits []string

// UserLimitsInfo holds information about the current user limits
type UserLimitsInfo struct {
	User  string           `json:"user"`
	Value UserLimitsValues `json:"value"`
}

// GetAllUserLimits gets all users limits.
func (c *Client) GetAllUserLimits() (rec []UserLimitsInfo, err error) {
	req, err := newGETRequest(c, "user-limits")
	if err != nil {
		return nil, err
	}

	if err = executeAndParseRequest(c, req, &rec); err != nil {
		return nil, err
	}

	return rec, nil
}

// GetUserLimits gets a user limits.
func (c *Client) GetUserLimits(username string) (rec []UserLimitsInfo, err error) {
	req, err := newGETRequest(c, "user-limits/"+url.PathEscape(username))
	if err != nil {
		return nil, err
	}

	if err = executeAndParseRequest(c, req, &rec); err != nil {
		return nil, err
	}

	return rec, nil
}

// PutUserLimits puts limits of a user.
func (c *Client) PutUserLimits(username string, limits UserLimitsValues) (res *http.Response, err error) {
	for limitName, limitValue := range limits {
		body, err := json.Marshal(struct {
			Value int `json:"value"`
		}{Value: limitValue})
		if err != nil {
			return nil, err
		}

		req, err := newRequestWithBody(c, "PUT", "user-limits/"+url.PathEscape(username)+"/"+limitName, body)
		if err != nil {
			return nil, err
		}

		if res, err = executeRequest(c, req); err != nil {
			return nil, err
		}
	}

	return res, nil
}

// DeleteUserLimits deletes limits of a user.
func (c *Client) DeleteUserLimits(username string, limits UserLimits) (res *http.Response, err error) {
	for _, limit := range limits {
		req, err := newRequestWithBody(c, "DELETE", "user-limits/"+url.PathEscape(username)+"/"+limit, nil)
		if err != nil {
			return nil, err
		}

		if res, err = executeRequest(c, req); err != nil {
			return nil, err
		}
	}

	return res, nil
}


text:
<?php
	// use Yii;
	use yii\helpers\Url;
	use yii\helpers\Html;
	use yii\base\Widget;
	use app\components\LanguageSwitcher\LanguageSwitcherWidget;
	use app\assets\ThemesAsset;

	$bundle = ThemesAsset::register($this);

	$this -> beginContent('@app/themes/desktop/views/layouts/main.php');
?>

			<?=
				// Изображение логотипа.
				Html::img(
					$bundle -> baseUrl . '/images/LogoSmall.png'
					// Yii::t('Dictionary', 'Filler')
				);
			?>

<?= Yii::t('Dictionary', 'Games'); ?>

<?= Yii::t('Dictionary', 'Winnings'); ?>

<?= Yii::t('Dictionary', 'Rating'); ?>

0

0

0 %

			<?=
				// Виджет переключателя языка.
				LanguageSwitcherWidget::widget(array(
					'Languages' => Yii::$app -> params['Languages'],
					'CurrentLanguageCode' => Yii::$app -> language,
				));
			?>
			<div class="Help-Label BlueLight-Box" title="<?= Yii::t('Dictionary', 'Game rules'); ?>"  id="Button-Help">
				?

			<div class="Sound-Label Sound-Label-On BlueLight-Box" title="<?= Yii::t('Dictionary', 'Sound switcher'); ?>" id="Button-Sound">

<?= Yii::t('Dictionary', 'Games'); ?>

<?= Yii::t('Dictionary', 'Winnings'); ?>

<?= Yii::t('Dictionary', 'Rating'); ?>

0

0

0 %

	<?= $content; ?>

<?php
	$this -> endContent();
?>


text:
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'TableIcon',
  template: '<svg class="hi hi-fw"><use xlink:href="#hueTableSymbol" /></svg>'
});


text:
package uk.ac.man.entitytagger.entities.misc;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;

import uk.ac.man.entitytagger.generate.GenerateMatchers;

import martin.common.ArgParser;
import martin.common.Loggers;

/**
 * This class will, given a DrugBank data file, parse its contents and output a tab-delimited
 * regular expression file suitable for import by the automaton generating software. Using it, an automaton can be
 * generated that may be used to locate and identify drug names as specified by DrugBank.
 * @author Martin Gerner
 */
public class DrugBank {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ArgParser ap = new ArgParser(args);
		File inFile = ap.getFile("in");
		File outFile = ap.getFile("out");
		Logger logger = Loggers.getDefaultLogger(ap);
		Set<String> stopwords = loadStopwords(ap.getFile("wordlist"), logger);

		run(inFile,outFile,stopwords,logger);
	}

	private static Set<String> loadStopwords(File file, Logger logger) {
		if (file == null){
			logger.info("%t: Not using wordlist.\n");
			return new HashSet<String>();
		}

		Set<String> res = new HashSet<String>();

		try{
			BufferedReader inStream = new BufferedReader(new FileReader(file));

			String line = inStream.readLine();
			while (line != null){
				res.add(line);
				line = inStream.readLine();
			}

			inStream.close();
			logger.info("%t: Loaded " + res.size() + " stopwords.\n");
			return res;
		} catch (Exception e){
			System.err.println(e);
			e.printStackTrace();
			System.exit(-1);
		}
		return null;
	}

	private static void run(File inFile, File outFile, Set<String> stopset, Logger logger) {
		logger.info("%t: processing " + inFile.getAbsolutePath() + "...\n");

		try{
			BufferedReader inStream = new BufferedReader(new FileReader(inFile));
			BufferedWriter outStream = new BufferedWriter(new FileWriter(outFile));

			outStream.write("#ID\tregexp\tCAS ID\n");

			String line = inStream.readLine();

			while (line != null){
				if (line.startsWith("#BEGIN_DRUGCARD ")){
					String id_DB = line.substring(16);

					Set<String> names = new HashSet<String>();

					while (!line.equals("# Brand_Names:"))
						line = inStream.readLine();

					line = inStream.readLine();
					while (!line.equals("")){
						//if (line.matches("[^\\(\\)]* \\(.*\\)")){
							String[] fs = line.split(" \\(");

							if (!stopset.contains(fs[0].toLowerCase()))
								names.add(fs[0]);
							else
								logger.info("removed b\t" + fs[0] + "\n");

							if (fs.length > 1)
							logger.info(line + " -> " + fs[0] + "\n");
						//} else {
//							names.add(line);
	//					}

						line = inStream.readLine();
					}

					while (!line.equals("# CAS_Registry_Number:"))
						line = inStream.readLine();

					String id_CAS = inStream.readLine();

					while (!line.equals("# Chemical_IUPAC_Name:"))
						line = inStream.readLine();

					names.add(inStream.readLine());

					while (!line.equals("# Synonyms:"))
						line = inStream.readLine();

					line = inStream.readLine();
					while (!line.equals("")){
						if (!stopset.contains(line.toLowerCase()))
							names.add(line);
						else
							logger.info("removed s\t" + line + "\n");
						line = inStream.readLine();
					}

					String regexp = toregexp(names);

					if (regexp.length() > 0)
						outStream.write("drug:DrugBank:" + id_DB + "\t" + regexp + "\t" + id_CAS + "\n");
				}

				line = inStream.readLine();
			}

			inStream.close();
			outStream.close();
		} catch (Exception e){
			e.printStackTrace();
			System.err.println(e);
			System.exit(-1);
		}
		logger.info("%t: Completed.\n");
	}

	private static String toregexp(Set<String> names) {
		StringBuffer sb = new StringBuffer();

		names.remove("Not Available");

		if (names.size() == 0)
			return "";

		for (String s : names)
			if (sb.length() == 0)
				sb.append("(" + escape(s) + ")");
			else
				sb.append("|(" + escape(s) + ")");

		return sb.toString();
	}

	private static String escape(String s) {
		s = GenerateMatchers.escapeRegexp(s);
		s = s.replace("\t", " ");

		return s;
	}
}


text:
#pragma once
#ifndef __JSON_DATA_STORE_HPP__
#define __JSON_DATA_STORE_HPP__

#include <cassert>
#include <cstring>
#include <type_traits>
#include <typeinfo>
#include <utility>

#include "json_functions.hpp"
#include "json_object_hints.hpp"
#include "json_common_defs.hpp"
#include "json_internal_declarations.hpp"
#include "json_member_mapper.hpp"

#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4291)
#endif
//TODO: Pretty much none of this file will play nice with custom allocators. Need to add support
//  later

//The standard mandates that calls to a non-throwing new check for null. The default placement new
//  inserts a null check and jump after every call, which is unnecessary since we know that the
//  pointer is not null. This makes gcc remove the null check.
json_force_inline
void* operator new(size_t, void*, tjson::detail::placement_new) json_return_nonull;

json_force_inline
void* operator new(size_t, void* ptr, tjson::detail::placement_new) {
    return ptr;
}

namespace tjson {
namespace detail {

    template<typename>
    struct underlying;

    template<typename ClassType, typename UnderlyingType, UnderlyingType ClassType::* member>
    struct underlying<MemberInfo<UnderlyingType ClassType::*, member>> {
        using type = basic_type<UnderlyingType>;
    };

    template<typename>
    struct member_pointer;

    template<typename ClassType, typename UnderlyingType, UnderlyingType ClassType::* member>
    struct member_pointer<MemberInfo<UnderlyingType ClassType::*, member>> {
        json_force_inline static UnderlyingType* apply(ClassType* instance) {
            return &(instance->*member);
        }
    };

    struct data_internal_store_tag : reference_only {};
    struct data_emplace_store_tag : reference_only {};

    template<typename store_tag>
    struct is_internal_store_tag : reference_only {
       constexpr static const bool value = std::is_same<store_tag, data_internal_store_tag>::value;
    };

    template<typename store_tag>
    struct is_emplace_store_tag : reference_only {
       constexpr static const bool value = std::is_same<store_tag, data_emplace_store_tag>::value;
    };

    template<typename construct_tag>
    struct is_non_trivial_construct_tag : reference_only {
       constexpr static const bool value = std::is_same<construct_tag, object_hints::non_trivially_constructible>::value;
    };

    template<typename construct_tag>
    struct is_trivial_construct_tag : reference_only {
       constexpr static const bool value = std::is_same<construct_tag, object_hints::trivially_constructible>::value;
    };

    template<typename ClassType>
    struct class_store_tag : reference_only {
        /**
         * Selects emplace store if the class is trivially constructible, otherwise selects internal
         * store so that the member can be built and copied/moved over
         */
        using type = typename std::conditional<
            is_non_trivial_construct_tag<typename ConstructHint<ClassType>::construction_type>::value,
            data_internal_store_tag,
            data_emplace_store_tag>::type;
    };

    template<typename, typename enabled = bool>
    struct destroy_storage_flag;

    template<typename ClassType>
    struct destroy_storage_flag<ClassType,
                            typename std::enable_if<
                                !std::is_trivially_destructible<ClassType>::value, bool
                            >::type>
    {
        json_force_inline constexpr destroy_storage_flag() noexcept : initialized(false) {}

        json_force_inline void set_should_destroy_storage() noexcept { initialized = true; }
        json_force_inline void unset_should_destroy_storage() noexcept { initialized = false; }
        json_force_inline bool should_destroy_storage() noexcept { return initialized; }
        json_force_inline bool is_initialized() noexcept { return initialized; }

    private:
        bool initialized;
    };

    template<typename ClassType>
    struct destroy_storage_flag<ClassType,
                            typename std::enable_if<
                                std::is_trivially_destructible<ClassType>::value, bool
                            >::type>
    {
        json_force_inline void set_should_destroy_storage() noexcept { }
        json_force_inline void unset_should_destroy_storage() noexcept { }
        json_force_inline bool should_destroy_storage() noexcept { return false; }
        json_force_inline bool is_initialized() noexcept { return true; }
    };

    template<typename StoredType>
    struct data_member_storage_base : destroy_storage_flag<StoredType> {

        json_force_inline data_member_storage_base(StoredType* storage) noexcept :
            _storage_ptr(storage)
        {}

        json_force_inline StoredType* storage_ptr() json_return_nonull { return _storage_ptr; }
        StoredType* _storage_ptr;
    };

    template<typename StoredType>
    struct DataMember : data_member_storage_base<StoredType> {
        json_force_inline DataMember(StoredType* storage) noexcept :
            data_member_storage_base<StoredType>(storage)
        {}

        template<typename... Args,
                 typename std::enable_if<!std::is_nothrow_constructible<StoredType, Args...>::value,
                    bool>::type = true>
        json_force_inline void write(Args&&... args) {
            new (storage_ptr(), placement_new::invoke) StoredType{ std::forward<Args>(args)... };
            //This must happen AFTER calling new, since if that throws we don't want to try to tear
            //  down a class that hasn't been built yet
            set_should_destroy_storage();
        }

        template<typename... Args,
                 typename std::enable_if<std::is_nothrow_constructible<StoredType, Args...>::value,
                    bool>::type = true>
        json_force_inline void write(Args&&... args) noexcept {
            new (storage_ptr(), placement_new::invoke) StoredType{ std::forward<Args>(args)... };
            set_should_destroy_storage();
        }

        using destroy_storage_flag<StoredType>::set_should_destroy_storage;
        using data_member_storage_base<StoredType>::storage_ptr;
    };

    template<typename StoredType, typename store_tag>
    struct data_member_storage : DataMember<StoredType> {
        json_force_inline data_member_storage() noexcept :
            DataMember<StoredType>(static_cast<StoredType*>(static_cast<void*>(&storage)))
        {}

        raw_data<StoredType> storage;
    };

    template<typename StoredType>
    struct data_member_storage<StoredType, data_emplace_store_tag> : DataMember<StoredType> {
        json_force_inline data_member_storage(StoredType* storage) noexcept :
            DataMember<StoredType>(storage)
        {}
    };

    template<typename StoredType, typename store_tag>
    struct DataMemberImpl : data_member_storage<StoredType, store_tag> {

        template<typename _store_tag = store_tag,
                 enable_if<_store_tag, is_internal_store_tag> = true>
        json_force_inline DataMemberImpl() noexcept {}

        template<typename _store_tag = store_tag,
                 enable_if<_store_tag, is_emplace_store_tag> = true>
        json_force_inline DataMemberImpl(StoredType* storage) noexcept :
            data_member_storage<StoredType, store_tag>(storage)
        {}

        template<typename _store_tag = store_tag,
                 enable_if<_store_tag, is_internal_store_tag> = true>
        json_force_inline StoredType&& consume() noexcept {
            assert(is_initialized());
            return std::move(*storage_ptr());
        }

        template<typename _store_tag = store_tag,
                 enable_if<_store_tag, is_emplace_store_tag> = true>
        json_force_inline void consume() noexcept {
            assert(is_initialized());
            unset_should_destroy_storage();
        }

        json_force_inline StoredType& access() noexcept {
            assert(is_initialized());
            return *storage_ptr();
        }

        json_force_inline ~DataMemberImpl() {
            if(should_destroy_storage()) {
                storage_ptr()->~StoredType();
            }
        }

        using destroy_storage_flag<StoredType>::set_should_destroy_storage;
    private:
        using destroy_storage_flag<StoredType>::is_initialized;
        using destroy_storage_flag<StoredType>::should_destroy_storage;
        using destroy_storage_flag<StoredType>::unset_should_destroy_storage;
        using data_member_storage<StoredType, store_tag>::storage_ptr;
    };

    //TODO: This stores members in the "wrong" order, since they are reverse-order in memory
    //  I *think* this doesn't matter since it looks like from the assembly the compiler just
    //  removes this class because of all the inlining and builds directly on the members, making
    //  the member memory-order irrelevant.
    //As long as there is no ##% performance difference in changing the order, this will stay as-is
    //  since it's much easier to understand/reason about
    template<typename ClassFor, typename... Types>
    struct DataList {};

    template<typename ClassFor, typename StoredType>
    struct DataList<ClassFor, StoredType> : DataList<ClassFor> {

        template<typename store_tag = typename class_store_tag<ClassFor>::type,
                 typename member, typename... members,
                 enable_if<store_tag, is_emplace_store_tag> = true>
        json_force_inline DataList(ClassFor* instance, MemberList<member, members...>&&) noexcept :
            data(member_pointer<member>::apply(instance))
        {}

        template<typename store_tag = typename class_store_tag<ClassFor>::type,
                 enable_if<store_tag, is_internal_store_tag> = true>
        json_force_inline DataList() noexcept {}

        DataMemberImpl<StoredType, typename class_store_tag<ClassFor>::type> data;
    };

    template<typename ClassFor, typename StoredType, typename NextType, typename... Types>
    struct DataList<ClassFor, StoredType, NextType, Types...> : DataList<ClassFor,
                                                                         NextType,
                                                                         Types...>
    {
        template<typename store_tag = typename class_store_tag<ClassFor>::type,
                 typename member,
                 typename... members,
                 enable_if<store_tag, is_emplace_store_tag> = true>
        json_force_inline DataList(ClassFor* instance, MemberList<member, members...>&&) noexcept :
            DataList<ClassFor, NextType, Types...>(instance, MemberList<members...>()),
            data(member_pointer<member>::apply(instance))
        {}

        template<typename store_tag = typename class_store_tag<ClassFor>::type,
                 enable_if<store_tag, is_internal_store_tag> = true>
        json_force_inline DataList() noexcept {}

        DataMemberImpl<StoredType, typename class_store_tag<ClassFor>::type> data;
    };

    /**
     * Used to deduce the type of the DataList required to store the members for a particular class
     */
    template<typename ClassFor, typename... members,
             typename std::enable_if<
                std::is_same<typename class_store_tag<ClassFor>::type,
                             data_internal_store_tag>::value, bool>::type = true>
    constexpr DataList<ClassFor, typename underlying<members>::type...>
    data_list_type(MemberList<members...>&&) noexcept {
        return DataList<ClassFor, typename underlying<members>::type...>();
    }

    template<typename ClassFor, typename... members,
             typename std::enable_if<
                std::is_same<typename class_store_tag<ClassFor>::type,
                             data_emplace_store_tag>::value, bool>::type = true>
    DataList<ClassFor, typename underlying<members>::type...>
    data_list_type(MemberList<members...>&&) noexcept {
        return DataList<ClassFor, typename underlying<members>::type...>(
            nullptr, MemberList<members...>()
        );
    }

    /**
     * Used to get the next node in the data list.
     */
    template<typename ClassFor, typename DataType, typename... DataTypes>
    json_force_inline
    constexpr DataList<ClassFor, DataTypes...>&
    data_list_next(DataList<ClassFor, DataType, DataTypes...>& list) noexcept {
        return static_cast<DataList<ClassFor, DataTypes...>&>(list);
    }

    template<typename StoredType>
    struct DataStore : destroy_storage_flag<StoredType> {

        template<typename construct_tag = typename ConstructHint<StoredType>::construction_type,
                 enable_if<construct_tag, is_trivial_construct_tag> = true>
        json_force_inline DataStore(StoredType* storage) noexcept
            : data_list(storage, MembersFor<StoredType>())
        {}

        template<typename construct_tag = typename ConstructHint<StoredType>::construction_type,
                 enable_if<construct_tag, is_non_trivial_construct_tag> = true>
        json_force_inline DataStore() noexcept {}

        decltype(data_list_type<StoredType>(MembersFor<StoredType>())) data_list;
    };

    //See cases outlined in data store
    template<typename StoredType, typename store_tag, typename construct_tag>
    struct data_storage : DataStore<StoredType> {
        using storage_ptr = void;
    };

    template<typename StoredType>
    struct data_storage<StoredType,
                        data_internal_store_tag,
                        object_hints::trivially_constructible> : DataStore<StoredType>
    {
        json_force_inline data_storage() noexcept :
            DataStore<StoredType>(storage_ptr())
        {}

        json_force_inline StoredType* storage_ptr() noexcept json_return_nonull {
            return static_cast<StoredType*>(static_cast<void*>(&storage));
        }

        raw_data<StoredType> storage;
    };

    template<typename StoredType, typename construct_tag>
    struct data_storage<StoredType,
                        data_emplace_store_tag,
                        construct_tag> : DataStore<StoredType>
    {
        template<typename _construct_tag = construct_tag,
                 enable_if<_construct_tag, is_trivial_construct_tag> = true>
        json_force_inline data_storage(StoredType* storage) noexcept :
            DataStore<StoredType>(storage),
            storage(storage)
        {}

        template<typename _construct_tag = construct_tag,
                 enable_if<_construct_tag, is_non_trivial_construct_tag> = true>
        json_force_inline data_storage(StoredType* storage) noexcept :
            storage(storage)
        {}

        json_force_inline StoredType* storage_ptr() json_return_nonull {
            return storage;
        }

        StoredType* storage;
    };

    template<typename StoredType, typename store_tag = data_internal_store_tag>
    struct DataStoreImpl : data_storage<StoredType,
                                        store_tag,
                                        typename ConstructHint<StoredType>::construction_type>
    {
        /* Four cases:
         * 1. We are emplacing a trivially constructible type:
         *    - Build the items in-place in the passed-in object
         *    - Do nothing in transfer_storage, just flag that owning object will do teardown
         *    - realize() is not a valid operation
         *    - Do nothing in the destructor, teardown is now owner's problem
         *
         * 2. We are emplacing a non-trivially constructible type:
         *    - Build the data list out of separate objects
         *    - Construct the target object during transfer_storage
         *    - realize() is not a valid operation
         *    - Do nothing in destructor (tear down is handled by data list/owner of target)
         *
         * 3. We are constructing a trivially constructible type (no emplacement):
         *    - Build the items in-place in an internal buffer
         *    - return the internal buffer during realize()
         *    - transfer_storage is not a valid operation
         *    - call destructor if realize() was invoked (data list teardown handles partial objs)
         *
         * 4. We are constructing a non-trivially constructible type (no emplacement):
         *    - Build the data list from separate objects
         *    - Construct the object and return it during realize()
         *    - transfer_storage is not a valid operation
         *    - do nothing in destructor
         */

        template<typename _store_tag = store_tag,
                 typename construct_tag = typename ConstructHint<StoredType>::construction_type,
                 enable_if<_store_tag, is_internal_store_tag> = true>
        json_force_inline DataStoreImpl() noexcept {}

        template<typename _store_tag = store_tag,
                 typename construct_tag = typename ConstructHint<StoredType>::construction_type,
                 enable_if<_store_tag, is_emplace_store_tag> = true,
                 enable_if<construct_tag, is_trivial_construct_tag> = true>
        json_force_inline DataStoreImpl(StoredType* storage) noexcept :
            data_storage<StoredType, store_tag, construct_tag>(storage)
        {}

        template<typename _store_tag = store_tag,
                 typename construct_tag = typename ConstructHint<StoredType>::construction_type,
                 enable_if<_store_tag, is_emplace_store_tag> = true,
                 enable_if<construct_tag, is_non_trivial_construct_tag> = true>
        json_force_inline DataStoreImpl(StoredType* storage) noexcept :
            data_storage<StoredType, store_tag, construct_tag>(storage)
        {}

        /**
         * Data store is no longer valid after this call
         */
        template<typename _store_tag = store_tag,
                 enable_if<_store_tag, is_internal_store_tag> = true>
        json_force_inline StoredType realize() {
            return realize(data_list);
        }

        /**
         * Data store is no longer valid after this call
         */
        template<typename _store_tag = store_tag,
                 enable_if<_store_tag, is_emplace_store_tag> = true>
        json_force_inline void transfer_storage(DataMember<StoredType>& into) {
            assert(into.storage_ptr() == storage_ptr());
            transfer_storage(data_list);
            into.set_should_destroy_storage();
        }

        json_force_inline ~DataStoreImpl() {
            DestroyStorage();
        }

        using DataStore<StoredType>::data_list;

    private:
        using data_storage<StoredType,
                           store_tag,
                           typename ConstructHint<StoredType>::construction_type
                          >::storage_ptr;
        using destroy_storage_flag<StoredType>::should_destroy_storage;
        using destroy_storage_flag<StoredType>::set_should_destroy_storage;

        //For constructing/returning an object
        //Creating a non trivially constructible type
        template<typename... Values,
                 typename _store_tag = store_tag,
                 typename construct_tag = typename ConstructHint<StoredType>::construction_type,
                 enable_if<_store_tag, is_internal_store_tag> = true,
                 enable_if<construct_tag, is_non_trivial_construct_tag> = true>
        json_force_inline
        static StoredType realize(DataList<StoredType>&,
                                  Values&&... values)
        {
            return StoredType{ std::forward<Values>(values)... };
        }

        template<typename DataType,
                 typename... DataTypes,
                 typename... Values,
                 typename _store_tag = store_tag,
                 typename construct_tag = typename ConstructHint<StoredType>::construction_type,
                 enable_if<_store_tag, is_internal_store_tag> = true,
                 enable_if<construct_tag, is_non_trivial_construct_tag> = true>
        json_force_inline
        static StoredType realize(DataList<StoredType, DataType, DataTypes...>& list,
                                  Values&&...                                   values)
        {
            return realize(data_list_next(list), std::forward<Values>(values)..., list.data.consume());
        }

        //Creating a trivially constructible type
        template<typename _store_tag = store_tag,
                 typename construct_tag = typename ConstructHint<StoredType>::construction_type,
                 enable_if<_store_tag, is_internal_store_tag> = true,
                 enable_if<construct_tag, is_trivial_construct_tag> = true>
        json_force_inline
        StoredType realize(DataList<StoredType>&) noexcept {
            //class has been fully created at this point, need to make sure to call destructor after
            //  calling move
            set_should_destroy_storage();
            return std::move(*storage_ptr());
        }

        template<typename DataType,
                 typename... DataTypes,
                 typename _store_tag = store_tag,
                 typename construct_tag = typename ConstructHint<StoredType>::construction_type,
                 enable_if<_store_tag, is_internal_store_tag> = true,
                 enable_if<construct_tag, is_trivial_construct_tag> = true>
        json_force_inline
        StoredType realize(DataList<StoredType, DataType, DataTypes...>& list) noexcept {
            //Need to flag all datalist members as non-destroying, since we'll handle that after
            //  this point. This puts it in a temporary partial-destroying state, but it should be
            //  safe since no exceptions can be thrown in the middle of this process.
            //This consume is different than the consume for a non-trivial type, since that still
            //  needs to call the destructor
            list.data.consume();
            return realize(data_list_next(list));
        }

        //For initializing a DataMember
        //Transferring a non trivially constructible type
        template<typename... Values,
                 typename _store_tag = store_tag,
                 typename construct_tag = typename ConstructHint<StoredType>::construction_type,
                 enable_if<_store_tag, is_emplace_store_tag> = true,
                 enable_if<construct_tag, is_non_trivial_construct_tag> = true>
        json_force_inline
        void transfer_storage(DataList<StoredType>&,
                              Values&&... values)
        {
            new (storage_ptr(), placement_new::invoke) StoredType{std::forward<Values>(values)...};
        }

        template<typename DataType,
                 typename... DataTypes,
                 typename... Values,
                 typename _store_tag = store_tag,
                 typename construct_tag = typename ConstructHint<StoredType>::construction_type,
                 enable_if<_store_tag, is_emplace_store_tag> = true,
                 enable_if<construct_tag, is_non_trivial_construct_tag> = true>
        json_force_inline
        void transfer_storage(DataList<StoredType, DataType, DataTypes...>& list,
                              Values&&...                                   values)
        {
            transfer_storage(data_list_next(list), std::forward<Values>(values)..., list.data.consume());
        }

        //Transferring a trivially constructible type
        template<typename _store_tag = store_tag,
                 typename construct_tag = typename ConstructHint<StoredType>::construction_type,
                 enable_if<_store_tag, is_emplace_store_tag> = true,
                 enable_if<construct_tag, is_trivial_construct_tag> = true>
        json_force_inline
        static void transfer_storage(DataList<StoredType>&) noexcept{}

        template<typename DataType,
                 typename... DataTypes,
                 typename _store_tag = store_tag,
                 typename construct_tag = typename ConstructHint<StoredType>::construction_type,
                 enable_if<_store_tag, is_emplace_store_tag> = true,
                 enable_if<construct_tag, is_trivial_construct_tag> = true>
        json_force_inline
        static void transfer_storage(DataList<StoredType, DataType, DataTypes...>& list) noexcept{
            list.data.consume();
            transfer_storage(data_list_next(list));
        }

        template<typename _store_tag = store_tag,
                 typename construct_tag = typename ConstructHint<StoredType>::construction_type,
                 typename std::enable_if<
                    is_emplace_store_tag<_store_tag>::value
                    || is_non_trivial_construct_tag<construct_tag>::value, bool>::type = true>
        json_force_inline void DestroyStorage() noexcept {}

        template<typename _store_tag = store_tag,
                 typename construct_tag = typename ConstructHint<StoredType>::construction_type,
                 enable_if<_store_tag, is_internal_store_tag> = true,
                 enable_if<construct_tag, is_trivial_construct_tag> = true>
        json_force_inline void DestroyStorage() noexcept {
            if(should_destroy_storage()) {
                storage_ptr()->~StoredType();
            }
        }
    };
}
}

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#endif


text:
/// <reference types="node" />
import * as cp from 'child_process';
import ChildProcess = cp.ChildProcess;
import { BaseLanguageClient, LanguageClientOptions, MessageTransports, StaticFeature, DynamicFeature } from './client';
import { Disposable } from 'vscode';
export * from './client';
export interface ExecutableOptions {
    cwd?: string;
    env?: any;
    detached?: boolean;
    shell?: boolean;
}
export interface Executable {
    command: string;
    args?: string[];
    options?: ExecutableOptions;
}
export interface ForkOptions {
    cwd?: string;
    env?: any;
    encoding?: string;
    execArgv?: string[];
}
export declare enum TransportKind {
    stdio = 0,
    ipc = 1,
    pipe = 2,
    socket = 3
}
export interface SocketTransport {
    kind: TransportKind.socket;
    port: number;
}
/**
 * To avoid any timing, pipe name or port number issues the pipe (TransportKind.pipe)
 * and the sockets (TransportKind.socket and SocketTransport) are owned by the
 * VS Code processes. The server process simply connects to the pipe / socket.
 * In node term the VS Code process calls `createServer`, then starts the server
 * process, waits until the server process has connected to the pipe / socket
 * and then signals that the connection has been established and messages can
 * be send back and forth. If the language server is implemented in a different
 * programm language the server simply needs to create a connection to the
 * passed pipe name or port number.
 */
export declare type Transport = TransportKind | SocketTransport;
export interface NodeModule {
    module: string;
    transport?: Transport;
    args?: string[];
    runtime?: string;
    options?: ForkOptions;
}
export interface StreamInfo {
    writer: NodeJS.WritableStream;
    reader: NodeJS.ReadableStream;
    detached?: boolean;
}
export interface ChildProcessInfo {
    process: ChildProcess;
    detached: boolean;
}
export declare type ServerOptions = Executable | {
    run: Executable;
    debug: Executable;
} | {
    run: NodeModule;
    debug: NodeModule;
} | NodeModule | (() => Promise<ChildProcess | StreamInfo | MessageTransports | ChildProcessInfo>);
export declare class LanguageClient extends BaseLanguageClient {
    private _serverOptions;
    private _forceDebug;
    private _serverProcess;
    private _isDetached;
    constructor(name: string, serverOptions: ServerOptions, clientOptions: LanguageClientOptions, forceDebug?: boolean);
    constructor(id: string, name: string, serverOptions: ServerOptions, clientOptions: LanguageClientOptions, forceDebug?: boolean);
    private checkVersion;
    stop(): Promise<void>;
    private checkProcessDied;
    protected handleConnectionClosed(): void;
    protected createMessageTransports(encoding: string): Promise<MessageTransports>;
    registerProposedFeatures(): void;
    protected registerBuiltinFeatures(): void;
    private _mainGetRootPath;
    private _getServerWorkingDir;
}
export declare class SettingMonitor {
    private _client;
    private _setting;
    private _listeners;
    constructor(_client: LanguageClient, _setting: string);
    start(): Disposable;
    private onDidChangeConfiguration;
}
export declare namespace ProposedFeatures {
    function createAll(client: BaseLanguageClient): (StaticFeature | DynamicFeature<any>)[];
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
    @author Lars Harmsen
    Copyright (c) <2014> <Lars Harmsen - Quchen>
-->
<resources>
    <string name="app_id" translatable="false">508732765831</string>

    <string name="ad_app_id" translatable="false">ca-app-pub-5615758120938208~8730683579</string> <!-- Google Admob -->
    <string name="ad_unit_id" translatable="false">ca-app-pub-5615758120938208/8958298370</string> <!-- Google Admob -->

    <string name="leaderboard_highscore" translatable="false">CgkIh-3XlucOEAIQAQ</string>

    <string name="achievement_50_coins" translatable="false">CgkIh-3XlucOEAIQAg</string>
    <string name="achievement_toastification" translatable="false">CgkIh-3XlucOEAIQAw</string>
    <string name="achievement_bronze" translatable="false">CgkIh-3XlucOEAIQBA</string>
    <string name="achievement_silver" translatable="false">CgkIh-3XlucOEAIQBQ</string>
    <string name="achievement_gold" translatable="false">CgkIh-3XlucOEAIQBg</string>
</resources>


text:
using System.Web;

namespace Kudu.Services.Infrastructure
{
    public static class HttpRequestExtensions
    {
        public static string GetRequestId(this HttpRequest httpRequest)
        {
            // prefer x-arr-log-id over x-ms-request-id since azure always populates the former.
            return httpRequest.Headers[Constants.ArrLogIdHeader] ?? httpRequest.Headers[Constants.RequestIdHeader];
        }

        public static string GetUserAgent(this HttpRequest httpRequest)
        {
            return httpRequest.UserAgent ?? string.Empty;
        }
    }
}


text:
pub mod server;
pub mod monitor;

use {Client, Result};
use Error::{self, ArgumentError, OperationError};

use bson::oid;

use common::{ReadPreference, ReadMode};
use connstring::{ConnectionString, Host};
use pool::PooledStream;

use rand::{thread_rng, Rng};

use std::collections::HashMap;
use std::i64;
use std::str::FromStr;
use std::sync::{Arc, RwLock};
use std::thread;
use time;

use self::server::{Server, ServerDescription, ServerType};

pub const DEFAULT_HEARTBEAT_FREQUENCY_MS: u32 = 10000;
pub const DEFAULT_LOCAL_THRESHOLD_MS: i64 = 15;
pub const DEFAULT_SERVER_SELECTION_TIMEOUT_MS: i64 = 30000;

/// Describes the type of topology for a server set.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TopologyType {
    Single,
    ReplicaSetNoPrimary,
    ReplicaSetWithPrimary,
    Sharded,
    Unknown,
}

/// Topology information gathered from server set monitoring.
#[derive(Clone)]
pub struct TopologyDescription {
    pub topology_type: TopologyType,
    /// The set name for a replica set topology. If the topology
    /// is not a replica set, this will be an empty string.
    pub set_name: String,
    /// Known servers within the topology.
    pub servers: HashMap<Host, Server>,
    /// The server connection health check frequency.
    /// The default is 10 seconds.
    pub heartbeat_frequency_ms: u32,
    /// The size of the latency window for selecting suitable servers.
    /// The default is 15 milliseconds.
    pub local_threshold_ms: i64,
    /// This defines how long to block for server selection before
    /// returning an error. The default is 30 seconds.
    pub server_selection_timeout_ms: i64,
    // The largest election id seen from a server in the topology.
    max_election_id: Option<oid::ObjectId>,
    // If true, all servers in the topology fall within the compatible
    // mongodb version for this driver.
    compatible: bool,
    compat_error: String,
}

/// Holds status and connection information about a server set.
#[derive(Clone)]
pub struct Topology {
    /// The initial connection configuration.
    pub config: ConnectionString,
    /// Monitored topology information.
    pub description: Arc<RwLock<TopologyDescription>>,
}

impl FromStr for TopologyType {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self> {
        Ok(match s {
            "Single" => TopologyType::Single,
            "ReplicaSetNoPrimary" => TopologyType::ReplicaSetNoPrimary,
            "ReplicaSetWithPrimary" => TopologyType::ReplicaSetWithPrimary,
            "Sharded" => TopologyType::Sharded,
            _ => TopologyType::Unknown,
        })
    }
}

impl TopologyDescription {
    /// Returns a default, unknown topology description.
    pub fn new() -> TopologyDescription {
        TopologyDescription {
            topology_type: TopologyType::Unknown,
            set_name: String::new(),
            heartbeat_frequency_ms: DEFAULT_HEARTBEAT_FREQUENCY_MS,
            server_selection_timeout_ms: DEFAULT_SERVER_SELECTION_TIMEOUT_MS,
            local_threshold_ms: DEFAULT_LOCAL_THRESHOLD_MS,
            servers: HashMap::new(),
            max_election_id: None,
            compatible: true,
            compat_error: String::new(),
        }
    }

    /// Returns the nearest server stream, calculated by round trip time.
    fn get_nearest_from_vec(&self, servers: &mut Vec<Host>) -> Result<(PooledStream, ServerType)> {
        servers.sort_by(|a, b| {
            let mut a_rtt = i64::MAX;
            let mut b_rtt = i64::MAX;
            if let Some(server) = self.servers.get(a) {
                if let Ok(a_description) = server.description.read() {
                    a_rtt = a_description.round_trip_time.unwrap_or(i64::MAX);
                }
            }
            if let Some(server) = self.servers.get(b) {
                if let Ok(b_description) = server.description.read() {
                    b_rtt = b_description.round_trip_time.unwrap_or(i64::MAX);
                }
            }

            a_rtt.cmp(&b_rtt)
        });

        // Iterate over each host until one's stream can be acquired.
        for host in servers.iter() {
            if let Some(server) = self.servers.get(host) {
                if let Ok(description) = server.description.read() {
                    if description.round_trip_time.is_none() {
                        break;
                    } else if let Ok(stream) = server.acquire_stream() {
                        return Ok((stream, description.server_type));
                    }
                }
            }
        }
        Err(OperationError("No servers available for the provided ReadPreference.".to_owned()))
    }

    /// Returns a random server stream from the vector.
    fn get_rand_from_vec(&self, servers: &mut Vec<Host>) -> Result<(PooledStream, ServerType)> {
        while !servers.is_empty() {
            let len = servers.len();
            let index = thread_rng().gen_range(0, len);

            if let Some(server) = self.servers.get(servers.get(index).unwrap()) {
                if let Ok(stream) = server.acquire_stream() {
                    if let Ok(description) = server.description.read() {
                        return Ok((stream, description.server_type));
                    }
                }
            }
            servers.remove(index);
        }
        Err(OperationError("No servers available for the provided ReadPreference.".to_owned()))
    }

    /// Returns a server stream for read operations.
    pub fn acquire_stream(&self, read_preference: &ReadPreference) -> Result<(PooledStream, bool, bool)> {
        let (mut hosts, rand) = self.choose_hosts(&read_preference);

        // Filter hosts by tagsets
        if self.topology_type != TopologyType::Sharded && self.topology_type != TopologyType::Single {
            self.filter_hosts(&mut hosts, read_preference);
        }

        // Special case - If secondaries are found, by are filtered out by tag sets,
        // the topology should return any available primaries instead.
        if hosts.is_empty() && read_preference.mode == ReadMode::SecondaryPreferred {
            let mut read_pref = read_preference.clone();
            read_pref.mode = ReadMode::PrimaryPreferred;
            return self.acquire_stream(&read_pref);
        }

        // If no servers are available, request an update from all monitors.
        if hosts.is_empty() {
            for (_, server) in self.servers.iter() {
                server.request_update();
            }
        }

        // Filter hosts by round trip times within the latency window.
        self.filter_latency_hosts(&mut hosts);

        // Retrieve a server stream from the list of acceptable hosts.
        let (pooled_stream, server_type) = if rand {
            try!(self.get_rand_from_vec(&mut hosts))
        } else {
            try!(self.get_nearest_from_vec(&mut hosts))
        };

        // Determine how to handle server-side logic based on ReadMode and TopologyType.
        let (slave_ok, send_read_pref) = match self.topology_type {
            TopologyType::Unknown => (false, false),
            TopologyType::Single => match server_type {
                ServerType::Mongos => {
                    match read_preference.mode {
                        ReadMode::Primary => (false, false),
                        ReadMode::Secondary => (true, true),
                        ReadMode::PrimaryPreferred => (true, true),
                        ReadMode::SecondaryPreferred => (true, !read_preference.tag_sets.is_empty()),
                        ReadMode::Nearest => (true, true),
                    }
                },
                _ => (true, false),
            },
            TopologyType::ReplicaSetWithPrimary | TopologyType::ReplicaSetNoPrimary => {
                match read_preference.mode {
                    ReadMode::Primary => (false, false),
                    _ => (true, false),
                }
            },
            TopologyType::Sharded => {
                match read_preference.mode {
                    ReadMode::Primary => (false, false),
                    ReadMode::Secondary => (true, true),
                    ReadMode::PrimaryPreferred => (true, true),
                    ReadMode::SecondaryPreferred => (true, !read_preference.tag_sets.is_empty()),
                    ReadMode::Nearest => (true, true),
                }
            }
        };

        Ok((pooled_stream, slave_ok, send_read_pref))
    }

    /// Returns a server stream for write operations.
    pub fn acquire_write_stream(&self) -> Result<PooledStream> {
        let (mut hosts, rand) = self.choose_write_hosts();

        // If no servers are available, request an update from all monitors.
        if hosts.is_empty() {
            for (_, server) in self.servers.iter() {
                server.request_update();
            }
        }

        if rand {
            Ok(try!(self.get_rand_from_vec(&mut hosts)).0)
        } else {
            Ok(try!(self.get_nearest_from_vec(&mut hosts)).0)
        }
    }

    /// Filters a given set of hosts based on the provided read preference tag sets.
    pub fn filter_hosts(&self, hosts: &mut Vec<Host>, read_preference: &ReadPreference) {
        let mut tag_filter = None;

        if read_preference.tag_sets.is_empty() {
            return;
        }

        // Set the tag_filter to the first tag set that matches at least one server in the set.
        for tags in read_preference.tag_sets.iter() {
            for ref host in hosts.iter() {
                if let Some(server) = self.servers.get(host) {
                    let description = server.description.read().unwrap();

                    // Check whether the read preference tags are contained
                    // within the server description tags.
                    let mut valid = true;
                    for (key, ref val) in tags.iter() {
                        match description.tags.get(key) {
                            Some(ref v) => if val != v { valid = false; break },
                            None => { valid = false; break },
                        }
                    }

                    if valid {
                        tag_filter = Some(tags);
                        break;
                    }
                }
            }

            // Short-circuit if tag filter has been found.
            if tag_filter.is_some() {
                break;
            }
        }

        match tag_filter {
            None => {
                // If no tags match but the replica set has a primary that is returnable with
                // the given ReadMode, return that primary server.
                if self.topology_type == TopologyType::ReplicaSetWithPrimary &&
                    (read_preference.mode == ReadMode::Primary ||
                     read_preference.mode == ReadMode::PrimaryPreferred) {
                        // Retain primaries.
                        hosts.retain(|host| {
                            if let Some(server) = self.servers.get(host) {
                                let description = server.description.read().unwrap();
                                description.server_type == ServerType::RSPrimary
                            } else {
                                false
                            }
                        });
                    } else {
                        // If no tags match and the above case does not occur,
                        // filter out all provided servers.
                        hosts.clear();
                    }
            },
            Some(tag_filter) => {
                // Filter out hosts by the discovered matching tagset.
                hosts.retain(|host| {
                    if let Some(server) = self.servers.get(host) {
                        let description = server.description.read().unwrap();

                        // Validate tag sets.
                        for (key, ref val) in tag_filter.iter() {
                            match description.tags.get(key) {
                                Some(ref v) => if val != v { return false; },
                                None => return false,
                            }
                        }
                        true
                    } else {
                        false
                    }
                });
            }
        }
    }

    /// Filter out provided hosts by creating a latency window around
    /// the server with the lowest round-trip time.
    pub fn filter_latency_hosts(&self, hosts: &mut Vec<Host>) {
        if hosts.len() <= 1 {
            return;
        }

        // Find the shortest round-trip time.
        let shortest_rtt = hosts.iter().fold({
            // Initialize the value to the first server's round-trip-time, or i64::MAX.
            if let Some(server) = self.servers.get(hosts.get(0).unwrap()) {
                if let Ok(description) = server.description.read() {
                    description.round_trip_time.unwrap_or(i64::MAX)
                } else {
                    i64::MAX
                }
            } else {
                i64::MAX
            }
        }, |acc, host| {
            // Compare the previous shortest rtt with the host rtt.
            if let Some(server) = self.servers.get(&host) {
                if let Ok(description) = server.description.read() {
                    let item_rtt = description.round_trip_time.unwrap_or(i64::MAX);
                    if acc < item_rtt {
                        return acc;
                    } else {
                        return item_rtt;
                    }
                }
            }
            acc
        });

        // If the shortest rtt is i64::MAX, all server rtts are None or could not be read.
        if shortest_rtt == i64::MAX {
            return;
        }

        let high_rtt = shortest_rtt + self.local_threshold_ms;

        // Filter hosts by the latency window [shortest_rtt, high_rtt].
        hosts.retain(|host| {
            if let Some(server) = self.servers.get(&host) {
                if let Ok(description) = server.description.read() {
                    let rtt = description.round_trip_time.unwrap_or(i64::MAX);
                    return shortest_rtt <= rtt && rtt <= high_rtt;
                }
            }
            false
        });
    }

    /// Returns suitable servers for write operations and whether to take a random element.
    pub fn choose_write_hosts(&self) -> (Vec<Host>, bool) {
        if self.servers.is_empty() {
            return (Vec::new(), true);
        }

        match self.topology_type {
            // No servers are suitable.
            TopologyType::Unknown => (Vec::new(), true),
            // All servers are suitable.
            TopologyType::Single => (self.servers.keys().map(|host| host.clone()).collect(), true),
            TopologyType::Sharded => (self.servers.keys().map(|host| host.clone()).collect(), false),
            // Only primary replica set members are suitable.
            _ => (self.servers.keys().filter_map(|host| {
                if let Some(server) = self.servers.get(host) {
                    if let Ok(description) = server.description.read() {
                        if description.server_type == ServerType::RSPrimary {
                            return Some(host.clone());
                        }
                    }
                }
                None
            }).collect(), true)
        }
    }

    /// Returns suitable servers for read operations and whether to take a random element.
    pub fn choose_hosts(&self, read_preference: &ReadPreference) -> (Vec<Host>, bool) {
        if self.servers.is_empty() {
            return (Vec::new(), true);
        }

        match self.topology_type {
            // No servers are suitable.
            TopologyType::Unknown => (Vec::new(), true),
            // All servers are suitable.
            TopologyType::Single => (self.servers.keys().map(|host| host.clone()).collect(), true),
            TopologyType::Sharded => (self.servers.keys().map(|host| host.clone()).collect(), false),
            _ => {

                // Handle replica set server selection
                // Short circuit if nearest
                if read_preference.mode == ReadMode::Nearest {
                    return (self.servers.keys().map(|host| host.clone()).collect(), false);
                }

                let mut primaries = Vec::new();
                let mut secondaries = Vec::new();

                // Collect a list of primaries and secondaries in the set
                for (host, server) in self.servers.iter() {
                    let stype = server.description.read().unwrap().server_type;
                    match stype {
                        ServerType::RSPrimary => primaries.push(host.clone()),
                        ServerType::RSSecondary => secondaries.push(host.clone()),
                        _ => (),
                    }
                }

                // Choose an appropriate server at random based on the read preference.
                match read_preference.mode {
                    ReadMode::Primary => (primaries, true),
                    ReadMode::PrimaryPreferred => {
                        let servers = if !primaries.is_empty() { primaries } else { secondaries };
                        (servers, true)
                    },
                    ReadMode::Secondary => (secondaries, true),
                    ReadMode::SecondaryPreferred => {
                        let servers = if !secondaries.is_empty() { secondaries } else { primaries };
                        (servers, true)
                    },
                    ReadMode::Nearest => (self.servers.keys().map(|host| host.clone()).collect(), false),
                }
            }
        }
    }

    /// Update the topology description, but don't start any monitors for new servers.
    pub fn update_without_monitor(&mut self, host: Host, description: ServerDescription,
                                  client: Client, top_arc: Arc<RwLock<TopologyDescription>>) {
        self.update_private(host, description, client, top_arc, false);
    }

    /// Updates the topology description based on an updated server description.
    pub fn update(&mut self, host: Host, description: ServerDescription,
                  client: Client, top_arc: Arc<RwLock<TopologyDescription>>) {
        self.update_private(host, description, client, top_arc, true);
    }

    // Internal topology description update helper.
    fn update_private(&mut self, host: Host, description: ServerDescription,
                      client: Client, top_arc: Arc<RwLock<TopologyDescription>>, run_monitor: bool) {

        let stype = description.server_type;
        match self.topology_type {
            TopologyType::Unknown => {
                match stype {
                    ServerType::Standalone => self.update_unknown_with_standalone(host),
                    ServerType::Mongos => self.topology_type = TopologyType::Sharded,
                    ServerType::RSPrimary => self.update_rs_from_primary(host, description, client, top_arc, run_monitor),
                    ServerType::RSSecondary |
                    ServerType::RSArbiter |
                    ServerType::RSOther => self.update_rs_without_primary(host, description, client, top_arc, run_monitor),
                    _ => (),
                }
            },
            TopologyType::ReplicaSetNoPrimary => {
                match stype {
                    ServerType::Standalone | ServerType::Mongos => {
                        self.servers.remove(&host);
                        self.check_if_has_primary();
                    },
                    ServerType::RSPrimary => self.update_rs_from_primary(host, description, client, top_arc, run_monitor),
                    ServerType::RSSecondary |
                    ServerType::RSArbiter |
                    ServerType::RSOther => self.update_rs_without_primary(host, description, client, top_arc, run_monitor),
                    _ => self.check_if_has_primary(),
                }
            },
            TopologyType::ReplicaSetWithPrimary => {
                match stype {
                    ServerType::Standalone | ServerType::Mongos => {
                        self.servers.remove(&host);
                        self.check_if_has_primary();
                    },
                    ServerType::RSPrimary => self.update_rs_from_primary(host, description, client, top_arc, run_monitor),
                    ServerType::RSSecondary |
                    ServerType::RSArbiter |
                    ServerType::RSOther => self.update_rs_with_primary_from_member(host, description),
                    _ => self.check_if_has_primary(),
                }
            },
            TopologyType::Sharded => {
                match stype {
                    ServerType::Unknown | ServerType::Mongos => (),
                    _ => { self.servers.remove(&host); },
                }
            },
            TopologyType::Single => (),
        }
    }

    // Sets the correct replica set topology type.
    fn check_if_has_primary(&mut self) {
        for (_, server) in self.servers.iter() {
            let stype = server.description.read().unwrap().server_type;
            if stype == ServerType::RSPrimary {
                self.topology_type = TopologyType::ReplicaSetWithPrimary;
                return;
            }
        }
        self.topology_type = TopologyType::ReplicaSetNoPrimary;
    }

    // Updates an unknown topology with a new standalone server description.
    fn update_unknown_with_standalone(&mut self, host: Host) {
        if !self.servers.contains_key(&host) {
            return;
        }

        if self.servers.len() == 1 {
            self.topology_type = TopologyType::Single;
        } else {
            self.servers.remove(&host);
        }
    }

    // Updates a replica set topology with a new primary server description.
    fn update_rs_from_primary(&mut self, host: Host, description: ServerDescription,
                              client: Client, top_arc: Arc<RwLock<TopologyDescription>>, run_monitor: bool) {

        if !self.servers.contains_key(&host) {
            return;
        }

        if self.set_name.is_empty() {
            self.set_name = description.set_name.to_owned();
        } else if self.set_name != description.set_name {
            // Primary found, but it doesn't have the setName
            // provided by the user or previously discovered.
            self.servers.remove(&host);
            self.check_if_has_primary();
            return;
        }

        if description.election_id.is_some() {
            if self.max_election_id.is_some() &&
                self.max_election_id.as_ref().unwrap() > description.election_id.as_ref().unwrap() {
                    // Stale primary
                    if let Some(server) = self.servers.get(&host) {
                        {
                            let mut server_description = server.description.write().unwrap();
                            server_description.server_type = ServerType::Unknown;
                            server_description.set_name = String::new();
                            server_description.election_id = None;
                        }
                    }
                    self.check_if_has_primary();
                    return;
                } else {
                    self.max_election_id = description.election_id.clone();
                }
        }

        // Invalidate any old primaries
        for (top_host, server) in self.servers.iter() {
            if *top_host != host {
                let mut server_description = server.description.write().unwrap();
                if server_description.server_type == ServerType::RSPrimary {
                    server_description.server_type = ServerType::Unknown;
                    server_description.set_name = String::new();
                    server_description.election_id = None;
                }
            }
        }

        self.add_missing_hosts(&description, client, top_arc, run_monitor);

        // Remove hosts that are not reported by the primary.
        let mut hosts_to_remove = Vec::new();
        for (host, _) in self.servers.iter() {
            if !description.hosts.contains(&host) &&
                !description.passives.contains(&host) &&
                !description.arbiters.contains(&host) {
                    hosts_to_remove.push(host.clone());
                }
        }

        for host in hosts_to_remove {
            self.servers.remove(&host);
        }

        self.check_if_has_primary();
    }

    // Updates a replica set topology with a missing primary.
    fn update_rs_without_primary(&mut self, host: Host, description: ServerDescription,
                                 client: Client, top_arc: Arc<RwLock<TopologyDescription>>, run_monitor: bool) {

        self.topology_type = TopologyType::ReplicaSetNoPrimary;
        if !self.servers.contains_key(&host) {
            return;
        }

        if self.set_name.is_empty() {
            self.set_name = description.set_name.to_owned();
        } else if self.set_name != description.set_name {
            self.servers.remove(&host);
            self.check_if_has_primary();
            return;
        }

        self.add_missing_hosts(&description, client, top_arc, run_monitor);

        if let Some(me) = description.me {
            if host != me {
                self.servers.remove(&host);
                self.check_if_has_primary();
            }
        }
    }

    // Updates a replica set topology with an updated member description.
    fn update_rs_with_primary_from_member(&mut self, host: Host, description: ServerDescription) {
        if !self.servers.contains_key(&host) {
            return;
        }

        if self.set_name != description.set_name {
            self.servers.remove(&host);
            return;
        }

        if let Some(me) = description.me {
            if host != me {
                self.servers.remove(&host);
            }
        }

        self.check_if_has_primary();
    }

    // Begins monitoring hosts that are not currently being monitored.
    fn add_missing_hosts(&mut self, description: &ServerDescription, client: Client,
                         top_arc: Arc<RwLock<TopologyDescription>>, run_monitor: bool) {

        for host in description.hosts.iter() {
            if !self.servers.contains_key(host) {
                let server = Server::new(client.clone(), host.clone(), top_arc.clone(), run_monitor);
                self.servers.insert(host.clone(), server);
            }
        }

        for host in description.passives.iter() {
            if !self.servers.contains_key(host) {
                let server = Server::new(client.clone(), host.clone(), top_arc.clone(), run_monitor);
                self.servers.insert(host.clone(), server);
            }
        }

        for host in description.arbiters.iter() {
            if !self.servers.contains_key(host) {
                let server = Server::new(client.clone(), host.clone(), top_arc.clone(), run_monitor);
                self.servers.insert(host.clone(), server);
            }
        }
    }
}

impl Topology {
    /// Returns a new topology with the given configuration and description.
    pub fn new(config: ConnectionString, description: Option<TopologyDescription>) -> Result<Topology> {

        let mut options = description.unwrap_or(TopologyDescription::new());

        if config.hosts.len() > 1 && options.topology_type == TopologyType::Single {
            return Err(ArgumentError(
                "TopologyType::Single cannot be used with multiple seeds.".to_owned()));
        }

        if let Some(ref config_opts) = config.options {
            if let Some(name) = config_opts.options.get("replicaSet") {
                options.set_name = name.to_owned();
                options.topology_type = TopologyType::ReplicaSetNoPrimary;
            }
        }

        if !options.set_name.is_empty() && options.topology_type != TopologyType::ReplicaSetNoPrimary {
            return Err(ArgumentError(
                "TopologyType must be ReplicaSetNoPrimary if set_name is provided.".to_owned()));
        }

        let top_description = Arc::new(RwLock::new(options));

        Ok(Topology {
            config: config,
            description: top_description,
        })
    }

    // Private server stream acquisition helper.
    fn acquire_stream_private(&self, read_preference: Option<ReadPreference>, write: bool) -> Result<(PooledStream, bool, bool)> {
        // Note start of server selection.
        let time = time::get_time();
        let start_ms = time.sec * 1000 + (time.nsec as i64) / 1000000;

        loop {
            let description = try!(self.description.read());
            let result = if write {
                match description.acquire_write_stream() {
                    Ok(stream) => Ok((stream, false, false)),
                    Err(err) => Err(err),
                }
            } else {
                description.acquire_stream(read_preference.as_ref().unwrap())
            };

            match result {
                Ok(stream) => return Ok(stream),
                Err(err) => {
                    // Check duration of current server selection and return an error if overdue.
                    let end_time = time::get_time();
                    let end_ms = end_time.sec * 1000 + (end_time.nsec as i64) / 1000000;
                    if end_ms - start_ms >= description.server_selection_timeout_ms {
                        return Err(err)
                    }
                    // Otherwise, sleep for a little while.
                    thread::sleep_ms(500);
                },
            }
        }
    }

    /// Returns a server stream for read operations.
    pub fn acquire_stream(&self, read_preference: ReadPreference) -> Result<(PooledStream, bool, bool)> {
        self.acquire_stream_private(Some(read_preference), false)
    }

    /// Returns a server stream for write operations.
    pub fn acquire_write_stream(&self) -> Result<PooledStream> {
        let (stream, _, _) = try!(self.acquire_stream_private(None, true));
        Ok(stream)
    }
}


text:
This file contains the quantity class

Copyright (c) 2021 Thomas Jenni

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]--

local prefix = ... and (...):match '(.-%.?)[^%.]+$' or ''
local D = require(prefix..'physical-dimension')
local U = require(prefix..'physical-unit')
local N = require(prefix..'physical-number')

-- Quantity class
local Quantity = {}
Quantity.__index = Quantity

-- make Quantity table callable
setmetatable(Quantity, {
	__call = function(class, ...)
		return Quantity.new(...)
	end
})

-- registry for base units
Quantity._base = {}

-- registry for prefixes
Quantity._prefixes = {}

-- modes for the function tosiunitx()
Quantity.SIUNITX_SI = 0
Quantity.SIUNITX_num = 1
Quantity.SIUNITX_si = 2

-- constructor
function Quantity.new(q)

	local p = {}
	setmetatable(p, Quantity)

	-- copy constructor
	if getmetatable(q) == Quantity then
		p.dimension = q.dimension
		p.value = q.value
		p.basefactor = q.basefactor
		p.unit = U(q.unit)

	-- create a dimensionless Quantity
	else
		p.dimension = D.new()
		p.value = q
		p.basefactor = 1
		p.unit = U()
	end

	return p
end

-- create base quantities
function Quantity.defineBase(symbol,name,dimension)

	if rawget(_G,"_"..symbol) ~= nil then
		error("Error: Quantity '_"..symbol.."' does already exist.")
	end

	local p = Quantity.new()
	p.value = 1
	p.dimension = dimension
	p.unit = U.new(symbol,name)

	table.insert(Quantity._base,p)

	rawset(_G, "_"..symbol, p)

	return p
end

-- create derived quantities
function Quantity.define(symbol, name, q)

	-- check if quantity does already exist
	if rawget(_G,"_"..symbol) ~= nil then
		error("Error: Quantity '_"..symbol.."' does already exist.")
	end

	-- check if given value is a quantity
	if getmetatable(q) ~= Quantity then
		error("Error: No quantity given in the definition of '"..name.."'.")
	end

	local p = Quantity.new(q)

	if name ~= nil then
		p.value = 1
		p.basefactor = q.basefactor * q.value
		p.unit = U.new(symbol, name)
	else
		local p = Quantity.new(q)
	end

	rawset(_G, "_"..symbol, p)

	return p
end

-- define a prefix
function Quantity.definePrefix(symbol,name,factor)

	-- check if prefix does already exist
	if Quantity._prefixes[symbol] ~= nil then
		error("Error: Prefix '"..symbol.."' does already exist.")
	end

	-- append prefix to the _prefixes table
	Quantity._prefixes[symbol] = {
		symbol=symbol,
		name=name,
		factor=factor
	}
end

-- create prefixed versions of the given units
function Quantity.addPrefix(prefixes, qs)

	-- todo: what if prefixes and units are no lists?

	for i=1,#prefixes do
		local prefix = Quantity._prefixes[prefixes[i]]

		for j=1,#qs do
			local q = qs[j]

			local p = Quantity.new(q)
			p.unit = U.new(q.unit.symbol, q.unit.name, prefix.symbol, prefix.name)
			p.basefactor = p.basefactor*prefix.factor

			-- assert that unit does not exist
			local symbol = "_"..prefix.symbol..q.unit.symbol
			if rawget(_G,symbol) ~= nil then
				error("Error: Cannot create prefixed Quantity, because '"..symbol.."' does already exist.")
			end

			-- set unit as a global variable
			rawset(_G, symbol, p)
		end
	end
end

-- Add two quantities
function Quantity.__add(q1, q2)

	if getmetatable(q1) ~= Quantity then
		q1 = Quantity.new(q1)
	end
	if getmetatable(q2) ~= Quantity then
		q2 = Quantity.new(q2)
	end

	if q1.dimension ~= q2.dimension then
		error("Error: Cannot add '"..tostring(q1).."' to '"..tostring(q2).."', because they have different dimensions.")
	end

	-- convert o1 to q2 units
	local p = q1:to(q2)
	p.value =  p.value + q2.value

	return 	p
end

-- subtract a dimension from another one
function Quantity.__sub(q1, q2)

	if getmetatable(q1) ~= Quantity then
		q1 = Quantity.new(q1)
	end
	if getmetatable(q2) ~= Quantity then
		q2 = Quantity.new(q2)
	end

	if q1.dimension ~= q2.dimension then
		error("Error: Cannot subtract '"..tostring(q2).."' from '"..tostring(q1).."', because they have different dimensions.")
	end

	-- convert q1 to q2 units
	local p = q1:to(q2)
	p.value =  p.value - q2.value

	return 	p
end

-- unary minus
function Quantity.__unm(q)
	local p = Quantity.new(q)
	p.value = -p.value
	return p
end

-- multiply a dimension by a number
function Quantity.__mul(q1, q2)

	if getmetatable(q1) ~= Quantity then
		q1 = Quantity.new(q1)
	end
	if getmetatable(q2) ~= Quantity then
		q2 = Quantity.new(q2)
	end

	local p = Quantity.new()

	p.dimension = q1.dimension * q2.dimension
	p.value = q1.value * q2.value
	p.basefactor = q1.basefactor * q2.basefactor
	p.unit = q1.unit * q2.unit

	return p
end

-- divide a quantity / number by a quantity / number
function Quantity.__div(q1, q2)

	if getmetatable(q1) ~= Quantity then
		q1 = Quantity.new(q1)
	end
	if getmetatable(q2) ~= Quantity then
		q2 = Quantity.new(q2)
	end

	local p = Quantity.new()

	p.dimension = q1.dimension / q2.dimension
	p.value = q1.value / q2.value
	p.basefactor = q1.basefactor / q2.basefactor
	p.unit = q1.unit / q2.unit

	return p
end

-- power
function Quantity.__pow(q1,q2)

	if getmetatable(q1) ~= Quantity then
		q1 = Quantity.new(q1)
	end
	if getmetatable(q2) ~= Quantity then
		q2 = Quantity.new(q2)
	end

	if not q2.dimension:iszero() then
		error("Error: Cannot take the power of '"..tostring(q1).."', because the exponent '"..tostring(q2).."' is not dimensionless.")
	end

	local p = Quantity.new()
	local e = q2:to()

	p.value = q1.value^e.value

	e = e:__tonumber()
	p.dimension = q1.dimension^e
	p.basefactor = q1.basefactor^e
	p.unit = q1.unit^e

	return p
end

-- test if two quantities are equal
function Quantity.__eq(q1,q2)

	if getmetatable(q1) ~= Quantity then
		q1 = Quantity.new(q1)
	end
	if getmetatable(q2) ~= Quantity then
		q2 = Quantity.new(q2)
	end

	local p = q1:to(q2)

	if p.value ~= q2.value then
		return false
	elseif p.dimension ~= q2.dimension then
		return false
	elseif p.basefactor ~= q2.basefactor then
		return false
	end

	return true
end

-- check if this quantity is less than another one
function Quantity.__lt(q1,q2)

	if getmetatable(q1) ~= Quantity then
		q1 = Quantity.new(q1)
	end
	if getmetatable(q2) ~= Quantity then
		q2 = Quantity.new(q2)
	end

	if q1.dimension ~= q2.dimension then
		error("Error: Cannot compare '"..tostring(q1).."' to '"..tostring(q2).."', because they have different dimensions.")
	end

	return q1:to().value < q2:to().value
end

-- check if this quantity is close to another one. r is the maximal relative deviation.
function Quantity:isclose(q, r)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if getmetatable(r) ~= Quantity then
		r = Quantity.new(r)
	end

	if self.dimension ~= q.dimension then
		error("Error: Cannot compare '"..tostring(self).."' to '"..tostring(q)..", because they have different dimensions.")
	end
	if not r.dimension:iszero() then
		error("Error. The argument '"..tostring(r).."' of the isclose function is not unitless.")
	end

	local q1 = self:to():__tonumber()
	local q2 = q:to():__tonumber()
	local r = r:to():__tonumber()

	local delta = math.abs(q1 - q2)
	local min = math.min(math.abs(q1),math.abs(q2))
	return  (delta / min) <= r
end

-- convert quantity to another unit
function Quantity:to(q)

	local p = Quantity.new()

	-- convert to base units
	p.dimension = self.dimension
	p.value = self.value * self.basefactor

	-- convert to target units
	if q ~= nil then
		if getmetatable(q) ~= Quantity then
			q = Quantity.new(q)
		end

		if self.dimension ~= q.dimension then
			error("Error: Cannot convert '"..tostring(self).."' to '"..tostring(q).."', because they have different dimensions.")
		end

		p.value = p.value / q.basefactor
		p.basefactor = q.basefactor
		p.unit = U(q.unit)

	-- convert to base units
	else
		local unit = U.new()
		local base = Quantity._base

		for i=1,#base do
			unit = unit * base[i].unit^self.dimension[i]
		end

		p.unit = unit
	end

	return p
end

-- convert quantity to a number
function Quantity:__tonumber()
	if type(self.value) == "number" then
		return self.value
	else
		return self.value:__tonumber()
	end
end

-- convert quantity to a string
function Quantity:__tostring()
	return tostring(self.value)..tostring(self.unit)
end

-- convert quantity to an siunitx expression
function Quantity:tosiunitx(param,mode)

	mode = mode or self.SIUNITX_SI
	param = param or ""

	if param ~= "" then
		param = "["..param.."]"
	end

	if mode == Quantity.SIUNITX_SI then
		if type(self.value) == "number" then
			return "\\SI"..param.."{"..tostring(self.value).."}".."{"..self.unit:tosiunitx().."}"
		else
			return "\\SI"..param.."{"..self.value:tosiunitx().."}".."{"..self.unit:tosiunitx().."}"
		end

	elseif mode == Quantity.SIUNITX_num then
		if type(self.value) == "number" then
			return "\\num"..param.."{"..tostring(self.value).."}"
		else
			return "\\num"..param.."{"..self.value:tosiunitx().."}"
		end

	elseif mode == Quantity.SIUNITX_si then
		return "\\si"..param.."{"..self.unit:tosiunitx().."}"

	else
		error("Error: Unknown mode '"..tostring(mode).."'.")
	end

end

-- minimum value
function Quantity.min(q,...)

	for _,p in ipairs({...}) do
		if p < q then
			q = p
		end
    end

    return Quantity.new(q)
end

-- maximum value
function Quantity.max(q,...)

	for _,p in ipairs({...}) do
		if p > q then
			q = p
		end
    end

    return Quantity.new(q)
end

-- absolute value
function Quantity.abs(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if q.value < 0 then
		return -q
	else
		return q
	end
end

-- square root
function Quantity.sqrt(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	return q^0.5
end

-- logarithm
function Quantity.log(q, base)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the logarithm function is not unitless.")
	end

	local b = nil
	if base ~= nil then
		if getmetatable(base) ~= Quantity then
			base = Quantity.new(base)
		end

		b = base:to():__tonumber()
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.log(q:to().value, b)
	else
		p.value = q:to().value:log(b)
	end

	return p
end

-- exponential function
function Quantity.exp(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the exponential function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.exp(q:to().value)
	else
		p.value = q:to().value:exp()
	end

	return p
end

-- TRIGONOMETRIC FUNCTIONS
-- https://en.wikipedia.org/wiki/Trigonometric_functions

-- sine
function Quantity.sin(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the sine function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.sin(q:to().value)
	else
		p.value = q:to().value:sin()
	end

	return p
end

-- cosine
function Quantity.cos(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the cosine function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.cos(q:to().value)
	else
		p.value = q:to().value:cos()
	end

	return p
end

-- tangent
function Quantity.tan(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the tangent function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.tan(q:to().value)
	else
		p.value = q:to().value:tan()
	end

	return p
end

-- arcus sine
function Quantity.asin(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the arcus sine function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.asin(q:to().value)
	else
		p.value = q:to().value:asin()
	end

	return p
end

-- arcus cosine
function Quantity.acos(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the arcus cosine function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.acos(q:to().value)
	else
		p.value = q:to().value:acos()
	end

	return p
end

-- arcus tangent
function Quantity.atan(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the arcus tangent function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.atan(q:to().value)
	else
		p.value = q:to().value:atan()
	end

	return p
end

-- HYPERBOLIC FUNCTIONS
-- https://en.wikipedia.org/wiki/Hyperbolic_function

-- hyperbolic sine
function Quantity.sinh(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the sine hyperbolicus function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = 0.5 * math.exp(q.value) - 0.5 / math.exp(q.value)
	else
		p.value = q:to().value:sinh()
	end

	return p
end

-- hyperbolic cosine
function Quantity.cosh(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the cosine hyperbolicus function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = 0.5 * math.exp(q.value) + 0.5 / math.exp(q.value)
	else
		p.value = q:to().value:cosh()
	end

	return p
end

-- hyperbolic tangent
function Quantity.tanh(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the tangent hyperbolicus function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = (math.exp(q.value) - math.exp(-q.value)) / (math.exp(q.value) + math.exp(-q.value))
	else
		p.value = q:to().value:tanh()
	end

	return p
end

-- INVERS HYPERBOLIC FUNCTIONS
-- https://en.wikipedia.org/wiki/Inverse_hyperbolic_function

-- inverse hyperbolic sine
-- (-inf < q < +inf)
function Quantity.asinh(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the inverse sine hyperbolicus function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.log(q.value + math.sqrt(q.value^2 + 1))
	else
		p.value = q:to().value:asinh()
	end

	return p
end

-- inverse hyperbolic cosine
-- (1 < q)
function Quantity.acosh(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the inverse cosine hyperbolicus function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = math.log(q.value + math.sqrt(q.value^2 - 1))
	else
		p.value = q:to().value:acosh()
	end

	return p
end

-- inverse hyperbolic tangent
-- (-1 < q < 1)
function Quantity.atanh(q)

	if getmetatable(q) ~= Quantity then
		q = Quantity.new(q)
	end

	if not q.dimension:iszero() then
		error("Error. The argument '"..tostring(q).."' of the inverse tangent hyperbolicus function is not unitless.")
	end

	local p = Quantity.new()

	if type(q.value) == "number" then
		p.value = 0.5 * math.log((1 + q.value)/(1 - q.value))
	else
		p.value = q:to().value:atanh()
	end

	return p
end

return Quantity


text:
package com.agapsys.logger;

import java.util.Date;

/**
 * Represents an output stream for log messages
 * @author Leandro Oliveira (leandro@agapsys.com)
 */
public interface LoggerStream {
	/**
	 * Print a message into stream
	 * @param localTimestamp local timestamp
	 * @param msg message to be printed
	 * @param logType log type
	 */
	void println(Date localTimestamp, String logType, String msg);

	/** Closes the stream. */
	void close();
}


text:
namespace dev
{
namespace db
{
namespace
{
inline leveldb::Slice toLDBSlice(Slice _slice)
{
    return leveldb::Slice(_slice.data(), _slice.size());
}

DatabaseStatus toDatabaseStatus(leveldb::Status const& _status)
{
    if (_status.ok())
        return DatabaseStatus::Ok;
    else if (_status.IsIOError())
        return DatabaseStatus::IOError;
    else if (_status.IsCorruption())
        return DatabaseStatus::Corruption;
    else if (_status.IsNotFound())
        return DatabaseStatus::NotFound;
    else
        return DatabaseStatus::Unknown;
}

void checkStatus(leveldb::Status const& _status, boost::filesystem::path const& _path = {})
{
    if (_status.ok())
        return;

    DatabaseError ex;
    ex << errinfo_dbStatusCode(toDatabaseStatus(_status))
       << errinfo_dbStatusString(_status.ToString());
    if (!_path.empty())
        ex << errinfo_path(_path.string());

    BOOST_THROW_EXCEPTION(ex);
}

class LevelDBWriteBatch : public WriteBatchFace
{
public:
    void insert(Slice _key, Slice _value) override;
    void kill(Slice _key) override;

    leveldb::WriteBatch const& writeBatch() const { return m_writeBatch; }
    leveldb::WriteBatch& writeBatch() { return m_writeBatch; }

private:
    leveldb::WriteBatch m_writeBatch;
};

void LevelDBWriteBatch::insert(Slice _key, Slice _value)
{
    m_writeBatch.Put(toLDBSlice(_key), toLDBSlice(_value));
}

void LevelDBWriteBatch::kill(Slice _key)
{
    m_writeBatch.Delete(toLDBSlice(_key));
}

}  // namespace

leveldb::ReadOptions LevelDB::defaultReadOptions()
{
    return leveldb::ReadOptions();
}

leveldb::WriteOptions LevelDB::defaultWriteOptions()
{
    return leveldb::WriteOptions();
}

leveldb::Options LevelDB::defaultDBOptions()
{
    leveldb::Options options;
    options.create_if_missing = true;
    options.max_open_files = 256;
    return options;
}

LevelDB::LevelDB(boost::filesystem::path const& _path, leveldb::ReadOptions _readOptions,
    leveldb::WriteOptions _writeOptions, leveldb::Options _dbOptions)
  : m_db(nullptr), m_readOptions(std::move(_readOptions)), m_writeOptions(std::move(_writeOptions))
{
    auto db = static_cast<leveldb::DB*>(nullptr);
    auto const status = leveldb::DB::Open(_dbOptions, _path.string(), &db);
    checkStatus(status, _path);

    assert(db);
    m_db.reset(db);
}

std::string LevelDB::lookup(Slice _key) const
{
    leveldb::Slice const key(_key.data(), _key.size());
    std::string value;
    auto const status = m_db->Get(m_readOptions, key, &value);
    if (status.IsNotFound())
        return std::string();

    checkStatus(status);
    return value;
}

bool LevelDB::exists(Slice _key) const
{
    std::string value;
    leveldb::Slice const key(_key.data(), _key.size());
    auto const status = m_db->Get(m_readOptions, key, &value);
    if (status.IsNotFound())
        return false;

    checkStatus(status);
    return true;
}

void LevelDB::insert(Slice _key, Slice _value)
{
    leveldb::Slice const key(_key.data(), _key.size());
    leveldb::Slice const value(_value.data(), _value.size());
    auto const status = m_db->Put(m_writeOptions, key, value);
    checkStatus(status);
}

void LevelDB::kill(Slice _key)
{
    leveldb::Slice const key(_key.data(), _key.size());
    auto const status = m_db->Delete(m_writeOptions, key);
    checkStatus(status);
}

std::unique_ptr<WriteBatchFace> LevelDB::createWriteBatch() const
{
    return std::unique_ptr<WriteBatchFace>(new LevelDBWriteBatch());
}

void LevelDB::commit(std::unique_ptr<WriteBatchFace> _batch)
{
    if (!_batch)
    {
        BOOST_THROW_EXCEPTION(DatabaseError() << errinfo_comment("Cannot commit null batch"));
    }
    auto* batchPtr = dynamic_cast<LevelDBWriteBatch*>(_batch.get());
    if (!batchPtr)
    {
        BOOST_THROW_EXCEPTION(
            DatabaseError() << errinfo_comment("Invalid batch type passed to LevelDB::commit"));
    }
    auto const status = m_db->Write(m_writeOptions, &batchPtr->writeBatch());
    checkStatus(status);
}

void LevelDB::forEach(std::function<bool(Slice, Slice)> _f) const
{
    std::unique_ptr<leveldb::Iterator> itr(m_db->NewIterator(m_readOptions));
    if (itr == nullptr)
    {
        BOOST_THROW_EXCEPTION(DatabaseError() << errinfo_comment("null iterator"));
    }
    auto keepIterating = true;
    for (itr->SeekToFirst(); keepIterating && itr->Valid(); itr->Next())
    {
        auto const dbKey = itr->key();
        auto const dbValue = itr->value();
        Slice const key(dbKey.data(), dbKey.size());
        Slice const value(dbValue.data(), dbValue.size());
        keepIterating = _f(key, value);
    }
}

}  // namespace db
}  // namespace dev


text:
/*A bare minimum self test function function */
#include <e-lib.h>
#include "common.h"
#include <string.h>

#define USE_DMA 1
#ifdef USE_DMA
#define e_memcopy(dst, src, size) e_dma_copy(dst, src, size)
#else
#define e_memcopy(dst, src, size) memcpy(dst, src, size)
#endif

#define MAILBOX_ADDR 0x810F0320

int main(void){

  int *mailbox= (int *) MAILBOX_ADDR;

  long long message = 0xfedcba9876543210;

  e_memcopy(mailbox, &message, sizeof(message));

}


text: ./gradlew testDebug && ./gradlew cC


text:
1. Fork and Clone Repository.
2. Open terminal and `cd` to path of the repo.
3. Install any node modules: `npm install`
4. Install gulp: `npm install gulp -g`

## Running the Enviornments
### Development
` npm run dev `

### Test (Karma-Mocha-Chai)
` npm run test `

### Production
` npm run build `

## Generators
This app comes with some helpful and generators for creating a new component/service. You simply have to hook them up to your components.js and services.js file.

### To create a new component:
` gulp component --name <NAME_OF_YOUR_COMPONENT> `

### To create a new common component:

` gulp common_component --name <NAME_OF_YOUR_COMPONENT> `

### To create a new service

` gulp service --name <NAME_OF_YOUR_SERVICE> `

##Project Structure

```
/app
  /assets
    /images
      /foo.png
  /common
    /button
      /button.js
      /button.component.js
      /button.controller.js
      /button.html
      /button.scss
      /button.test.js
    /navbar/
    /components.js
  /components
    /about
      /about.js
      /about.component.js
      /about.controller.js
      /about.html
      /about.scss
      /about.test.js
    /home/
    /components.js
  /services
    /users
      /users.js
      /users.service.js
      /users.test.js
    /documents/
    /services.js
  /app.config.js
  /index.js
  /index.html
  /index.scss
```

### Main/Entry File To the Project
`index.js` is the main entry file which serves as the total include point for all of your components, services, assets, and styles.


text:
import subprocess
import sys

process = subprocess.Popen([sys.executable, 'repy.py', '--ip', '127.0.0.1', 'restrictions.default', 'ip_onlyloopback_checkgetmyip.py'])
process.wait()


text:
import { EventBus } from 'app/utils/observable';
import { DimItem } from '../inventory/item-types';

export const showInfuse$ = new EventBus<DimItem>();

/**
 * Show the infusion fuel finder.
 */
export function showInfuse(item: DimItem) {
  showInfuse$.next(item);
}


text:
<?php

/**
 * Extended CMS page collection
 *
 * @category    Mage
 * @package     Mage_XmlConnect
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_XmlConnect_Model_Resource_Cms_Page_Collection extends Mage_Cms_Model_Resource_Page_Collection
{
    /**
     * Returns pairs identifier - title for unique identifiers
     * and pairs identifier|page_id - title for non-unique after first
     *
     * @return array
     */
    public function toOptionIdArray()
    {
        $model = $app = Mage::helper('xmlconnect')->getApplication();
        $this->addStoreFilter($model->getStoreId());

        $res = array();
        $existingIdentifiers = array();
        foreach ($this as $item) {
            $identifier = $item->getData('identifier');

            $data['value'] = $identifier;
            $data['label'] = $item->getData('title');
            if (in_array($identifier, $existingIdentifiers)) {
                $data['value'] .= '|' . $item->getData('page_id');
            } else {
                $existingIdentifiers[] = $identifier;
            }

            $res[] = $data;
        }

        return $res;
    }
}


text:
mkdir -p $HOME/.reactor
mkdir -p $HOME/.m2

if (type vagrant) && (type virtualbox) then

    echo "get latest vagrant file"
    wget https://raw.githubusercontent.com/tascape/reactor-report/master/doc/Vagrantfile -O Vagrantfile
    vagrant up

    export PROP=$HOME/.reactor/reactor.properties
    echo "create reactor system properties file" $PROP
cat <<EOF > $PROP
# reactor system properties
# use -Dkey=value to override or add in commandline
reactor.db.type=mysql
reactor.db.host=localhost:23306
reactor.log.path=$HOME/.reactor/logs
reactor.case.station=localhost
reactor.JOB_NAME=local-run
EOF
cat $PROP

    echo "check report at http://localhost:28088/rr/suites_result.xhtml"
    open "http://localhost:28088/rr/suites_result.xhtml" || echo "OK"

else
    echo "you need to first install vagrant (http://www.vagrantup.com/downloads.html) and virtualbox (https://www.virtualbox.org/wiki/Downloads)"
fi


text:
#ifndef ES_SECURITY_TIMING_H__
#define ES_SECURITY_TIMING_H__

#include <stdint.h>
#include "app_error.h"

/**
 * @file
 * @addtogroup eddystone_security
 * @{
 */

typedef uint8_t es_stopwatch_id_t;

/**@brief Function for getting the number of seconds passed since the last invocation.
 * @details If the function returns zero, the 'last time called' state is not updated. If a non-zero value
 *       is returned, the 'last time called' state will point to the last whole second.
 * @return    Number of seconds passed since the last invocation.
 */
uint32_t es_stopwatch_check(es_stopwatch_id_t id);

ret_code_t es_stopwatch_create(es_stopwatch_id_t * p_sw_id, uint32_t ticks_wrap);

/**@brief Function for initializing the security timing module.
 */
void es_stopwatch_init(void);

/**
 * @}
 */

#endif // ES_SECURITY_TIMING_H__


text:
<?php
if($_POST){
	$name=$_POST['name'];
	$email=$_POST['email'];
	$comments=$_POST['comments'];

	//Here Write Sql Insert commeand to srote
	//the data into database as well as send acknowledgement mail

	//Here i'm considering both sql insert and send mail success so $result=1
	$result=1;

	if($result){
		echo "success";

		//$handle = fopen("contactvjcet.txt", "a");

		//if($handle)
		//{
	//	echo 'success';

		$text= '
'.$name.'

'.$email.'

'.$comments.'

';
		//echo $text;
   //fwrite = ($handle,$text);//not the way to append to textfile
//   $data = sprintf("%s %s %s\n", $name, $email, $comments);
file_put_contents('contactvjcet.txt', $text, FILE_APPEND);

//}
//else
echo 'failed';
//fclose($handle);

	}

exit();
}
?>