text:
#ifndef _LEMMATIZER_
#define _LEMMATIZER_

#include <functional>
#include "lemmatizer-interface.h"

namespace lemmatizer
{

/**
 * @class	Lemmatizer
 * @brief	Class for lemmatizing words to its lemma with help of dictionary
 */
class Lemmatizer : public ILemmatizer
{
public:
    /**
     * @brief Default constructor
     * @param[in] i_disambiguator - pointer to disambiguator. If i_disambiguator is NULL,
     * create own disambiguator, otherwise (i_disambiguator not NULL) use outsider disambiguator
     */
    Lemmatizer(shared_ptr<IDisambiguator> i_disambiguator = NULL);

    /**
     * @brief lemmatize is the main function
     * @param[in] i_tokens is a number of tokens to lemmatization
     * @param[in] i_extractor custom processing function (see static methods)
     * @param[out] o_result is place to store result of lemmatization
     * @return true if dictionary has token, false otherwise
     */
    bool lemmatize(const vector<Token>& i_tokens, vector<wstring>& o_result, const std::function<wstring(const DisambiguatedData&)>& i_extractor);

    /**
     * @brief lemmatize is the main function
     * @param[in] i_tokens is a number of tokens to lemmatization
     * @param[out] o_result is place to store result of lemmatization
     * @return true if dictionary has token, false otherwise
     */
    bool lemmatize(const vector<Token>& i_tokens, vector<wstring>& o_result);

    /**
     * @brief tokens is getter for m_token
     * @return Function returns last token which was lemmatize
     */
    vector<Token> tokens(void)
    {
        return m_tokens;
    }

    /**
     * @brief result is getter for m_result.
     * @return Function returns result of last lemmatization
     */
    vector<wstring> result(void)
    {
        return m_result;
    }

    void clean(void);

    static wstring extractLemma(const DisambiguatedData& i_ddata)
    {
        return (i_ddata.lemma.empty()) ? i_ddata.content : i_ddata.lemma;
    }

    static wstring extractMorphology(const DisambiguatedData& i_ddata)
    {
        return i_ddata.label;
    }

    static wstring replaceUnknownTokens(const DisambiguatedData& i_ddata)
    {
        return (i_ddata.lemma.empty()) ? L"<unk>" : i_ddata.content;
    }

    static wstring lemmaAndMorphology(const DisambiguatedData& i_ddata)
    {
        wstring lemma = (i_ddata.lemmaId == -1) ? i_ddata.content : i_ddata.lemma;
        wstring morph = i_ddata.label;
        wstring o_result = lemma + L":" + morph;
        return o_result;
    }

    static wstring wordLemmaAndMorphology(const DisambiguatedData& i_ddata)
    {
        wstring lemma = (i_ddata.lemmaId == -1) ? L"#LemmaNotFoundError" : i_ddata.lemma;
        wstring morph = i_ddata.label;
        wstring o_result = i_ddata.content + L":" + lemma + L":" + morph;
        return o_result;
    }

protected:
    void addDDataToResult_(vector<DisambiguatedData>& i_ddata, const std::function<wstring(const DisambiguatedData&)>& i_extractor);

    bool m_ownDisambiguator;

    shared_ptr<DictionaryInterface> m_dict;
    shared_ptr<IDisambiguator> m_disambiguator;
    vector<Token> m_tokens;
    vector<wstring> m_result;
};

shared_ptr<ILemmatizer> GetLemmatizer(Tools::Language lang = Tools::Language::RU);
void Lemmatize(const char* fileIn, const char* fileOut, int &SentenceCounter, Tools::Language lang = Tools::Language::RU);

}
#endif //_LEMMATIZER_


text:
<?php

namespace fecadmin\models\AdminUser;
use fecadmin\models\AdminUser;
use yii\base\Model;
/**
 * @author Terry Zhao <2358269014@qq.com>
 * @since 1.0
 */
class AdminUserLogin extends Model{

	public $username;
	public $password;
	public $captcha;
	private $_admin_user;
	public function rules()
    {
        return [
            [['username', 'password'], 'required'],
			['password', 'validatePassword'],
         //   ['captcha', 'captcha','captchaAction'=>'/fecadmin/captcha/index'],
		//	 ['captcha', 'required'],
        ];
    }

	public function validatePassword($attribute,$params){

		if (!$this->hasErrors()) {
            $AdminUser = $this->getAdminUser();
            if (!$AdminUser) {
                $this->addError('用户名', '用户名不存在');
            }else if(!$AdminUser->validatePassword($this->password)){
				$this->addError('用户名或密码','不正确');
			}
        }
	}

	public function getAdminUser(){
		if($this->_admin_user === null){
			$this->_admin_user = AdminUser::findByUsername($this->username);
		}
		return $this->_admin_user;

	}

	public function login()
    {
        if ($this->validate()) {
            //return \Yii::$app->user->login($this->getAdminUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
			return \Yii::$app->user->login($this->getAdminUser(), 3600 * 24);
        } else {
            return false;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace VhostManager\ApiBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * domains
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class domain
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text")
     */
    private $description;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return domains
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return domains
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }
}


text:
package me.benroberts.lib.scuba;

/**
 * @author Ben Roberts (ben@benroberts.me)
 */
public class CnsOtu {

	public static class MaxPo2ExceededException extends Exception {
		private static final long serialVersionUID = 9110983151742007956L;
	}

	private float mSurfacePressure;
	private Units mUnits;

	private float mCns;
	private float mOtu;

	private int mDepth = 0;

	public CnsOtu(int altitude, Units units, float resCNS, float resOTU) {
		mSurfacePressure = GasSource.pressureAtAltitude(altitude, units);
		mUnits = units;
		mCns = resCNS;
		mOtu = resOTU;
	}

	public float getCns() { return mCns; }
	public float getOtu() { return mOtu; }

	/**
	 * Execute a depth change on the CNS/OTU model, and compute the result.
	 * @param newDepth The new depth to change to
	 * @param time The amount of time it's expected to take to get to the
	 * desired depth from the current one
	 * @param source the GasSource being breathed during the depth change
	 * @throws MaxPo2ExceededException
	 */
	public void changeDepth(int newDepth, float time, GasSource source) throws MaxPo2ExceededException {
		final double po2i = source.pO2AtDepth(mDepth, mSurfacePressure, mUnits);
		final double po2f = source.pO2AtDepth(mDepth, mSurfacePressure, mUnits);
		mCns += getCNSPerMinute(po2i, po2f) * time;
		mOtu += getOTUPerMinute(po2i, po2f) * time;
	}

	/**
	 * Execute a constant exposure on the CNS/OTU model based on the current
	 * depth, and compute the result.
	 * @param time The amount of time at which to stay at the current depth
	 * @param source The GasSource being breathed during this time
	 * @throws MaxPo2ExceededException
	 */
	public void run(float time, GasSource source) throws MaxPo2ExceededException {
		final double po2 = source.pO2AtDepth(mDepth, mSurfacePressure, mUnits);
		mCns += getCNSPerMinute(po2) * time;
		mOtu += getOTUPerMinute(po2) * time;
	}

	// Uses NOAA data with linear interpolation at lower pO2's to get CNS
	// loading rate in percent per minute at the passed pO2 in ATA.
	public static float getCNSPerMinute(double po2) throws MaxPo2ExceededException {
		// Source of this data is the 2004 edition TDI Advanced Trimix manual,
		// combined with an older table I got from TDI somewhere that was more
		// precise, but less conservative. The most conservative values
		// available from each were combined into this model.
		if(po2 < 0.55) {
			return 0;
		} else if(po2 <= 0.8) {
			// NOAA data has CNS accumulation per minute go up by 0.04 for every
			// 0.1 ata increase in pO2, with 0.6 ata creating 0.14% CNS per min.
			// This linear relationship models that data.
			return 0.4f * (float)po2 - 0.1f;
		} else if(po2 <= 0.9) {
			// From here on out we can't assume the relationship is linear, so
			// we go conservative and round up.
			return 0.33f;
		} else if(po2 <= 1) {
			return 0.42f;
		} else if(po2 <= 1.1) {
			return 0.48f;
		} else if(po2 <= 1.2) {
			// At 1.2 and above, the older more precise table I have corresponds
			// exactly to the 2004 table. So I'm using the older data with 0.05
			// increments as long as the latest data continues to agree with it.
			return 0.48f;
		} else if(po2 <= 1.25) {
			return 0.51f;
		} else if(po2 <= 1.3) {
			return 0.56f;
		} else if(po2 <= 1.35) {
			return 0.61f;
		} else if(po2 <= 1.4) {
			return 0.67f;
		} else if(po2 <= 1.45) {
			return 0.73f;
		} else if(po2 <= 1.5) {
			return 0.83f;
		} else if(po2 <= 1.55) {
			return 1.12f;
		} else if(po2 <= 1.6) {
			return 2.22f;
		} else {
			throw new MaxPo2ExceededException();
		}
	}

	public static float getCNSPerMinute(double po2i, double po2f) throws MaxPo2ExceededException {
		// This method does a sum of the contributions of the highest pO2 and
		// all po2's on a 0.05 interval and weights them by the interval width
		// (the first and last pO2's can be off-interval, affecting the end
		// widths)
		final double po2Hi = Math.max(po2i, po2f);
		final double po2Lo = Math.min(po2i, po2f);
		double change = po2Hi - po2Lo;
		float result = 0;
		float interval;
		for(double p = po2Hi; p > po2Lo; p -= interval) {
			final float pDev = (float)p / 0.05f - (int)(p / 0.05);
			if(pDev > 0) {
				// p is not a multiple of our interval. Set interval to the
				// difference
				interval = pDev;
			} else {
				// Set the interval to either 0.05 or, if we're at the last
				// segment, the distance between the current value and the
				// low pO2.
				interval = Math.min((float)(p - po2Lo), 0.05f);
			}
			result += getCNSPerMinute(p) * interval / change;
		}

		return result;
	}

	public static float getOTUPerMinute(double po2) {
		// Uses equation published in 2004 edition TDI Advanced Trimix manual
		return (float)Math.pow(0.5 / (po2 - 0.05), -5/6);
	}

	public static float getOTUPerMinute(double po2i, double po2f) {
		// Uses equation published in 2004 edition TDI Advanced Trimix manual
		if(po2i == po2f) {
			// Avoid divide by 0
			return getOTUPerMinute(po2i);
		}
		return (float)(3 / (11 * po2f - po2i) * (Math.pow((po2f - 0.5) / 0.5, 11/6) - Math.pow((po2f - 0.5) / 0.5, 11/6)));
	}
}


text:
<?php
namespace CodeTool\ArtifactDownloader\Runit\Command\Factory;

use CodeTool\ArtifactDownloader\Command\CommandInterface;

interface RunitCommandFactoryInterface
{
    /**
     * @param string $serviceName
     * @param string $targetState
     * @param bool   $fatal
     *
     * @return CommandInterface
     */
    public function createSetServiceStateCommand($serviceName, $targetState, $fatal = true);
}


text:
module Ca
  module Exceptions
    # Class Ca::Exceptions::IncompleteTags
    class IncompleteTags < Exception
    end
  end
end


text:
from termcolor import colored
class ColorPrinter:
  def __init__(self, verbose = False):
    self.verbose = verbose

  def puts(self, text, to_print = None, to_compare = None):
    if to_print == to_compare:
      if self.verbose or (to_print is None and to_compare is None):
        print(colored(text, 'green'))
    else:
      print(colored(text, 'yellow'))


text:
var dao;

/**
  * Initializes the module and stores the dao.
  */
exports.setup = function (daoIn) {
    dao = daoIn;
}

/**
  * Loads data in the datastore to simulate a
  * production enviroment.
  */
exports.loadDevelopmentData = function () {
    storeDevelopmentData ();
}

/**
  * This wipes the datastore and then writes
  * the simulation data in the datastore.
  */
function storeDevelopmentData () {
    // first drop all collections
    dao.CleanDatastore (function () {
        // now that the db is clean lets add some simulated data
        dao.CreateNewUser ("michael dillon", "michaelcdillon",
                           "michaelcdillon@me.com", function () {});
        dao.SaveNewPost ("apost.post", "SimTitle", "
Simulated Content

lorem ipsum
",
                         Date (), "sim-commit-id-asdf877239sdkasf9", "michaelcdillon@me.com",
                         "michaelcdillon", "michael dillon");
    });
}


text:
**Inspector++**

Inspector++ Is a tool to visually create Unity inspectors

![Main](https://raw.githubusercontent.com/ArthurBrussee/InspectorPlusPlus/master/MainGithub.PNG)

**Set-up**

As soon as you imported this asset you can start creating inspectors! Open the Inspector++ window via the Window->Inspector++ menu.

**Adding Inspectors**
Select your scripts from your project window. All MonoBehaviours or ScriptableObjects you selected appear in the window. Click create and you're done!

**Editing Inspectors**
Inspector++ includes a window to visually edit your inspectors. Open it by clicking 'edit' next to the file you want to edit.

The window displays all variables, with some options. Here are the basic options in order:

- The first toggle hides or unhides the variable from the inspector.
- The display name of the variable
- A toggle to enable a tooltip
- A field for the tooltip
- Arrow to move the variable up
- Arrow to move the variable down
- The last toggle enables/disables writing to the field (Disable it to make a read-only property)

From there it depends on the type of variable what kind of controls you see.

Under the variable there is a smal seperator. You can drag this seperator to put some space between vars. When the box is large enough you will notice some additional controls. From left to right:

- Toggle to enable or disable a label
- The text of the label.
- Toggle for a Bold label
- Toggle to enable or disable a button
- The text that should appear on the button.
- The function that should be called when the button is pressed
- If you have multiple buttons, you can 'condense' them. This means they will stick together and take up less space.

You can add a maximum of 16 buttons (4 per line) and 4 labels

Tooltips
You can make tooltips via a toggle and textfield in the editor, but also through scripting, in 2 different ways:

1. a summary (C# only)
```C#
///<summary>
///this will be my tooltip!
///</summary>
public float tooltip;
````

2.Attribute:
```C#
[Tooltip("This will be my tooltip!")]
public int myInt;
```

**Save to file**
You can also use 'Save to file'. This features produces a C# file you can share in your projects or use in an asset store project. The .cs file is a optimized version of your custom inspector. Note that when you edit your inspector, this file doesn't get updated. You need to regenerate it after any changes.


text:
CREATE TABLE pbAaDistQ (
  x float default NULL,
  y float default NULL
) TYPE=MyISAM;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Function template replacements</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../yap/reference.html#header.boost.yap.algorithm_hpp" title="Header <boost/yap/algorithm.hpp>">
<link rel="prev" href="make_expression_function.html" title="Function template make_expression_function">
<link rel="next" href="replace_placeholders.html" title="Function template replace_placeholders">

Home
Libraries
People
FAQ
More

Function template replacements

boost::yap::replacements

Synopsis

// In header: <boost/yap/algorithm.hpp>

template<typename... T> constexpr auto replacements(T &&... t);

Description

Returns a transform object that replaces placeholders within an expression with the given values.

Copyright © 2018 T. Zachary Laine

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package org.apache.hive.jdbc;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.hive.jdbc.Utils.JdbcConnectionParams;
import org.apache.zookeeper.Watcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class ZooKeeperHiveClientHelper {
  static final Logger LOG = LoggerFactory.getLogger(ZooKeeperHiveClientHelper.class.getName());
  // Pattern for key1=value1;key2=value2
  private static final Pattern kvPattern = Pattern.compile("([^=;]*)=([^;]*)[;]?");
  /**
   * A no-op watcher class
   */
  static class DummyWatcher implements Watcher {
    @Override
    public void process(org.apache.zookeeper.WatchedEvent event) {
    }
  }

  static void configureConnParams(JdbcConnectionParams connParams)
      throws ZooKeeperHiveClientException {
    // 获得zooKeeperEnsemble, 例如: zkNode1:2181,zkNode2:2181,zkNode3:2181, 也即是hive-site.xml中hive.zookeeper.quorum的值
    String zooKeeperEnsemble = connParams.getZooKeeperEnsemble();
    // 获取zooKeeperNamespace, 比如: hiveserver2_zk, 也即是hive-site.xml中hive.server2.zookeeper.namespace的值
    String zooKeeperNamespace =
        connParams.getSessionVars().get(JdbcConnectionParams.ZOOKEEPER_NAMESPACE);
    // 如果为null或为空, 设置为默认的namespace: hiveserver2
    if ((zooKeeperNamespace == null) || (zooKeeperNamespace.isEmpty())) {
      zooKeeperNamespace = JdbcConnectionParams.ZOOKEEPER_DEFAULT_NAMESPACE;
    }
    List<String> serverHosts;
    Random randomizer = new Random();
    String serverNode;
    // 构造zooKeeperClient
    CuratorFramework zooKeeperClient =
        CuratorFrameworkFactory.builder().connectString(zooKeeperEnsemble)
            .retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
    try {
      // 启动client
      zooKeeperClient.start();
      serverHosts = zooKeeperClient.getChildren().forPath("/" + zooKeeperNamespace);
      // Remove the znodes we've already tried from this list
      // 移除不需要的节点, 即移除丢弃的hiveserve2节点, 默认为空
      serverHosts.removeAll(connParams.getRejectedHostZnodePaths());
      if (serverHosts.isEmpty()) {
        throw new ZooKeeperHiveClientException(
            "Tried all existing HiveServer2 uris from ZooKeeper.");
      }
      // Now pick a server node randomly
      // 一般配置了几个hiveServer2到zookeeper, serverHosts.size()就为多少, 这里是随机选择一个hiveServer2节点
      // 比如我们配置了两个节点, 分别是: serverUri=BDS-TEST-002:10000;version=1.2.1;sequence=0000000019 serverUri=BDS-TEST-001:10000;version=1.2.1;sequence=0000000025
      serverNode = serverHosts.get(randomizer.nextInt(serverHosts.size()));
      // 将选中的hiveserver2节点设置给currentHostZnodePath
      connParams.setCurrentHostZnodePath(serverNode);
      // Read data from the znode for this server node
      // This data could be either config string (new releases) or server end
      // point (old releases)
      // 这里比如我们获取的是BDS-TEST-002对应的节点, dataStr值为:
      /*
        BDS-TEST-002:10000
        cZxid = 0xa002ea844
        ctime = Fri Dec 23 11:39:25 CST 2016
        mZxid = 0xa002ea844
        mtime = Fri Dec 23 11:39:25 CST 2016
        pZxid = 0xa002ea844
        cversion = 0
        dataVersion = 0
        aclVersion = 0
        ephemeralOwner = 0x258d78d9ed70018
        dataLength = 18
        numChildren = 0
      */
      String dataStr =
          new String(
              zooKeeperClient.getData().forPath("/" + zooKeeperNamespace + "/" + serverNode),
              Charset.forName("UTF-8"));
      Matcher matcher = kvPattern.matcher(dataStr);
      // If dataStr is not null and dataStr is not a KV pattern,
      // it must be the server uri added by an older version HS2
      if ((dataStr != null) && (!matcher.find())) {
        String[] split = dataStr.split(":");
        if (split.length != 2) {
          throw new ZooKeeperHiveClientException("Unable to read HiveServer2 uri from ZooKeeper: "
              + dataStr);
        }
        connParams.setHost(split[0]);
        connParams.setPort(Integer.parseInt(split[1]));
      } else {
        // 对dataStr中的key value对进行分析设置给connParams
        applyConfs(dataStr, connParams);
      }
    } catch (Exception e) {
      throw new ZooKeeperHiveClientException("Unable to read HiveServer2 configs from ZooKeeper", e);
    } finally {
      // Close the client connection with ZooKeeper
      if (zooKeeperClient != null) {
        zooKeeperClient.close();
      }
    }
  }

  /**
   * Apply configs published by the server. Configs specified from client's JDBC URI override
   * configs published by the server.
   *
   * @param serverConfStr
   * @param connParams
   * @throws Exception
   */
  private static void applyConfs(String serverConfStr, JdbcConnectionParams connParams)
      throws Exception {
    Matcher matcher = kvPattern.matcher(serverConfStr);
    while (matcher.find()) {
      // Have to use this if-else since switch-case on String is supported Java 7 onwards
      if ((matcher.group(1) != null)) {
        if ((matcher.group(2) == null)) {
          throw new Exception("Null config value for: " + matcher.group(1)
              + " published by the server.");
        }
        // Set host
        if (matcher.group(1).equals("hive.server2.thrift.bind.host")) {
          connParams.setHost(matcher.group(2));
        }
        // Set transportMode
        if ((matcher.group(1).equals("hive.server2.transport.mode"))
            && !(connParams.getSessionVars().containsKey(JdbcConnectionParams.TRANSPORT_MODE))) {
          connParams.getSessionVars().put(JdbcConnectionParams.TRANSPORT_MODE, matcher.group(2));
        }
        // Set port
        if (matcher.group(1).equals("hive.server2.thrift.port")) {
          connParams.setPort(Integer.parseInt(matcher.group(2)));
        }
        if ((matcher.group(1).equals("hive.server2.thrift.http.port"))
            && !(connParams.getPort() > 0)) {
          connParams.setPort(Integer.parseInt(matcher.group(2)));
        }
        // Set sasl qop
        if ((matcher.group(1).equals("hive.server2.thrift.sasl.qop"))
            && !(connParams.getSessionVars().containsKey(JdbcConnectionParams.AUTH_QOP))) {
          connParams.getSessionVars().put(JdbcConnectionParams.AUTH_QOP, matcher.group(2));
        }
        // Set http path
        if ((matcher.group(1).equals("hive.server2.thrift.http.path"))
            && !(connParams.getSessionVars().containsKey(JdbcConnectionParams.HTTP_PATH))) {
          connParams.getSessionVars().put(JdbcConnectionParams.HTTP_PATH, matcher.group(2));
        }
        // Set SSL
        if ((matcher.group(1) != null) && (matcher.group(1).equals("hive.server2.use.SSL"))
            && !(connParams.getSessionVars().containsKey(JdbcConnectionParams.USE_SSL))) {
          connParams.getSessionVars().put(JdbcConnectionParams.USE_SSL, matcher.group(2));
        }
        /**
         * Note: this is pretty messy, but sticking to the current implementation.
         * Set authentication configs. Note that in JDBC driver, we have 3 auth modes: NOSASL,
         * Kerberos (including delegation token mechanism) and password based.
         * The use of JdbcConnectionParams.AUTH_TYPE==JdbcConnectionParams.AUTH_SIMPLE picks NOSASL.
         * The presence of JdbcConnectionParams.AUTH_PRINCIPAL==<principal> picks Kerberos.
         * If principal is absent, the presence of
         * JdbcConnectionParams.AUTH_TYPE==JdbcConnectionParams.AUTH_TOKEN uses delegation token.
         * Otherwise password based (which includes NONE, PAM, LDAP, CUSTOM)
         */
        if (matcher.group(1).equals("hive.server2.authentication")) {
          // NOSASL
          if (matcher.group(2).equalsIgnoreCase("NOSASL")
              && !(connParams.getSessionVars().containsKey(JdbcConnectionParams.AUTH_TYPE) && connParams
                  .getSessionVars().get(JdbcConnectionParams.AUTH_TYPE)
                  .equalsIgnoreCase(JdbcConnectionParams.AUTH_SIMPLE))) {
            connParams.getSessionVars().put(JdbcConnectionParams.AUTH_TYPE,
                JdbcConnectionParams.AUTH_SIMPLE);
          }
        }
        // KERBEROS
        // If delegation token is passed from the client side, do not set the principal
        if (matcher.group(1).equalsIgnoreCase("hive.server2.authentication.kerberos.principal")
            && !(connParams.getSessionVars().containsKey(JdbcConnectionParams.AUTH_TYPE) && connParams
                .getSessionVars().get(JdbcConnectionParams.AUTH_TYPE)
                .equalsIgnoreCase(JdbcConnectionParams.AUTH_TOKEN))
            && !(connParams.getSessionVars().containsKey(JdbcConnectionParams.AUTH_PRINCIPAL))) {
          connParams.getSessionVars().put(JdbcConnectionParams.AUTH_PRINCIPAL, matcher.group(2));
        }
      }
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2014 Stresso authors (see AUTHORS)

  Licensed 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 xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>io.github.astralway</groupId>
  <artifactId>stresso</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Stresso</name>
  <description>This repo contains an example application designed to stress Apache Fluo</description>
  <url>https://github.com/astralway/stresso</url>

  <properties>
    <accumulo.version>1.7.2</accumulo.version>
    <hadoop.version>2.6.3</hadoop.version>
    <fluo.version>1.0.0-incubating</fluo.version>
    <fluo-recipes.version>1.0.0-incubating</fluo-recipes.version>
    <slf4j.version>1.7.12</slf4j.version>
  </properties>

  <profiles>
    <profile>
      <id>mini-accumulo</id>
      <activation>
        <property>
          <name>!skipTests</name>
        </property>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.accumulo</groupId>
            <artifactId>accumulo-maven-plugin</artifactId>
            <version>${accumulo.version}</version>
            <configuration>
              <instanceName>it-instance-maven</instanceName>
              <rootPassword>ITSecret</rootPassword>
            </configuration>
            <executions>
              <execution>
                <id>run-plugin</id>
                <goals>
                  <goal>start</goal>
                  <goal>stop</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <optimize>true</optimize>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-failsafe-plugin</artifactId>
        <configuration>
          <systemPropertyVariables>
            <fluo.it.instance.name>it-instance-maven</fluo.it.instance.name>
            <fluo.it.instance.clear>false</fluo.it.instance.clear>
          </systemPropertyVariables>
        </configuration>
        <executions>
          <execution>
            <id>run-integration-tests</id>
            <goals>
              <goal>integration-test</goal>
              <goal>verify</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>shade</goal>
            </goals>
            <phase>package</phase>
            <configuration>
              <shadedArtifactAttached>true</shadedArtifactAttached>
              <shadedClassifierName>shaded</shadedClassifierName>
              <filters>
                <filter>
                  <artifact>*:*</artifact>
                  <excludes>
                    <exclude>META-INF/*.SF</exclude>
                    <exclude>META-INF/*.DSA</exclude>
                    <exclude>META-INF/*.RSA</exclude>
                  </excludes>
                </filter>
              </filters>
            </configuration>
          </execution>
        </executions>
      </plugin>

    </plugins>
  </build>

  <!--
       The provided scope is used for dependencies that should not end up in
       the shaded jar.  The shaded jar is used to run map reduce jobs via the yarn
       command.  The yarn command will provided hadoop dependencies, so they are not
       needed in the shaded jar.
  -->

  <dependencies>
    <dependency>
      <groupId>org.apache.fluo</groupId>
      <artifactId>fluo-api</artifactId>
      <version>${fluo.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.fluo</groupId>
      <artifactId>fluo-core</artifactId>
      <version>${fluo.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.fluo</groupId>
      <artifactId>fluo-mapreduce</artifactId>
      <version>${fluo.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.fluo</groupId>
      <artifactId>fluo-recipes-core</artifactId>
      <version>${fluo-recipes.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.accumulo</groupId>
      <artifactId>accumulo-core</artifactId>
      <version>${accumulo.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-client</artifactId>
      <version>${hadoop.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>13.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>commons-configuration</groupId>
      <artifactId>commons-configuration</artifactId>
      <version>1.10</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.10</version>
      <scope>provided</scope>
    </dependency>

    <!-- Test Dependencies -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.accumulo</groupId>
      <artifactId>accumulo-minicluster</artifactId>
      <version>${accumulo.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.fluo</groupId>
      <artifactId>fluo-mini</artifactId>
      <version>${fluo.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.fluo</groupId>
      <artifactId>fluo-recipes-test</artifactId>
      <version>${fluo-recipes.version}</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
define({
  root: {
    instruction: 'Enter any custom CSS for your application here:'
  }
});


text:
import { Component, Input } from '@angular/core';
import { SymbolGroup } from '../../../entities/symbol-group';
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';

@Component({
  selector: 'test-case-table',
  styleUrls: ['./test-case-table.component.scss'],
  templateUrl: './test-case-table.component.html'
})
export class TestCaseTableComponent {

  @Input()
  testCase: any;

  @Input()
  result: any;

  @Input()
  symbolMap: any;

  @Input()
  groups: SymbolGroup[];

  drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      transferArrayItem(event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex);
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Synergy.Lerman.Models;
using Synergy.Lerman.Realm.Books;
using Synergy.Lerman.Realm.Infrastructure;
using Synergy.Lerman.Realm.Users;

namespace Synergy.Lerman.Realm.Lessons
{
    public class Lesson
    {
        public string Id { get; set; }
        public Book Book { get; set; }
        public Category Category { get; set; }

        private List<Word> toLearn;
        private List<Word> learned;
        private List<LearningWord> learning;

        public DateTime StartedOn { get; }
        public DateTime? FinishedOn { get; private set; }
        public int WordCount => this.toLearn.Count + this.learned.Count;
        public int ElapsedMinutes
        {
            get
            {
                var end = this.FinishedOn ?? DateTime.Now;
                var minutes = end.Subtract(this.StartedOn).TotalMinutes;
                if (minutes < 1)
                    minutes = 1;
                return (int)minutes;
            }
        }

        public Lesson(string id, Book book, Category category, int? count)
        {
            this.Id = id;
            this.Book = book;
            this.Category = category;
            int noOfWords = count ?? 30;
            this.toLearn = new List<Word>(noOfWords);
            this.learned = new List<Word>(noOfWords);
            this.learning = new List<LearningWord>();

            this.PrepareWords(category, noOfWords);
            this.StartedOn = DateTime.Now;
        }

        private void PrepareWords(Category category, int count)
        {
            List<Word> wordsAlreadyLearned = CurrentUser.GetLearnedWords();
            var allWords = category.Words.Except(wordsAlreadyLearned).ToList();
            if (allWords.Count == 0)
            {
                // TODO: Losuj spośród pomyłek
                allWords = category.Words.ToList();
            }

            var noOfWordsInLesson = Math.Min(count, allWords.Count);
            for (int i = 0; i < noOfWordsInLesson; i++)
            {
                int randomIndex = CryptoRandom.NextIndex(allWords.Count);
                var word = allWords[randomIndex];
                allWords.Remove(word);
                this.toLearn.Add(word);
            }
        }

        public Word NextWord(Word lastWord = null)
        {
            if (this.toLearn.Count == 0)
                return null;

            var unknownWords = this.toLearn.ToList();
            if (this.toLearn.Count > 1 && lastWord != null)
            {
                unknownWords.Remove(lastWord);
            }

            int randomIndex = CryptoRandom.NextIndex(unknownWords.Count);
            return unknownWords[randomIndex];
        }

        public string GetProgress()
        {
            return $"{this.learned.Count} / {this.WordCount}";
        }

        public int GetSpeed()
        {
            return (int)(this.learned.Count / this.ElapsedMinutes);
        }

        public void NoticeAnswer(LearnInputModel inputModel)
        {
            if (inputModel.PreviousWord == null)
                return;

            var word = this.toLearn.FirstOrDefault(w => w.Polish == inputModel.PreviousWord);
            if (word == null)
                return;

            LearningWord learning = NoticeLearningOf(word);

            if (inputModel.UserMarkedWordAsLearned())
            {
                this.toLearn.Remove(word);
                this.learned.Add(word);
                learning.Learned = true;
            }
            else
            {
                learning.Mistakes++;
            }

            CurrentUser.Learned(learning);
        }

        internal Word GetWord(string polish)
        {
            return this.Category.GetWord(polish);
                //.FirstOrDefault(w => w.Word.Polish == polish)
                //?.Word
                //.FailIfNull("There is no '{0} in lesson {1}", polish, this.Id)
                //;
        }

        private LearningWord NoticeLearningOf(Word word)
        {
            var learning = this.learning.FirstOrDefault(m => m.Word.Polish == word.Polish);
            if (learning == null)
            {
                learning = new LearningWord(word);
                this.learning.Add(learning);
            }

            return learning;
        }

        public bool LearnedAll()
        {
            return this.toLearn.Count == 0;
        }

        internal void Finished()
        {
            this.FinishedOn = DateTime.Now;
        }
    }
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<geo:GeodesyML xsi:schemaLocation="urn:xml-gov-au:icsm:egeodesy:0.3" xmlns:geo="urn:xml-gov-au:icsm:egeodesy:0.3" xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:ns9="http://www.w3.org/1999/xlink" xmlns:gmd="http://www.isotc211.org/2005/gmd" xmlns:gmx="http://www.isotc211.org/2005/gmx" xmlns:om="http://www.opengis.net/om/2.0" xmlns:gco="http://www.isotc211.org/2005/gco" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" gml:id="GeodesyMLType_620">
   <geo:siteLog gml:id="SiteLogType_620">
      <geo:formInformation>
         <geo:preparedBy>Nick Dando</geo:preparedBy>
         <geo:datePrepared>2012-11-04T13:00:00Z</geo:datePrepared>
         <geo:reportType>UPDATE</geo:reportType>
      </geo:formInformation>
      <geo:siteIdentification>
         <geo:siteName>Warakurna</geo:siteName>
         <geo:fourCharacterID>WARA</geo:fourCharacterID>
         <geo:iersDOMESNumber>50198M001</geo:iersDOMESNumber>
         <geo:cdpNumber>not available</geo:cdpNumber>
         <geo:monumentDescription>PILLAR</geo:monumentDescription>
         <geo:heightOfTheMonument>1.5</geo:heightOfTheMonument>
         <geo:monumentFoundation>STEEL RODS / CONCRETE BLOCK</geo:monumentFoundation>
         <geo:foundationDepth>0.5</geo:foundationDepth>
         <geo:markerDescription>STAINLESS STEEL PLATE, THREADED SPIGOT</geo:markerDescription>
         <geo:dateInstalled>2009-01-22T13:00:00Z</geo:dateInstalled>
         <geo:geologicCharacteristic>BEDROCK</geo:geologicCharacteristic>
         <geo:bedrockType>SEDIMENTARY</geo:bedrockType>
         <geo:bedrockCondition>WEATHERED</geo:bedrockCondition>
         <geo:faultZonesNearby>NO</geo:faultZonesNearby>
      </geo:siteIdentification>
      <geo:siteLocation>
         <geo:city>Warakurna</geo:city>
         <geo:state>Western Australia</geo:state>
         <geo:countryCodeISO>AUS</geo:countryCodeISO>
         <geo:tectonicPlate codeSpace="">Australia</geo:tectonicPlate>
         <geo:approximatePositionITRF>
            <geo:xCoordinateInMeters>-3583757.167</geo:xCoordinateInMeters>
            <geo:yCoordinateInMeters>4538446.739</geo:yCoordinateInMeters>
            <geo:zCoordinateInMeters>-2683057.267</geo:zCoordinateInMeters>
            <geo:latitude-North>-25.037201875000004491766958381049335002899169921875</geo:latitude-North>
            <geo:longitude-East>128.296173711111123338923789560794830322265625</geo:longitude-East>
            <geo:elevation-m_ellips.>0587.191</geo:elevation-m_ellips.>
         </geo:approximatePositionITRF>
      </geo:siteLocation>
      <geo:gnssReceivers>
         <geo:gnssReceiver gml:id="GnssReceiverType_2796">
            <geo:manufacturerSerialNumber>356539</geo:manufacturerSerialNumber>
            <geo:receiverType codeList="codelist" codeListValue="codeListValue" codeSpace="DummyCodeSpace">LEICA GRX1200GGPRO</geo:receiverType>
            <geo:satelliteSystem>GPS+GLO</geo:satelliteSystem>
            <geo:serialNumber>356539</geo:serialNumber>
            <geo:firmwareVersion>8.10 / 3.019</geo:firmwareVersion>
            <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting>
            <geo:dateInstalled>2011-05-17T01:45:00Z</geo:dateInstalled>
            <geo:dateRemoved>2011-06-28T23:59:00Z</geo:dateRemoved>
            <geo:temperatureStabilization>0.0</geo:temperatureStabilization>
         </geo:gnssReceiver>
         <geo:dateInserted>2011-05-17T01:45:00Z</geo:dateInserted>
      </geo:gnssReceivers>
      <geo:gnssReceivers>
         <geo:gnssReceiver gml:id="GnssReceiverType_2797">
            <geo:manufacturerSerialNumber>356539</geo:manufacturerSerialNumber>
            <geo:receiverType codeList="codelist" codeListValue="codeListValue" codeSpace="DummyCodeSpace">LEICA GRX1200GGPRO</geo:receiverType>
            <geo:satelliteSystem>GPS+GLO</geo:satelliteSystem>
            <geo:serialNumber>356539</geo:serialNumber>
            <geo:firmwareVersion>8.20/3.019</geo:firmwareVersion>
            <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting>
            <geo:dateInstalled>2011-06-29T00:00:00Z</geo:dateInstalled>
            <geo:dateRemoved></geo:dateRemoved>
            <geo:temperatureStabilization>0.0</geo:temperatureStabilization>
         </geo:gnssReceiver>
         <geo:dateInserted>2011-06-29T00:00:00Z</geo:dateInserted>
      </geo:gnssReceivers>
      <geo:gnssReceivers>
         <geo:gnssReceiver gml:id="GnssReceiverType_2798">
            <geo:manufacturerSerialNumber>356539</geo:manufacturerSerialNumber>
            <geo:receiverType codeList="codelist" codeListValue="codeListValue" codeSpace="DummyCodeSpace">LEICA GRX1200GGPRO</geo:receiverType>
            <geo:satelliteSystem>GPS+GLO</geo:satelliteSystem>
            <geo:serialNumber>356539</geo:serialNumber>
            <geo:firmwareVersion>7.50</geo:firmwareVersion>
            <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting>
            <geo:dateInstalled>2010-02-16T00:00:00Z</geo:dateInstalled>
            <geo:dateRemoved>2010-05-03T04:00:00Z</geo:dateRemoved>
            <geo:temperatureStabilization>0.0</geo:temperatureStabilization>
            <geo:notes>Tracking set to P2 only</geo:notes>
         </geo:gnssReceiver>
         <geo:dateInserted>2010-02-16T00:00:00Z</geo:dateInserted>
      </geo:gnssReceivers>
      <geo:gnssReceivers>
         <geo:gnssReceiver gml:id="GnssReceiverType_2799">
            <geo:manufacturerSerialNumber>356539</geo:manufacturerSerialNumber>
            <geo:receiverType codeList="codelist" codeListValue="codeListValue" codeSpace="DummyCodeSpace">LEICA GRX1200GGPRO</geo:receiverType>
            <geo:satelliteSystem>GPS+GLO</geo:satelliteSystem>
            <geo:serialNumber>356539</geo:serialNumber>
            <geo:firmwareVersion>7.50 / 3.019</geo:firmwareVersion>
            <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting>
            <geo:dateInstalled>2010-05-03T04:00:00Z</geo:dateInstalled>
            <geo:dateRemoved>2011-05-17T01:45:00Z</geo:dateRemoved>
            <geo:temperatureStabilization>0.0</geo:temperatureStabilization>
            <geo:notes>ME upgrade due to GLONASS tracking problem</geo:notes>
         </geo:gnssReceiver>
         <geo:dateInserted>2010-05-03T04:00:00Z</geo:dateInserted>
      </geo:gnssReceivers>
      <geo:gnssReceivers>
         <geo:gnssReceiver gml:id="GnssReceiverType_2800">
            <geo:manufacturerSerialNumber>356539</geo:manufacturerSerialNumber>
            <geo:receiverType codeList="codelist" codeListValue="codeListValue" codeSpace="DummyCodeSpace">LEICA GRX1200GGPRO</geo:receiverType>
            <geo:satelliteSystem>GPS+GLO</geo:satelliteSystem>
            <geo:serialNumber>356539</geo:serialNumber>
            <geo:firmwareVersion>6.02</geo:firmwareVersion>
            <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting>
            <geo:dateInstalled>2009-05-20T00:00:00Z</geo:dateInstalled>
            <geo:dateRemoved>2010-02-15T23:59:00Z</geo:dateRemoved>
            <geo:temperatureStabilization>0.0</geo:temperatureStabilization>
         </geo:gnssReceiver>
         <geo:dateInserted>2009-05-20T00:00:00Z</geo:dateInserted>
      </geo:gnssReceivers>
      <geo:gnssAntennas>
         <geo:gnssAntenna gml:id="GnssAntennaType_1254">
            <geo:manufacturerSerialNumber>200677</geo:manufacturerSerialNumber>
            <geo:antennaType codeList="codelist" codeListValue="codeListValue" codeSpace="codespace">LEIAT504GG      SCIS</geo:antennaType>
            <geo:serialNumber>200677</geo:serialNumber>
            <geo:antennaReferencePoint codeSpace="">BPA</geo:antennaReferencePoint>
            <geo:marker-arpUpEcc.>0.0</geo:marker-arpUpEcc.>
            <geo:marker-arpNorthEcc.>0.0</geo:marker-arpNorthEcc.>
            <geo:marker-arpEastEcc.>0.0</geo:marker-arpEastEcc.>
            <geo:alignmentFromTrueNorth>0.0</geo:alignmentFromTrueNorth>
            <geo:antennaRadomeType codeSpace="CodeSpaceAttr">SCIS</geo:antennaRadomeType>
            <geo:radomeSerialNumber>NA</geo:radomeSerialNumber>
            <geo:antennaCableType>CNT400</geo:antennaCableType>
            <geo:antennaCableLength>22.0</geo:antennaCableLength>
            <geo:dateInstalled>2009-05-20T00:00:00Z</geo:dateInstalled>
            <geo:dateRemoved></geo:dateRemoved>
            <geo:notes>Additional 2 x 0.3m RG58 antenna cable extensions at antenna and receiver end</geo:notes>
         </geo:gnssAntenna>
         <geo:dateInserted>2009-05-20T00:00:00Z</geo:dateInserted>
      </geo:gnssAntennas>
      <geo:frequencyStandards>
         <geo:frequencyStandard gml:id="FrequencyStandardType_1002">
            <geo:standardType codeSpace="">QUARTZ/INTERNAL</geo:standardType>
            <geo:inputFrequency>5.0</geo:inputFrequency>
            <gml:validTime nilReason="">
               <gml:TimePeriod gml:id="TimePeriodType_1644">
                  <gml:beginPosition>2009-05-20T00:00:00Z</gml:beginPosition>
                  <gml:endPosition></gml:endPosition>
               </gml:TimePeriod>
            </gml:validTime>
         </geo:frequencyStandard>
         <geo:dateInserted>2016-04-14T00:03:13Z</geo:dateInserted>
      </geo:frequencyStandards>
      <geo:humiditySensors>
         <geo:humiditySensor gml:id="HumiditySensorType_283">
            <geo:type codeSpace="">PAROSCIENTIFIC MET4</geo:type>
            <geo:manufacturer>PAROSCIENTIFIC</geo:manufacturer>
            <geo:serialNumber>107351</geo:serialNumber>
            <geo:heightDiffToAntenna>0.0</geo:heightDiffToAntenna>
            <geo:calibrationDate></geo:calibrationDate>
            <gml:validTime nilReason="">
               <gml:TimePeriod gml:id="TimePeriodType_1645">
                  <gml:beginPosition>2009-05-20T00:00:00Z</gml:beginPosition>
                  <gml:endPosition>2012-11-05T00:00:00Z</gml:endPosition>
               </gml:TimePeriod>
            </gml:validTime>
            <geo:dataSamplingInterval>30.0</geo:dataSamplingInterval>
            <geo:accuracy-percentRelativeHumidity>2.0</geo:accuracy-percentRelativeHumidity>
            <geo:aspiration>NATURAL</geo:aspiration>
         </geo:humiditySensor>
         <geo:dateInserted>2016-04-14T00:03:13Z</geo:dateInserted>
      </geo:humiditySensors>
      <geo:humiditySensors>
         <geo:humiditySensor gml:id="HumiditySensorType_284">
            <geo:type codeSpace="">PAROSCIENTIFIC MET4</geo:type>
            <geo:manufacturer>PAROSCIENTIFIC</geo:manufacturer>
            <geo:serialNumber>110574</geo:serialNumber>
            <geo:heightDiffToAntenna>0.0</geo:heightDiffToAntenna>
            <geo:calibrationDate></geo:calibrationDate>
            <gml:validTime nilReason="">
               <gml:TimePeriod gml:id="TimePeriodType_1646">
                  <gml:beginPosition>2012-11-05T00:00:00Z</gml:beginPosition>
                  <gml:endPosition></gml:endPosition>
               </gml:TimePeriod>
            </gml:validTime>
            <geo:dataSamplingInterval>30.0</geo:dataSamplingInterval>
            <geo:accuracy-percentRelativeHumidity>2.0</geo:accuracy-percentRelativeHumidity>
            <geo:aspiration>NATURAL</geo:aspiration>
         </geo:humiditySensor>
         <geo:dateInserted>2016-04-14T00:03:13Z</geo:dateInserted>
      </geo:humiditySensors>
      <geo:pressureSensors>
         <geo:pressureSensor gml:id="PressureSensorType_289">
            <geo:type codeSpace="">PAROSCIENTIFIC MET4</geo:type>
            <geo:manufacturer>PAROSCIENTIFIC</geo:manufacturer>
            <geo:serialNumber>110574</geo:serialNumber>
            <geo:heightDiffToAntenna>0.0</geo:heightDiffToAntenna>
            <geo:calibrationDate></geo:calibrationDate>
            <gml:validTime nilReason="">
               <gml:TimePeriod gml:id="TimePeriodType_1647">
                  <gml:beginPosition>2012-11-05T00:00:00Z</gml:beginPosition>
                  <gml:endPosition></gml:endPosition>
               </gml:TimePeriod>
            </gml:validTime>
            <geo:dataSamplingInterval>30.0</geo:dataSamplingInterval>
            <geo:accuracy-hPa>0.1</geo:accuracy-hPa>
         </geo:pressureSensor>
         <geo:dateInserted>2016-04-14T00:03:13Z</geo:dateInserted>
      </geo:pressureSensors>
      <geo:pressureSensors>
         <geo:pressureSensor gml:id="PressureSensorType_290">
            <geo:type codeSpace="">PAROSCIENTIFIC MET4</geo:type>
            <geo:manufacturer>PAROSCIENTIFIC</geo:manufacturer>
            <geo:serialNumber>107351</geo:serialNumber>
            <geo:heightDiffToAntenna>0.0</geo:heightDiffToAntenna>
            <geo:calibrationDate></geo:calibrationDate>
            <gml:validTime nilReason="">
               <gml:TimePeriod gml:id="TimePeriodType_1648">
                  <gml:beginPosition>2009-05-20T00:00:00Z</gml:beginPosition>
                  <gml:endPosition>2012-11-05T00:00:00Z</gml:endPosition>
               </gml:TimePeriod>
            </gml:validTime>
            <geo:dataSamplingInterval>30.0</geo:dataSamplingInterval>
            <geo:accuracy-hPa>0.1</geo:accuracy-hPa>
         </geo:pressureSensor>
         <geo:dateInserted>2016-04-14T00:03:13Z</geo:dateInserted>
      </geo:pressureSensors>
      <geo:temperatureSensors>
         <geo:temperatureSensor gml:id="TemperatureSensorType_280">
            <geo:type codeSpace="">PAROSCIENTIFIC MET4</geo:type>
            <geo:manufacturer>PAROSCIENTIFIC</geo:manufacturer>
            <geo:serialNumber>107351</geo:serialNumber>
            <geo:heightDiffToAntenna>0.0</geo:heightDiffToAntenna>
            <geo:calibrationDate></geo:calibrationDate>
            <gml:validTime nilReason="">
               <gml:TimePeriod gml:id="TimePeriodType_1649">
                  <gml:beginPosition>2009-05-20T00:00:00Z</gml:beginPosition>
                  <gml:endPosition>2012-11-05T00:00:00Z</gml:endPosition>
               </gml:TimePeriod>
            </gml:validTime>
            <geo:dataSamplingInterval>30.0</geo:dataSamplingInterval>
            <geo:accuracy-degreesCelcius>0.5</geo:accuracy-degreesCelcius>
            <geo:aspiration>NATURAL</geo:aspiration>
         </geo:temperatureSensor>
         <geo:dateInserted>2016-04-14T00:03:13Z</geo:dateInserted>
      </geo:temperatureSensors>
      <geo:temperatureSensors>
         <geo:temperatureSensor gml:id="TemperatureSensorType_281">
            <geo:type codeSpace="">PAROSCIENTIFIC MET4</geo:type>
            <geo:manufacturer>PAROSCIENTIFIC</geo:manufacturer>
            <geo:serialNumber>110574</geo:serialNumber>
            <geo:heightDiffToAntenna>0.0</geo:heightDiffToAntenna>
            <geo:calibrationDate></geo:calibrationDate>
            <gml:validTime nilReason="">
               <gml:TimePeriod gml:id="TimePeriodType_1650">
                  <gml:beginPosition>2012-11-05T00:00:00Z</gml:beginPosition>
                  <gml:endPosition></gml:endPosition>
               </gml:TimePeriod>
            </gml:validTime>
            <geo:dataSamplingInterval>30.0</geo:dataSamplingInterval>
            <geo:accuracy-degreesCelcius>0.5</geo:accuracy-degreesCelcius>
            <geo:aspiration>NATURAL</geo:aspiration>
         </geo:temperatureSensor>
         <geo:dateInserted>2016-04-14T00:03:13Z</geo:dateInserted>
      </geo:temperatureSensors>
      <geo:siteContact gml:id="AgencyPropertyType_1240">
         <gmd:MD_SecurityConstraints id="MDSecurityConstraintsType_1240">
            <gmd:classification>
               <gmd:MD_ClassificationCode codeList="codelist" codeListValue="codeListValue"/>
            </gmd:classification>
         </gmd:MD_SecurityConstraints>
         <gmd:CI_ResponsibleParty id="CIResponsiblePartyType_1240">
            <gmd:organisationName>
               <gco:CharacterString>Geoscience Australia</gco:CharacterString>
            </gmd:organisationName>
            <gmd:contactInfo>
               <gmd:CI_Contact id="CIContactType_1240">
                  <gmd:address>
                     <gmd:CI_Address id="CIAddressType_1240"/>
                  </gmd:address>
               </gmd:CI_Contact>
            </gmd:contactInfo>
            <gmd:role>
               <gmd:CI_RoleCode codeList="codelist" codeListValue="codeListValue"/>
            </gmd:role>
         </gmd:CI_ResponsibleParty>
      </geo:siteContact>
      <geo:siteMetadataCustodian gml:id="AgencyPropertyType_1241">
         <gmd:MD_SecurityConstraints id="MDSecurityConstraintsType_1241">
            <gmd:classification>
               <gmd:MD_ClassificationCode codeList="codelist" codeListValue="codeListValue"/>
            </gmd:classification>
         </gmd:MD_SecurityConstraints>
         <gmd:CI_ResponsibleParty id="CIResponsiblePartyType_1241">
            <gmd:organisationName>
               <gco:CharacterString>Geoscience Australia</gco:CharacterString>
            </gmd:organisationName>
            <gmd:contactInfo>
               <gmd:CI_Contact id="CIContactType_1241">
                  <gmd:address>
                     <gmd:CI_Address id="CIAddressType_1241">
                        <gmd:deliveryPoint>
                           <gco:CharacterString>Geoscience Australia</gco:CharacterString>
                        </gmd:deliveryPoint>
                     </gmd:CI_Address>
                  </gmd:address>
               </gmd:CI_Contact>
            </gmd:contactInfo>
            <gmd:role>
               <gmd:CI_RoleCode codeList="codelist" codeListValue="codeListValue"/>
            </gmd:role>
         </gmd:CI_ResponsibleParty>
      </geo:siteMetadataCustodian>
      <geo:moreInformation>
         <geo:dataCenter></geo:dataCenter>
         <geo:urlForMoreInformation></geo:urlForMoreInformation>
         <geo:siteMap></geo:siteMap>
         <geo:siteDiagram>X</geo:siteDiagram>
         <geo:horizonMask>X</geo:horizonMask>
         <geo:monumentDescription></geo:monumentDescription>
         <geo:sitePictures>Y</geo:sitePictures>
         <geo:antennaGraphicsWithDimensions></geo:antennaGraphicsWithDimensions>
         <geo:insertTextGraphicFromAntenna></geo:insertTextGraphicFromAntenna>
         <geo:DOI codeSpace="CodeSpaceTODO">CodeTypeTODO</geo:DOI>
      </geo:moreInformation>
   </geo:siteLog>
</geo:GeodesyML>


text:
from __future__ import annotations

from datetime import timedelta
from typing import (
    TYPE_CHECKING,
    cast,
)

import numpy as np

from pandas._libs import (
    lib,
    tslibs,
)
from pandas._libs.tslibs import (
    BaseOffset,
    NaT,
    NaTType,
    Tick,
    Timedelta,
    astype_overflowsafe,
    iNaT,
    periods_per_second,
    to_offset,
)
from pandas._libs.tslibs.conversion import precision_from_unit
from pandas._libs.tslibs.fields import get_timedelta_field
from pandas._libs.tslibs.timedeltas import (
    array_to_timedelta64,
    ints_to_pytimedelta,
    parse_timedelta_unit,
)
from pandas._typing import (
    DtypeObj,
    NpDtype,
    npt,
)
from pandas.compat.numpy import function as nv
from pandas.util._validators import validate_endpoints

from pandas.core.dtypes.astype import astype_td64_unit_conversion
from pandas.core.dtypes.common import (
    TD64NS_DTYPE,
    is_dtype_equal,
    is_float_dtype,
    is_integer_dtype,
    is_object_dtype,
    is_scalar,
    is_string_dtype,
    is_timedelta64_dtype,
    pandas_dtype,
)
from pandas.core.dtypes.missing import isna

from pandas.core import nanops
from pandas.core.arrays import datetimelike as dtl
from pandas.core.arrays._ranges import generate_regular_range
import pandas.core.common as com
from pandas.core.ops.common import unpack_zerodim_and_defer

if TYPE_CHECKING:
    from pandas import DataFrame

def _field_accessor(name: str, alias: str, docstring: str):
    def f(self) -> np.ndarray:
        values = self.asi8
        result = get_timedelta_field(values, alias, reso=self._reso)
        if self._hasna:
            result = self._maybe_mask_results(
                result, fill_value=None, convert="float64"
            )

        return result

    f.__name__ = name
    f.__doc__ = f"\n{docstring}\n"
    return property(f)

class TimedeltaArray(dtl.TimelikeOps):
    """
    Pandas ExtensionArray for timedelta data.

    .. warning::

       TimedeltaArray is currently experimental, and its API may change
       without warning. In particular, :attr:`TimedeltaArray.dtype` is
       expected to change to be an instance of an ``ExtensionDtype``
       subclass.

    Parameters
    ----------
    values : array-like
        The timedelta data.

    dtype : numpy.dtype
        Currently, only ``numpy.dtype("timedelta64[ns]")`` is accepted.
    freq : Offset, optional
    copy : bool, default False
        Whether to copy the underlying array of data.

    Attributes
    ----------
    None

    Methods
    -------
    None
    """

    _typ = "timedeltaarray"
    _internal_fill_value = np.timedelta64("NaT", "ns")
    _recognized_scalars = (timedelta, np.timedelta64, Tick)
    _is_recognized_dtype = is_timedelta64_dtype
    _infer_matches = ("timedelta", "timedelta64")

    @property
    def _scalar_type(self) -> type[Timedelta]:
        return Timedelta

    __array_priority__ = 1000
    # define my properties & methods for delegation
    _other_ops: list[str] = []
    _bool_ops: list[str] = []
    _object_ops: list[str] = ["freq"]
    _field_ops: list[str] = ["days", "seconds", "microseconds", "nanoseconds"]
    _datetimelike_ops: list[str] = _field_ops + _object_ops + _bool_ops
    _datetimelike_methods: list[str] = [
        "to_pytimedelta",
        "total_seconds",
        "round",
        "floor",
        "ceil",
    ]

    # Note: ndim must be defined to ensure NaT.__richcmp__(TimedeltaArray)
    #  operates pointwise.

    def _box_func(self, x: np.timedelta64) -> Timedelta | NaTType:
        y = x.view("i8")
        if y == NaT.value:
            return NaT
        return Timedelta._from_value_and_reso(y, reso=self._reso)

    @property
    # error: Return type "dtype" of "dtype" incompatible with return type
    # "ExtensionDtype" in supertype "ExtensionArray"
    def dtype(self) -> np.dtype:  # type: ignore[override]
        """
        The dtype for the TimedeltaArray.

        .. warning::

           A future version of pandas will change dtype to be an instance
           of a :class:`pandas.api.extensions.ExtensionDtype` subclass,
           not a ``numpy.dtype``.

        Returns
        -------
        numpy.dtype
        """
        return self._ndarray.dtype

    # ----------------------------------------------------------------
    # Constructors

    _freq = None
    _default_dtype = TD64NS_DTYPE  # used in TimeLikeOps.__init__

    @classmethod
    def _validate_dtype(cls, values, dtype):
        # used in TimeLikeOps.__init__
        _validate_td64_dtype(values.dtype)
        dtype = _validate_td64_dtype(dtype)
        return dtype

    # error: Signature of "_simple_new" incompatible with supertype "NDArrayBacked"
    @classmethod
    def _simple_new(  # type: ignore[override]
        cls, values: np.ndarray, freq: BaseOffset | None = None, dtype=TD64NS_DTYPE
    ) -> TimedeltaArray:
        # Require td64 dtype, not unit-less, matching values.dtype
        assert isinstance(dtype, np.dtype) and dtype.kind == "m"
        assert not tslibs.is_unitless(dtype)
        assert isinstance(values, np.ndarray), type(values)
        assert dtype == values.dtype

        result = super()._simple_new(values=values, dtype=dtype)
        result._freq = freq
        return result

    @classmethod
    def _from_sequence(
        cls, data, *, dtype=TD64NS_DTYPE, copy: bool = False
    ) -> TimedeltaArray:
        if dtype:
            _validate_td64_dtype(dtype)

        data, inferred_freq = sequence_to_td64ns(data, copy=copy, unit=None)
        freq, _ = dtl.validate_inferred_freq(None, inferred_freq, False)

        return cls._simple_new(data, dtype=data.dtype, freq=freq)

    @classmethod
    def _from_sequence_not_strict(
        cls,
        data,
        dtype=TD64NS_DTYPE,
        copy: bool = False,
        freq=lib.no_default,
        unit=None,
    ) -> TimedeltaArray:
        if dtype:
            _validate_td64_dtype(dtype)

        assert unit not in ["Y", "y", "M"]  # caller is responsible for checking

        explicit_none = freq is None
        freq = freq if freq is not lib.no_default else None

        freq, freq_infer = dtl.maybe_infer_freq(freq)

        data, inferred_freq = sequence_to_td64ns(data, copy=copy, unit=unit)
        freq, freq_infer = dtl.validate_inferred_freq(freq, inferred_freq, freq_infer)
        if explicit_none:
            freq = None

        result = cls._simple_new(data, dtype=data.dtype, freq=freq)

        if inferred_freq is None and freq is not None:
            # this condition precludes `freq_infer`
            cls._validate_frequency(result, freq)

        elif freq_infer:
            # Set _freq directly to bypass duplicative _validate_frequency
            # check.
            result._freq = to_offset(result.inferred_freq)

        return result

    @classmethod
    def _generate_range(cls, start, end, periods, freq, closed=None):

        periods = dtl.validate_periods(periods)
        if freq is None and any(x is None for x in [periods, start, end]):
            raise ValueError("Must provide freq argument if no data is supplied")

        if com.count_not_none(start, end, periods, freq) != 3:
            raise ValueError(
                "Of the four parameters: start, end, periods, "
                "and freq, exactly three must be specified"
            )

        if start is not None:
            start = Timedelta(start)

        if end is not None:
            end = Timedelta(end)

        left_closed, right_closed = validate_endpoints(closed)

        if freq is not None:
            index = generate_regular_range(start, end, periods, freq)
        else:
            index = np.linspace(start.value, end.value, periods).astype("i8")

        if not left_closed:
            index = index[1:]
        if not right_closed:
            index = index[:-1]

        td64values = index.view("m8[ns]")
        return cls._simple_new(td64values, dtype=td64values.dtype, freq=freq)

    # ----------------------------------------------------------------
    # DatetimeLike Interface

    def _unbox_scalar(self, value, setitem: bool = False) -> np.timedelta64:
        if not isinstance(value, self._scalar_type) and value is not NaT:
            raise ValueError("'value' should be a Timedelta.")
        self._check_compatible_with(value, setitem=setitem)
        return np.timedelta64(value.value, "ns")

    def _scalar_from_string(self, value) -> Timedelta | NaTType:
        return Timedelta(value)

    def _check_compatible_with(self, other, setitem: bool = False) -> None:
        # we don't have anything to validate.
        pass

    # ----------------------------------------------------------------
    # Array-Like / EA-Interface Methods

    def astype(self, dtype, copy: bool = True):
        # We handle
        #   --> timedelta64[ns]
        #   --> timedelta64
        # DatetimeLikeArrayMixin super call handles other cases
        dtype = pandas_dtype(dtype)

        if dtype.kind == "m":
            return astype_td64_unit_conversion(self._ndarray, dtype, copy=copy)

        return dtl.DatetimeLikeArrayMixin.astype(self, dtype, copy=copy)

    def __iter__(self):
        if self.ndim > 1:
            for i in range(len(self)):
                yield self[i]
        else:
            # convert in chunks of 10k for efficiency
            data = self._ndarray
            length = len(self)
            chunksize = 10000
            chunks = (length // chunksize) + 1
            for i in range(chunks):
                start_i = i * chunksize
                end_i = min((i + 1) * chunksize, length)
                converted = ints_to_pytimedelta(data[start_i:end_i], box=True)
                yield from converted

    # ----------------------------------------------------------------
    # Reductions

    def sum(
        self,
        *,
        axis: int | None = None,
        dtype: NpDtype | None = None,
        out=None,
        keepdims: bool = False,
        initial=None,
        skipna: bool = True,
        min_count: int = 0,
    ):
        nv.validate_sum(
            (), {"dtype": dtype, "out": out, "keepdims": keepdims, "initial": initial}
        )

        result = nanops.nansum(
            self._ndarray, axis=axis, skipna=skipna, min_count=min_count
        )
        return self._wrap_reduction_result(axis, result)

    def std(
        self,
        *,
        axis: int | None = None,
        dtype: NpDtype | None = None,
        out=None,
        ddof: int = 1,
        keepdims: bool = False,
        skipna: bool = True,
    ):
        nv.validate_stat_ddof_func(
            (), {"dtype": dtype, "out": out, "keepdims": keepdims}, fname="std"
        )

        result = nanops.nanstd(self._ndarray, axis=axis, skipna=skipna, ddof=ddof)
        if axis is None or self.ndim == 1:
            return self._box_func(result)
        return self._from_backing_data(result)

    # ----------------------------------------------------------------
    # Rendering Methods

    def _formatter(self, boxed: bool = False):
        from pandas.io.formats.format import get_format_timedelta64

        return get_format_timedelta64(self, box=True)

    def _format_native_types(
        self, *, na_rep="NaT", date_format=None, **kwargs
    ) -> npt.NDArray[np.object_]:
        from pandas.io.formats.format import get_format_timedelta64

        # Relies on TimeDelta._repr_base
        formatter = get_format_timedelta64(self._ndarray, na_rep)
        # equiv: np.array([formatter(x) for x in self._ndarray])
        #  but independent of dimension
        return np.frompyfunc(formatter, 1, 1)(self._ndarray)

    # ----------------------------------------------------------------
    # Arithmetic Methods

    def _add_offset(self, other):
        assert not isinstance(other, Tick)
        raise TypeError(
            f"cannot add the type {type(other).__name__} to a {type(self).__name__}"
        )

    @unpack_zerodim_and_defer("__mul__")
    def __mul__(self, other) -> TimedeltaArray:
        if is_scalar(other):
            # numpy will accept float and int, raise TypeError for others
            result = self._ndarray * other
            freq = None
            if self.freq is not None and not isna(other):
                freq = self.freq * other
            return type(self)._simple_new(result, dtype=result.dtype, freq=freq)

        if not hasattr(other, "dtype"):
            # list, tuple
            other = np.array(other)
        if len(other) != len(self) and not is_timedelta64_dtype(other.dtype):
            # Exclude timedelta64 here so we correctly raise TypeError
            #  for that instead of ValueError
            raise ValueError("Cannot multiply with unequal lengths")

        if is_object_dtype(other.dtype):
            # this multiplication will succeed only if all elements of other
            #  are int or float scalars, so we will end up with
            #  timedelta64[ns]-dtyped result
            arr = self._ndarray
            result = [arr[n] * other[n] for n in range(len(self))]
            result = np.array(result)
            return type(self)._simple_new(result, dtype=result.dtype)

        # numpy will accept float or int dtype, raise TypeError for others
        result = self._ndarray * other
        return type(self)._simple_new(result, dtype=result.dtype)

    __rmul__ = __mul__

    @unpack_zerodim_and_defer("__truediv__")
    def __truediv__(self, other):
        # timedelta / X is well-defined for timedelta-like or numeric X

        if isinstance(other, self._recognized_scalars):
            other = Timedelta(other)
            # mypy assumes that __new__ returns an instance of the class
            # github.com/python/mypy/issues/1020
            if cast("Timedelta | NaTType", other) is NaT:
                # specifically timedelta64-NaT
                result = np.empty(self.shape, dtype=np.float64)
                result.fill(np.nan)
                return result

            # otherwise, dispatch to Timedelta implementation
            return self._ndarray / other

        elif lib.is_scalar(other):
            # assume it is numeric
            result = self._ndarray / other
            freq = None
            if self.freq is not None:
                # Tick division is not implemented, so operate on Timedelta
                freq = self.freq.delta / other
                freq = to_offset(freq)
            return type(self)._simple_new(result, dtype=result.dtype, freq=freq)

        if not hasattr(other, "dtype"):
            # e.g. list, tuple
            other = np.array(other)

        if len(other) != len(self):
            raise ValueError("Cannot divide vectors with unequal lengths")

        elif is_timedelta64_dtype(other.dtype):
            # let numpy handle it
            return self._ndarray / other

        elif is_object_dtype(other.dtype):
            # We operate on raveled arrays to avoid problems in inference
            #  on NaT
            # TODO: tests with non-nano
            srav = self.ravel()
            orav = other.ravel()
            result_list = [srav[n] / orav[n] for n in range(len(srav))]
            result = np.array(result_list).reshape(self.shape)

            # We need to do dtype inference in order to keep DataFrame ops
            #  behavior consistent with Series behavior
            inferred = lib.infer_dtype(result, skipna=False)
            if inferred == "timedelta":
                flat = result.ravel()
                result = type(self)._from_sequence(flat).reshape(result.shape)
            elif inferred == "floating":
                result = result.astype(float)
            elif inferred == "datetime":
                # GH#39750 this occurs when result is all-NaT, in which case
                #  we want to interpret these NaTs as td64.
                #  We construct an all-td64NaT result.
                # error: Incompatible types in assignment (expression has type
                # "TimedeltaArray", variable has type "ndarray[Any,
                # dtype[floating[_64Bit]]]")
                result = self * np.nan  # type: ignore[assignment]

            return result

        else:
            result = self._ndarray / other
            return type(self)._simple_new(result, dtype=result.dtype)

    @unpack_zerodim_and_defer("__rtruediv__")
    def __rtruediv__(self, other):
        # X / timedelta is defined only for timedelta-like X
        if isinstance(other, self._recognized_scalars):
            other = Timedelta(other)
            # mypy assumes that __new__ returns an instance of the class
            # github.com/python/mypy/issues/1020
            if cast("Timedelta | NaTType", other) is NaT:
                # specifically timedelta64-NaT
                result = np.empty(self.shape, dtype=np.float64)
                result.fill(np.nan)
                return result

            # otherwise, dispatch to Timedelta implementation
            return other / self._ndarray

        elif lib.is_scalar(other):
            raise TypeError(
                f"Cannot divide {type(other).__name__} by {type(self).__name__}"
            )

        if not hasattr(other, "dtype"):
            # e.g. list, tuple
            other = np.array(other)

        if len(other) != len(self):
            raise ValueError("Cannot divide vectors with unequal lengths")

        elif is_timedelta64_dtype(other.dtype):
            # let numpy handle it
            return other / self._ndarray

        elif is_object_dtype(other.dtype):
            # Note: unlike in __truediv__, we do not _need_ to do type
            #  inference on the result.  It does not raise, a numeric array
            #  is returned.  GH#23829
            result_list = [other[n] / self[n] for n in range(len(self))]
            return np.array(result_list)

        else:
            raise TypeError(
                f"Cannot divide {other.dtype} data by {type(self).__name__}"
            )

    @unpack_zerodim_and_defer("__floordiv__")
    def __floordiv__(self, other):

        if is_scalar(other):
            if isinstance(other, self._recognized_scalars):
                other = Timedelta(other)
                # mypy assumes that __new__ returns an instance of the class
                # github.com/python/mypy/issues/1020
                if cast("Timedelta | NaTType", other) is NaT:
                    # treat this specifically as timedelta-NaT
                    result = np.empty(self.shape, dtype=np.float64)
                    result.fill(np.nan)
                    return result

                # dispatch to Timedelta implementation
                return other.__rfloordiv__(self._ndarray)

            # at this point we should only have numeric scalars; anything
            #  else will raise
            result = self._ndarray // other
            freq = None
            if self.freq is not None:
                # Note: freq gets division, not floor-division
                freq = self.freq / other
                if freq.nanos == 0 and self.freq.nanos != 0:
                    # e.g. if self.freq is Nano(1) then dividing by 2
                    #  rounds down to zero
                    freq = None
            return type(self)(result, freq=freq)

        if not hasattr(other, "dtype"):
            # list, tuple
            other = np.array(other)
        if len(other) != len(self):
            raise ValueError("Cannot divide with unequal lengths")

        elif is_timedelta64_dtype(other.dtype):
            other = type(self)(other)

            # numpy timedelta64 does not natively support floordiv, so operate
            #  on the i8 values
            result = self.asi8 // other.asi8
            mask = self._isnan | other._isnan
            if mask.any():
                result = result.astype(np.float64)
                np.putmask(result, mask, np.nan)
            return result

        elif is_object_dtype(other.dtype):
            # error: Incompatible types in assignment (expression has type
            # "List[Any]", variable has type "ndarray")
            srav = self.ravel()
            orav = other.ravel()
            res_list = [srav[n] // orav[n] for n in range(len(srav))]
            result_flat = np.asarray(res_list)
            inferred = lib.infer_dtype(result_flat, skipna=False)

            result = result_flat.reshape(self.shape)

            if inferred == "timedelta":
                result, _ = sequence_to_td64ns(result)
                return type(self)(result)
            if inferred == "datetime":
                # GH#39750 occurs when result is all-NaT, which in this
                #  case should be interpreted as td64nat. This can only
                #  occur when self is all-td64nat
                return self * np.nan
            return result

        elif is_integer_dtype(other.dtype) or is_float_dtype(other.dtype):
            result = self._ndarray // other
            return type(self)(result)

        else:
            dtype = getattr(other, "dtype", type(other).__name__)
            raise TypeError(f"Cannot divide {dtype} by {type(self).__name__}")

    @unpack_zerodim_and_defer("__rfloordiv__")
    def __rfloordiv__(self, other):

        if is_scalar(other):
            if isinstance(other, self._recognized_scalars):
                other = Timedelta(other)
                # mypy assumes that __new__ returns an instance of the class
                # github.com/python/mypy/issues/1020
                if cast("Timedelta | NaTType", other) is NaT:
                    # treat this specifically as timedelta-NaT
                    result = np.empty(self.shape, dtype=np.float64)
                    result.fill(np.nan)
                    return result

                # dispatch to Timedelta implementation
                return other.__floordiv__(self._ndarray)

            raise TypeError(
                f"Cannot divide {type(other).__name__} by {type(self).__name__}"
            )

        if not hasattr(other, "dtype"):
            # list, tuple
            other = np.array(other)

        if len(other) != len(self):
            raise ValueError("Cannot divide with unequal lengths")

        elif is_timedelta64_dtype(other.dtype):
            other = type(self)(other)
            # numpy timedelta64 does not natively support floordiv, so operate
            #  on the i8 values
            result = other.asi8 // self.asi8
            mask = self._isnan | other._isnan
            if mask.any():
                result = result.astype(np.float64)
                np.putmask(result, mask, np.nan)
            return result

        elif is_object_dtype(other.dtype):
            result_list = [other[n] // self[n] for n in range(len(self))]
            result = np.array(result_list)
            return result

        else:
            dtype = getattr(other, "dtype", type(other).__name__)
            raise TypeError(f"Cannot divide {dtype} by {type(self).__name__}")

    @unpack_zerodim_and_defer("__mod__")
    def __mod__(self, other):
        # Note: This is a naive implementation, can likely be optimized
        if isinstance(other, self._recognized_scalars):
            other = Timedelta(other)
        return self - (self // other) * other

    @unpack_zerodim_and_defer("__rmod__")
    def __rmod__(self, other):
        # Note: This is a naive implementation, can likely be optimized
        if isinstance(other, self._recognized_scalars):
            other = Timedelta(other)
        return other - (other // self) * self

    @unpack_zerodim_and_defer("__divmod__")
    def __divmod__(self, other):
        # Note: This is a naive implementation, can likely be optimized
        if isinstance(other, self._recognized_scalars):
            other = Timedelta(other)

        res1 = self // other
        res2 = self - res1 * other
        return res1, res2

    @unpack_zerodim_and_defer("__rdivmod__")
    def __rdivmod__(self, other):
        # Note: This is a naive implementation, can likely be optimized
        if isinstance(other, self._recognized_scalars):
            other = Timedelta(other)

        res1 = other // self
        res2 = other - res1 * self
        return res1, res2

    def __neg__(self) -> TimedeltaArray:
        if self.freq is not None:
            return type(self)(-self._ndarray, freq=-self.freq)
        return type(self)(-self._ndarray)

    def __pos__(self) -> TimedeltaArray:
        return type(self)(self._ndarray.copy(), freq=self.freq)

    def __abs__(self) -> TimedeltaArray:
        # Note: freq is not preserved
        return type(self)(np.abs(self._ndarray))

    # ----------------------------------------------------------------
    # Conversion Methods - Vectorized analogues of Timedelta methods

    def total_seconds(self) -> npt.NDArray[np.float64]:
        """
        Return total duration of each element expressed in seconds.

        This method is available directly on TimedeltaArray, TimedeltaIndex
        and on Series containing timedelta values under the ``.dt`` namespace.

        Returns
        -------
        seconds : [ndarray, Float64Index, Series]
            When the calling object is a TimedeltaArray, the return type
            is ndarray.  When the calling object is a TimedeltaIndex,
            the return type is a Float64Index. When the calling object
            is a Series, the return type is Series of type `float64` whose
            index is the same as the original.

        See Also
        --------
        datetime.timedelta.total_seconds : Standard library version
            of this method.
        TimedeltaIndex.components : Return a DataFrame with components of
            each Timedelta.

        Examples
        --------
        **Series**

        >>> s = pd.Series(pd.to_timedelta(np.arange(5), unit='d'))
        >>> s
        0   0 days
        1   1 days
        2   2 days
        3   3 days
        4   4 days
        dtype: timedelta64[ns]

        >>> s.dt.total_seconds()
        0         0.0
        1     86400.0
        2    172800.0
        3    259200.0
        4    345600.0
        dtype: float64

        **TimedeltaIndex**

        >>> idx = pd.to_timedelta(np.arange(5), unit='d')
        >>> idx
        TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],
                       dtype='timedelta64[ns]', freq=None)

        >>> idx.total_seconds()
        Float64Index([0.0, 86400.0, 172800.0, 259200.0, 345600.0],
                     dtype='float64')
        """
        pps = periods_per_second(self._reso)
        return self._maybe_mask_results(self.asi8 / pps, fill_value=None)

    def to_pytimedelta(self) -> npt.NDArray[np.object_]:
        """
        Return an ndarray of datetime.timedelta objects.

        Returns
        -------
        timedeltas : ndarray[object]
        """
        return ints_to_pytimedelta(self._ndarray)

    days = _field_accessor("days", "days", "Number of days for each element.")
    seconds = _field_accessor(
        "seconds",
        "seconds",
        "Number of seconds (>= 0 and less than 1 day) for each element.",
    )
    microseconds = _field_accessor(
        "microseconds",
        "microseconds",
        "Number of microseconds (>= 0 and less than 1 second) for each element.",
    )
    nanoseconds = _field_accessor(
        "nanoseconds",
        "nanoseconds",
        "Number of nanoseconds (>= 0 and less than 1 microsecond) for each element.",
    )

    @property
    def components(self) -> DataFrame:
        """
        Return a DataFrame of the individual resolution components of the Timedeltas.

        The components (days, hours, minutes seconds, milliseconds, microseconds,
        nanoseconds) are returned as columns in a DataFrame.

        Returns
        -------
        DataFrame
        """
        from pandas import DataFrame

        columns = [
            "days",
            "hours",
            "minutes",
            "seconds",
            "milliseconds",
            "microseconds",
            "nanoseconds",
        ]
        hasnans = self._hasna
        if hasnans:

            def f(x):
                if isna(x):
                    return [np.nan] * len(columns)
                return x.components

        else:

            def f(x):
                return x.components

        result = DataFrame([f(x) for x in self], columns=columns)
        if not hasnans:
            result = result.astype("int64")
        return result

# ---------------------------------------------------------------------
# Constructor Helpers

def sequence_to_td64ns(
    data, copy: bool = False, unit=None, errors="raise"
) -> tuple[np.ndarray, Tick | None]:
    """
    Parameters
    ----------
    data : list-like
    copy : bool, default False
    unit : str, optional
        The timedelta unit to treat integers as multiples of. For numeric
        data this defaults to ``'ns'``.
        Must be un-specified if the data contains a str and ``errors=="raise"``.
    errors : {"raise", "coerce", "ignore"}, default "raise"
        How to handle elements that cannot be converted to timedelta64[ns].
        See ``pandas.to_timedelta`` for details.

    Returns
    -------
    converted : numpy.ndarray
        The sequence converted to a numpy array with dtype ``timedelta64[ns]``.
    inferred_freq : Tick or None
        The inferred frequency of the sequence.

    Raises
    ------
    ValueError : Data cannot be converted to timedelta64[ns].

    Notes
    -----
    Unlike `pandas.to_timedelta`, if setting ``errors=ignore`` will not cause
    errors to be ignored; they are caught and subsequently ignored at a
    higher level.
    """
    assert unit not in ["Y", "y", "M"]  # caller is responsible for checking

    inferred_freq = None
    if unit is not None:
        unit = parse_timedelta_unit(unit)

    data, copy = dtl.ensure_arraylike_for_datetimelike(
        data, copy, cls_name="TimedeltaArray"
    )

    if isinstance(data, TimedeltaArray):
        inferred_freq = data.freq

    # Convert whatever we have into timedelta64[ns] dtype
    if is_object_dtype(data.dtype) or is_string_dtype(data.dtype):
        # no need to make a copy, need to convert if string-dtyped
        data = _objects_to_td64ns(data, unit=unit, errors=errors)
        copy = False

    elif is_integer_dtype(data.dtype):
        # treat as multiples of the given unit
        data, copy_made = ints_to_td64ns(data, unit=unit)
        copy = copy and not copy_made

    elif is_float_dtype(data.dtype):
        # cast the unit, multiply base/frac separately
        # to avoid precision issues from float -> int
        mask = np.isnan(data)
        # The next few lines are effectively a vectorized 'cast_from_unit'
        m, p = precision_from_unit(unit or "ns")
        base = data.astype(np.int64)
        frac = data - base
        if p:
            frac = np.round(frac, p)
        data = (base * m + (frac * m).astype(np.int64)).view("timedelta64[ns]")
        data[mask] = iNaT
        copy = False

    elif is_timedelta64_dtype(data.dtype):
        if data.dtype != TD64NS_DTYPE:
            # non-nano unit
            data = astype_overflowsafe(data, dtype=TD64NS_DTYPE)
            copy = False

    else:
        # This includes datetime64-dtype, see GH#23539, GH#29794
        raise TypeError(f"dtype {data.dtype} cannot be converted to timedelta64[ns]")

    data = np.array(data, copy=copy)

    assert data.dtype == "m8[ns]", data
    return data, inferred_freq

def ints_to_td64ns(data, unit="ns"):
    """
    Convert an ndarray with integer-dtype to timedelta64[ns] dtype, treating
    the integers as multiples of the given timedelta unit.

    Parameters
    ----------
    data : numpy.ndarray with integer-dtype
    unit : str, default "ns"
        The timedelta unit to treat integers as multiples of.

    Returns
    -------
    numpy.ndarray : timedelta64[ns] array converted from data
    bool : whether a copy was made
    """
    copy_made = False
    unit = unit if unit is not None else "ns"

    if data.dtype != np.int64:
        # converting to int64 makes a copy, so we can avoid
        # re-copying later
        data = data.astype(np.int64)
        copy_made = True

    if unit != "ns":
        dtype_str = f"timedelta64[{unit}]"
        data = data.view(dtype_str)

        data = astype_overflowsafe(data, dtype=TD64NS_DTYPE)

        # the astype conversion makes a copy, so we can avoid re-copying later
        copy_made = True

    else:
        data = data.view("timedelta64[ns]")

    return data, copy_made

def _objects_to_td64ns(data, unit=None, errors="raise"):
    """
    Convert a object-dtyped or string-dtyped array into an
    timedelta64[ns]-dtyped array.

    Parameters
    ----------
    data : ndarray or Index
    unit : str, default "ns"
        The timedelta unit to treat integers as multiples of.
        Must not be specified if the data contains a str.
    errors : {"raise", "coerce", "ignore"}, default "raise"
        How to handle elements that cannot be converted to timedelta64[ns].
        See ``pandas.to_timedelta`` for details.

    Returns
    -------
    numpy.ndarray : timedelta64[ns] array converted from data

    Raises
    ------
    ValueError : Data cannot be converted to timedelta64[ns].

    Notes
    -----
    Unlike `pandas.to_timedelta`, if setting `errors=ignore` will not cause
    errors to be ignored; they are caught and subsequently ignored at a
    higher level.
    """
    # coerce Index to np.ndarray, converting string-dtype if necessary
    values = np.array(data, dtype=np.object_, copy=False)

    result = array_to_timedelta64(values, unit=unit, errors=errors)
    return result.view("timedelta64[ns]")

def _validate_td64_dtype(dtype) -> DtypeObj:
    dtype = pandas_dtype(dtype)
    if is_dtype_equal(dtype, np.dtype("timedelta64")):
        # no precision disallowed GH#24806
        msg = (
            "Passing in 'timedelta' dtype with no precision is not allowed. "
            "Please pass in 'timedelta64[ns]' instead."
        )
        raise ValueError(msg)

    if not is_dtype_equal(dtype, TD64NS_DTYPE):
        raise ValueError(f"dtype {dtype} cannot be converted to timedelta64[ns]")

    return dtype


text:
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="./bwt-datatable-column.html">
<link rel="import" href="./bwt-datatable-edit-dialog.html">
<link rel="import" href="./datatable-icons.html">

<link rel="import" href="../paper-checkbox/paper-checkbox.html">
<link rel="import" href="../paper-tooltip/paper-tooltip.html">
<link rel="import" href="../paper-progress/paper-progress.html">
<link rel="import" href="../iron-media-query/iron-media-query.html">
<link rel="import" href="../iron-scroll-target-behavior/iron-scroll-target-behavior.html">

<link rel="import" href="./src/weakCache.html">
<link rel="import" href="./src/collectionHelpers.html">

<dom-module id="paper-datatable">
	<template>
		<custom-style>

		</custom-style>
		<iron-media-query query="(max-width: [[responseWidth]])" query-matches="{{mobileView}}"></iron-media-query>
		<paper-datatable-edit-dialog id="dialog"></paper-datatable-edit-dialog>

						<template is="dom-if" if="[[selectable]]">

								<template is="dom-if" if="[[multiSelection]]">

										<paper-checkbox on-change="toggleAll" checked$="[[_allChecked(selectedKeys.splices, data.*)]]" style="position:absolute;left:0px;top:0px;"></paper-checkbox>

								</template>

						</template>
						<template id="columnRepeat" is="dom-repeat" items="[[_columns]]" as="column" on-dom-change="_columnsRendered">

								<iron-icon icon="datatable:sort-desc-md" class="sort"></iron-icon>
								[[column.header]]
								<template is="dom-if" if="[[column.tooltip]]">
									<paper-tooltip offset="-10" fit-to-visible-bounds>[[column.tooltip]]</paper-tooltip>
								</template>

						</template>

							<paper-progress indeterminate></paper-progress>

							<slot name="no-results"></slot>

					<template id="rowRepeat" is="dom-repeat" items="[[_rowKeys]]" as="rowKey" on-dom-change="_restructureData">

						<template is="dom-if" if="[[multiSelection]]">

								<template is="dom-if" if="[[selectable]]">

											<paper-checkbox checked$="[[_isRowSelected(rowKey, selectedKeys.splices)]]" on-change="_setSelection"></paper-checkbox>

								</template>
								<template id="cellRepeat" is="dom-repeat" items="[[_columns]]" as="column" on-dom-change="_restructureData">

											<iron-icon icon="datatable:editable" class="editable"></iron-icon>

								</template>

						</template>
						<template is="dom-if" if="[[!multiSelection]]">

								<template is="dom-if" if="[[selectable]]">

										<paper-checkbox checked="[[_isRowSelected(rowKey, selectedKey)]]" on-change="_setSelection"></paper-checkbox>

								</template>
								<template id="cellRepeat" is="dom-repeat" items="[[_columns]]" as="column" on-dom-change="_restructureData">

											<iron-icon icon="datatable:editable" class="editable"></iron-icon>

								</template>

						</template>
					</template>

	</template>

</dom-module>