prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>AggressorAI.cpp<|end_file_name|><|fim▁begin|>/* * This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "AggressorAI.h" #include "Errors.h" #include "Creature.h" #include "SharedDefines.h" #include "VMapFactory.h" #include "World.h" #include "DBCStores.h" #include "Map.h" #include <list> int AggressorAI::Permissible(const Creature* creature) { // have some hostile factions, it will be selected by IsHostileTo check at MoveInLineOfSight if (!(creature->GetCreatureInfo()->ExtraFlags & CREATURE_EXTRA_FLAG_NO_AGGRO) && !creature->IsNeutralToAll()) return PERMIT_BASE_PROACTIVE; return PERMIT_BASE_NO; } AggressorAI::AggressorAI(Creature* c) : CreatureAI(c), i_state(STATE_NORMAL), i_tracker(TIME_INTERVAL_LOOK) { } void AggressorAI::MoveInLineOfSight(Unit* u) { // Ignore Z for flying creatures if (!m_creature->CanFly() && m_creature->GetDistanceZ(u) > CREATURE_Z_ATTACK_RANGE) return; if (m_creature->CanInitiateAttack() && u->isTargetableForAttack() && m_creature->IsHostileTo(u) && u->isInAccessablePlaceFor(m_creature)) { float attackRadius = m_creature->GetAttackDistance(u); if (m_creature->IsWithinDistInMap(u, attackRadius) && m_creature->IsWithinLOSInMap(u)) { if (!m_creature->getVictim()) { AttackStart(u); u->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH); } else if (sMapStore.LookupEntry(m_creature->GetMapId())->IsDungeon()) { m_creature->AddThreat(u); u->SetInCombatWith(m_creature); } } } } void AggressorAI::EnterEvadeMode() { if (!m_creature->isAlive()) { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, he is dead [guid=%u]", m_creature->GetGUIDLow()); i_victimGuid.Clear(); m_creature->CombatStop(true); m_creature->DeleteThreatList(); return; } Unit* victim = m_creature->GetMap()->GetUnit(i_victimGuid); if (!victim) { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, no victim [guid=%u]", m_creature->GetGUIDLow()); } else if (!victim->isAlive()) { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, victim is dead [guid=%u]", m_creature->GetGUIDLow()); } else if (victim->HasStealthAura()) { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, victim is in stealth [guid=%u]", m_creature->GetGUIDLow()); } else if (victim->IsTaxiFlying()) { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, victim is in flight [guid=%u]", m_creature->GetGUIDLow()); } else { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, victim out run him [guid=%u]", m_creature->GetGUIDLow()); // i_state = STATE_LOOK_AT_VICTIM; // i_tracker.Reset(TIME_INTERVAL_LOOK); } if (!m_creature->isCharmed()) { m_creature->RemoveAllAurasOnEvade(); // Remove ChaseMovementGenerator from MotionMaster stack list, and add HomeMovementGenerator instead if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == CHASE_MOTION_TYPE) m_creature->GetMotionMaster()->MoveTargetedHome(); } m_creature->DeleteThreatList(); i_victimGuid.Clear(); m_creature->CombatStop(true); m_creature->SetLootRecipient(nullptr); } <|fim▁hole|> // update i_victimGuid if m_creature->getVictim() !=0 and changed if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; i_victimGuid = m_creature->getVictim()->GetObjectGuid(); DoMeleeAttackIfReady(); } bool AggressorAI::IsVisible(Unit* pl) const { return m_creature->IsWithinDist(pl, sWorld.getConfig(CONFIG_FLOAT_SIGHT_MONSTER)) && pl->isVisibleForOrDetect(m_creature, m_creature, true); } void AggressorAI::AttackStart(Unit* u) { if (!u) return; if (m_creature->Attack(u, true)) { i_victimGuid = u->GetObjectGuid(); m_creature->AddThreat(u); m_creature->SetInCombatWith(u); u->SetInCombatWith(m_creature); HandleMovementOnAttackStart(u); } }<|fim▁end|>
void AggressorAI::UpdateAI(const uint32 /*diff*/) {
<|file_name|>RunTransformTim.java<|end_file_name|><|fim▁begin|>package fortesting; import java.io.IOException;<|fim▁hole|> /** * Loads data into appropriate tables (assumes scheme already created) * * This will import the tables from my CSVs, which I have on dropbox. Let me * (Tim) know if you need the CSVs No guarantee that it works on CSVs * generated differently * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // String host = "127.0.0.1"; String host = "52.32.209.104"; // String keyspace = "new"; String keyspace = "main"; String year = "2012"; // if an error occurs during upload of first CSV, use // GetLastRow.getLastEntry() to find its // npi value and use that as start. This will not work in other CSVs // unless the last npi // added is greater than the largest npi in all previously loaded CSVs String start = ""; TransformTim t = new TransformTim(); t.injest(host, keyspace, "CSV/MedicareA2012.csv", year, start); t.injest(host, keyspace, "CSV/MedicareB2012.csv", year, ""); t.injest(host, keyspace, "CSV/MedicareC2012.csv", year, ""); t.injest(host, keyspace, "CSV/MedicareD2012.csv", year, ""); t.injest(host, keyspace, "CSV/MedicareEG2012.csv", year, ""); t.injest(host, keyspace, "CSV/MedicareHJ2012.csv", year, ""); t.injest(host, keyspace, "CSV/MedicareKL2012.csv", year, ""); t.injest(host, keyspace, "CSV/MedicareMN2012.csv", year, ""); t.injest(host, keyspace, "CSV/MedicareOQ2012.csv", year, ""); t.injest(host, keyspace, "CSV/MedicareR2012.csv", year, ""); t.injest(host, keyspace, "CSV/MedicareS2012.csv", year, ""); t.injest(host, keyspace, "CSV/MedicareTX2012.csv", year, ""); t.injest(host, keyspace, "CSV/MedicareYZ2012.csv", year, ""); } }<|fim▁end|>
public class RunTransformTim {
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for INSTEON Modems (PLM and Hub).""" import asyncio from contextlib import suppress import logging from pyinsteon import async_close, async_connect, devices from homeassistant.config_entries import SOURCE_IMPORT from homeassistant.const import CONF_PLATFORM, EVENT_HOMEASSISTANT_STOP from homeassistant.exceptions import ConfigEntryNotReady from . import api from .const import ( CONF_CAT, CONF_DIM_STEPS, CONF_HOUSECODE, CONF_OVERRIDE, CONF_SUBCAT, CONF_UNITCODE, CONF_X10, DOMAIN, INSTEON_PLATFORMS, ON_OFF_EVENTS, ) from .schemas import convert_yaml_to_config_flow from .utils import ( add_on_off_event_device, async_register_services, get_device_platforms, register_new_device_callback, ) _LOGGER = logging.getLogger(__name__) OPTIONS = "options" async def async_get_device_config(hass, config_entry): """Initiate the connection and services.""" # Make a copy of addresses due to edge case where the list of devices could change during status update # Cannot be done concurrently due to issues with the underlying protocol. for address in list(devices): if devices[address].is_battery: continue with suppress(AttributeError): await devices[address].async_status() await devices.async_load(id_devices=1) for addr in devices: device = devices[addr] flags = True for name in device.operating_flags: if not device.operating_flags[name].is_loaded: flags = False break if flags: for name in device.properties: if not device.properties[name].is_loaded: flags = False break # Cannot be done concurrently due to issues with the underlying protocol. if not device.aldb.is_loaded or not flags: await device.async_read_config() await devices.async_save(workdir=hass.config.config_dir) async def close_insteon_connection(*args): """Close the Insteon connection.""" await async_close() async def async_setup(hass, config): """Set up the Insteon platform.""" if DOMAIN not in config: return True conf = config[DOMAIN] data, options = convert_yaml_to_config_flow(conf) if options: hass.data[DOMAIN] = {} hass.data[DOMAIN][OPTIONS] = options # Create a config entry with the connection data hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=data ) ) return True async def async_setup_entry(hass, entry): """Set up an Insteon entry.""" if not devices.modem: try: await async_connect(**entry.data) except ConnectionError as exception: _LOGGER.error("Could not connect to Insteon modem") raise ConfigEntryNotReady from exception entry.async_on_unload( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, close_insteon_connection) ) await devices.async_load( workdir=hass.config.config_dir, id_devices=0, load_modem_aldb=0<|fim▁hole|> if ( not entry.options and entry.source == SOURCE_IMPORT and hass.data.get(DOMAIN) and hass.data[DOMAIN].get(OPTIONS) ): hass.config_entries.async_update_entry( entry=entry, options=hass.data[DOMAIN][OPTIONS], ) for device_override in entry.options.get(CONF_OVERRIDE, []): # Override the device default capabilities for a specific address address = device_override.get("address") if not devices.get(address): cat = device_override[CONF_CAT] subcat = device_override[CONF_SUBCAT] devices.set_id(address, cat, subcat, 0) for device in entry.options.get(CONF_X10, []): housecode = device.get(CONF_HOUSECODE) unitcode = device.get(CONF_UNITCODE) x10_type = "on_off" steps = device.get(CONF_DIM_STEPS, 22) if device.get(CONF_PLATFORM) == "light": x10_type = "dimmable" elif device.get(CONF_PLATFORM) == "binary_sensor": x10_type = "sensor" _LOGGER.debug( "Adding X10 device to Insteon: %s %d %s", housecode, unitcode, x10_type ) device = devices.add_x10_device(housecode, unitcode, x10_type, steps) for platform in INSTEON_PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, platform) ) for address in devices: device = devices[address] platforms = get_device_platforms(device) if ON_OFF_EVENTS in platforms: add_on_off_event_device(hass, device) _LOGGER.debug("Insteon device count: %s", len(devices)) register_new_device_callback(hass) async_register_services(hass) device_registry = await hass.helpers.device_registry.async_get_registry() device_registry.async_get_or_create( config_entry_id=entry.entry_id, identifiers={(DOMAIN, str(devices.modem.address))}, manufacturer="Smart Home", name=f"{devices.modem.description} {devices.modem.address}", model=f"{devices.modem.model} ({devices.modem.cat!r}, 0x{devices.modem.subcat:02x})", sw_version=f"{devices.modem.firmware:02x} Engine Version: {devices.modem.engine_version}", ) api.async_load_api(hass) asyncio.create_task(async_get_device_config(hass, entry)) return True<|fim▁end|>
) # If options existed in YAML and have not already been saved to the config entry # add them now
<|file_name|>ntp_snippets_service.cc<|end_file_name|><|fim▁begin|>// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/ntp_snippets/ntp_snippets_service.h" #include <algorithm> #include <utility> #include "base/command_line.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/location.h" #include "base/path_service.h" #include "base/strings/string_number_conversions.h" #include "base/task_runner_util.h" #include "base/time/time.h" #include "base/values.h" #include "components/ntp_snippets/pref_names.h" #include "components/ntp_snippets/switches.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/suggestions/proto/suggestions.pb.h" using suggestions::ChromeSuggestion; using suggestions::SuggestionsProfile; using suggestions::SuggestionsService; namespace ntp_snippets { namespace { const int kFetchingIntervalWifiChargingSeconds = 30 * 60; const int kFetchingIntervalWifiSeconds = 2 * 60 * 60; const int kFetchingIntervalFallbackSeconds = 24 * 60 * 60; const int kDefaultExpiryTimeMins = 24 * 60; base::TimeDelta GetFetchingInterval(const char* switch_name, int default_value_seconds) { int value_seconds = default_value_seconds; const base::CommandLine& cmdline = *base::CommandLine::ForCurrentProcess(); if (cmdline.HasSwitch(switch_name)) { std::string str = cmdline.GetSwitchValueASCII(switch_name); int switch_value_seconds = 0; if (base::StringToInt(str, &switch_value_seconds)) value_seconds = switch_value_seconds; else LOG(WARNING) << "Invalid value for switch " << switch_name; } return base::TimeDelta::FromSeconds(value_seconds); } base::TimeDelta GetFetchingIntervalWifiCharging() { return GetFetchingInterval(switches::kFetchingIntervalWifiChargingSeconds, kFetchingIntervalWifiChargingSeconds); } base::TimeDelta GetFetchingIntervalWifi() { return GetFetchingInterval(switches::kFetchingIntervalWifiSeconds, kFetchingIntervalWifiSeconds); } base::TimeDelta GetFetchingIntervalFallback() { return GetFetchingInterval(switches::kFetchingIntervalFallbackSeconds, kFetchingIntervalFallbackSeconds); } // Extracts the hosts from |suggestions| and returns them in a set. std::set<std::string> GetSuggestionsHosts( const SuggestionsProfile& suggestions) { std::set<std::string> hosts; for (int i = 0; i < suggestions.suggestions_size(); ++i) { const ChromeSuggestion& suggestion = suggestions.suggestions(i); GURL url(suggestion.url()); if (url.is_valid()) hosts.insert(url.host()); } return hosts; } const char kContentInfo[] = "contentInfo"; // Parses snippets from |list| and adds them to |snippets|. Returns true on // success, false if anything went wrong. bool AddSnippetsFromListValue(const base::ListValue& list, NTPSnippetsService::NTPSnippetStorage* snippets) { for (const base::Value* const value : list) { const base::DictionaryValue* dict = nullptr; if (!value->GetAsDictionary(&dict)) return false; const base::DictionaryValue* content = nullptr; if (!dict->GetDictionary(kContentInfo, &content)) return false; scoped_ptr<NTPSnippet> snippet = NTPSnippet::CreateFromDictionary(*content); if (!snippet) return false; snippets->push_back(std::move(snippet)); } return true; } scoped_ptr<base::ListValue> SnippetsToListValue( const NTPSnippetsService::NTPSnippetStorage& snippets) { scoped_ptr<base::ListValue> list(new base::ListValue); for (const auto& snippet : snippets) { scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue); dict->Set(kContentInfo, snippet->ToDictionary()); list->Append(std::move(dict)); } return list; } } // namespace NTPSnippetsService::NTPSnippetsService( PrefService* pref_service, SuggestionsService* suggestions_service, scoped_refptr<base::SequencedTaskRunner> file_task_runner, const std::string& application_language_code, NTPSnippetsScheduler* scheduler, scoped_ptr<NTPSnippetsFetcher> snippets_fetcher, const ParseJSONCallback& parse_json_callback) : pref_service_(pref_service), suggestions_service_(suggestions_service), file_task_runner_(file_task_runner), application_language_code_(application_language_code), scheduler_(scheduler), snippets_fetcher_(std::move(snippets_fetcher)), parse_json_callback_(parse_json_callback), weak_ptr_factory_(this) { snippets_fetcher_subscription_ = snippets_fetcher_->AddCallback(base::Bind( &NTPSnippetsService::OnSnippetsDownloaded, base::Unretained(this))); } NTPSnippetsService::~NTPSnippetsService() {} // static void NTPSnippetsService::RegisterProfilePrefs(PrefRegistrySimple* registry) { registry->RegisterListPref(prefs::kSnippets); registry->RegisterListPref(prefs::kDiscardedSnippets); registry->RegisterListPref(prefs::kSnippetHosts); } void NTPSnippetsService::Init(bool enabled) { if (enabled) { // |suggestions_service_| can be null in tests. if (suggestions_service_) { suggestions_service_subscription_ = suggestions_service_->AddCallback( base::Bind(&NTPSnippetsService::OnSuggestionsChanged, base::Unretained(this))); } // Get any existing snippets immediately from prefs. LoadDiscardedSnippetsFromPrefs(); LoadSnippetsFromPrefs(); // If we don't have any snippets yet, start a fetch. if (snippets_.empty()) FetchSnippets(); } // The scheduler only exists on Android so far, it's null on other platforms. if (!scheduler_) return; if (enabled) { scheduler_->Schedule(GetFetchingIntervalWifiCharging(), GetFetchingIntervalWifi(), GetFetchingIntervalFallback()); } else { scheduler_->Unschedule(); } } void NTPSnippetsService::Shutdown() { FOR_EACH_OBSERVER(NTPSnippetsServiceObserver, observers_, NTPSnippetsServiceShutdown()); } void NTPSnippetsService::FetchSnippets() { // |suggestions_service_| can be null in tests. if (!suggestions_service_) return; FetchSnippetsImpl(GetSuggestionsHosts( suggestions_service_->GetSuggestionsDataFromCache())); } bool NTPSnippetsService::DiscardSnippet(const GURL& url) { auto it = std::find_if(snippets_.begin(), snippets_.end(), [&url](const scoped_ptr<NTPSnippet>& snippet) { return snippet->url() == url; }); if (it == snippets_.end()) return false; discarded_snippets_.push_back(std::move(*it)); snippets_.erase(it); StoreDiscardedSnippetsToPrefs(); StoreSnippetsToPrefs(); return true; } void NTPSnippetsService::AddObserver(NTPSnippetsServiceObserver* observer) { observers_.AddObserver(observer); observer->NTPSnippetsServiceLoaded(); } void NTPSnippetsService::RemoveObserver(NTPSnippetsServiceObserver* observer) { observers_.RemoveObserver(observer); } void NTPSnippetsService::OnSuggestionsChanged( const SuggestionsProfile& suggestions) { std::set<std::string> hosts = GetSuggestionsHosts(suggestions); if (hosts == GetSnippetHostsFromPrefs()) return; // Remove existing snippets that aren't in the suggestions anymore. snippets_.erase( std::remove_if(snippets_.begin(), snippets_.end(), [&hosts](const scoped_ptr<NTPSnippet>& snippet) { return !hosts.count(snippet->url().host()); }), snippets_.end()); StoreSnippetsToPrefs(); StoreSnippetHostsToPrefs(hosts); FOR_EACH_OBSERVER(NTPSnippetsServiceObserver, observers_, NTPSnippetsServiceLoaded()); FetchSnippetsImpl(hosts); } void NTPSnippetsService::OnSnippetsDownloaded( const std::string& snippets_json) { parse_json_callback_.Run( snippets_json, base::Bind(&NTPSnippetsService::OnJsonParsed, weak_ptr_factory_.GetWeakPtr(), snippets_json), base::Bind(&NTPSnippetsService::OnJsonError, weak_ptr_factory_.GetWeakPtr(), snippets_json)); } void NTPSnippetsService::OnJsonParsed(const std::string& snippets_json, scoped_ptr<base::Value> parsed) { LOG_IF(WARNING, !LoadFromValue(*parsed)) << "Received invalid snippets: " << snippets_json; } void NTPSnippetsService::OnJsonError(const std::string& snippets_json, const std::string& error) { LOG(WARNING) << "Received invalid JSON (" << error << "): " << snippets_json; } <|fim▁hole|>void NTPSnippetsService::FetchSnippetsImpl( const std::set<std::string>& hosts) { if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDontRestrict)) { snippets_fetcher_->FetchSnippets(std::set<std::string>()); return; } if (!hosts.empty()) snippets_fetcher_->FetchSnippets(hosts); } bool NTPSnippetsService::LoadFromValue(const base::Value& value) { const base::DictionaryValue* top_dict = nullptr; if (!value.GetAsDictionary(&top_dict)) return false; const base::ListValue* list = nullptr; if (!top_dict->GetList("recos", &list)) return false; return LoadFromListValue(*list); } bool NTPSnippetsService::LoadFromListValue(const base::ListValue& list) { NTPSnippetStorage new_snippets; if (!AddSnippetsFromListValue(list, &new_snippets)) return false; for (scoped_ptr<NTPSnippet>& snippet : new_snippets) { // If this snippet has previously been discarded, don't add it again. if (HasDiscardedSnippet(snippet->url())) continue; // If the snippet has no publish/expiry dates, fill in defaults. if (snippet->publish_date().is_null()) snippet->set_publish_date(base::Time::Now()); if (snippet->expiry_date().is_null()) { snippet->set_expiry_date( snippet->publish_date() + base::TimeDelta::FromMinutes(kDefaultExpiryTimeMins)); } // Check if we already have a snippet with the same URL. If so, replace it // rather than adding a duplicate. const GURL& url = snippet->url(); auto it = std::find_if(snippets_.begin(), snippets_.end(), [&url](const scoped_ptr<NTPSnippet>& old_snippet) { return old_snippet->url() == url; }); if (it != snippets_.end()) *it = std::move(snippet); else snippets_.push_back(std::move(snippet)); } // Immediately remove any already-expired snippets. This will also notify our // observers and schedule the expiry timer. RemoveExpiredSnippets(); return true; } void NTPSnippetsService::LoadSnippetsFromPrefs() { bool success = LoadFromListValue(*pref_service_->GetList(prefs::kSnippets)); DCHECK(success) << "Failed to parse snippets from prefs"; } void NTPSnippetsService::StoreSnippetsToPrefs() { pref_service_->Set(prefs::kSnippets, *SnippetsToListValue(snippets_)); } void NTPSnippetsService::LoadDiscardedSnippetsFromPrefs() { discarded_snippets_.clear(); bool success = AddSnippetsFromListValue( *pref_service_->GetList(prefs::kDiscardedSnippets), &discarded_snippets_); DCHECK(success) << "Failed to parse discarded snippets from prefs"; } void NTPSnippetsService::StoreDiscardedSnippetsToPrefs() { pref_service_->Set(prefs::kDiscardedSnippets, *SnippetsToListValue(discarded_snippets_)); } std::set<std::string> NTPSnippetsService::GetSnippetHostsFromPrefs() const { std::set<std::string> hosts; const base::ListValue* list = pref_service_->GetList(prefs::kSnippetHosts); for (const base::Value* value : *list) { std::string str; bool success = value->GetAsString(&str); DCHECK(success) << "Failed to parse snippet host from prefs"; hosts.insert(std::move(str)); } return hosts; } void NTPSnippetsService::StoreSnippetHostsToPrefs( const std::set<std::string>& hosts) { base::ListValue list; for (const std::string& host : hosts) list.AppendString(host); pref_service_->Set(prefs::kSnippetHosts, list); } bool NTPSnippetsService::HasDiscardedSnippet(const GURL& url) const { auto it = std::find_if(discarded_snippets_.begin(), discarded_snippets_.end(), [&url](const scoped_ptr<NTPSnippet>& snippet) { return snippet->url() == url; }); return it != discarded_snippets_.end(); } void NTPSnippetsService::RemoveExpiredSnippets() { base::Time expiry = base::Time::Now(); snippets_.erase( std::remove_if(snippets_.begin(), snippets_.end(), [&expiry](const scoped_ptr<NTPSnippet>& snippet) { return snippet->expiry_date() <= expiry; }), snippets_.end()); StoreSnippetsToPrefs(); discarded_snippets_.erase( std::remove_if(discarded_snippets_.begin(), discarded_snippets_.end(), [&expiry](const scoped_ptr<NTPSnippet>& snippet) { return snippet->expiry_date() <= expiry; }), discarded_snippets_.end()); StoreDiscardedSnippetsToPrefs(); FOR_EACH_OBSERVER(NTPSnippetsServiceObserver, observers_, NTPSnippetsServiceLoaded()); // If there are any snippets left, schedule a timer for the next expiry. if (snippets_.empty() && discarded_snippets_.empty()) return; base::Time next_expiry = base::Time::Max(); for (const auto& snippet : snippets_) { if (snippet->expiry_date() < next_expiry) next_expiry = snippet->expiry_date(); } for (const auto& snippet : discarded_snippets_) { if (snippet->expiry_date() < next_expiry) next_expiry = snippet->expiry_date(); } DCHECK_GT(next_expiry, expiry); expiry_timer_.Start(FROM_HERE, next_expiry - expiry, base::Bind(&NTPSnippetsService::RemoveExpiredSnippets, base::Unretained(this))); } } // namespace ntp_snippets<|fim▁end|>
<|file_name|>test_append.py<|end_file_name|><|fim▁begin|># TODO.TXT-CLI-python test script # Copyright (C) 2011-2012 Sigmavirus24, Jeff Stein # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License<|fim▁hole|>import unittest import base import todo class AppendTest(base.BaseTest): def test_append(self): todo.cli.addm_todo("\n".join(self._test_lines_no_pri(self.num))) for i in range(1, self.num + 1): todo.cli.append_todo([str(i), "testing", "append"]) self.assertNumLines(self.num, "Test\s\d+\stesting\sappend") if __name__ == "__main__": unittest.main()<|fim▁end|>
# along with this program. If not, see <http://www.gnu.org/licenses/>. # # TLDR: This is licensed under the GPLv3. See LICENSE for more details.
<|file_name|>flex.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Layout for elements with a CSS `display` property of `flex`. #![deny(unsafe_code)] use app_units::Au; use block::BlockFlow;<|fim▁hole|>use flow; use flow::INLINE_POSITION_IS_STATIC; use flow::IS_ABSOLUTELY_POSITIONED; use flow::ImmutableFlowUtils; use flow::{Flow, FlowClass, OpaqueFlow}; use flow::{HAS_LEFT_FLOATED_DESCENDANTS, HAS_RIGHT_FLOATED_DESCENDANTS}; use fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; use gfx::display_list::{StackingContext, StackingContextId}; use incremental::{REFLOW, REFLOW_OUT_OF_FLOW}; use layout_debug; use model::MaybeAuto; use model::{IntrinsicISizes}; use std::cmp::max; use std::sync::Arc; use style::computed_values::{flex_direction, float}; use style::logical_geometry::LogicalSize; use style::properties::ComputedValues; use style::properties::style_structs; use style::values::computed::LengthOrPercentageOrAuto; // A mode describes which logical axis a flex axis is parallel with. // The logical axises are inline and block, the flex axises are main and cross. // When the flex container has flex-direction: column or flex-direction: column-reverse, the main axis // should be block. Otherwise, it should be inline. #[derive(Debug)] enum Mode { Inline, Block } /// A block with the CSS `display` property equal to `flex`. #[derive(Debug)] pub struct FlexFlow { /// Data common to all block flows. block_flow: BlockFlow, /// The logical axis which the main axis will be parallel with. /// The cross axis will be parallel with the opposite logical axis. main_mode: Mode, } fn flex_style(fragment: &Fragment) -> &style_structs::Flex { fragment.style.get_flex() } // TODO(zentner): This function should use flex-basis. fn flex_item_inline_sizes(flow: &mut Flow) -> IntrinsicISizes { let _scope = layout_debug_scope!("flex::flex_item_inline_sizes"); debug!("flex_item_inline_sizes"); let base = flow::mut_base(flow); debug!("FlexItem intrinsic inline sizes: {:?}, {:?}", base.intrinsic_inline_sizes.minimum_inline_size, base.intrinsic_inline_sizes.preferred_inline_size); IntrinsicISizes { minimum_inline_size: base.intrinsic_inline_sizes.minimum_inline_size, preferred_inline_size: base.intrinsic_inline_sizes.preferred_inline_size, } } impl FlexFlow { pub fn from_fragment(fragment: Fragment, flotation: Option<FloatKind>) -> FlexFlow { let main_mode = match flex_style(&fragment).flex_direction { flex_direction::T::row_reverse => Mode::Inline, flex_direction::T::row => Mode::Inline, flex_direction::T::column_reverse => Mode::Block, flex_direction::T::column => Mode::Block }; FlexFlow { block_flow: BlockFlow::from_fragment(fragment, flotation), main_mode: main_mode } } // TODO(zentner): This function should use flex-basis. // Currently, this is the core of BlockFlow::bubble_inline_sizes() with all float logic // stripped out, and max replaced with union_nonbreaking_inline. fn inline_mode_bubble_inline_sizes(&mut self) { let fixed_width = match self.block_flow.fragment.style().get_box().width { LengthOrPercentageOrAuto::Length(_) => true, _ => false, }; let mut computation = self.block_flow.fragment.compute_intrinsic_inline_sizes(); if !fixed_width { for kid in self.block_flow.base.child_iter() { let is_absolutely_positioned = flow::base(kid).flags.contains(IS_ABSOLUTELY_POSITIONED); if !is_absolutely_positioned { computation.union_nonbreaking_inline(&flex_item_inline_sizes(kid)); } } } self.block_flow.base.intrinsic_inline_sizes = computation.finish(); } // TODO(zentner): This function should use flex-basis. // Currently, this is the core of BlockFlow::bubble_inline_sizes() with all float logic // stripped out. fn block_mode_bubble_inline_sizes(&mut self) { let fixed_width = match self.block_flow.fragment.style().get_box().width { LengthOrPercentageOrAuto::Length(_) => true, _ => false, }; let mut computation = self.block_flow.fragment.compute_intrinsic_inline_sizes(); if !fixed_width { for kid in self.block_flow.base.child_iter() { let is_absolutely_positioned = flow::base(kid).flags.contains(IS_ABSOLUTELY_POSITIONED); let child_base = flow::mut_base(kid); if !is_absolutely_positioned { computation.content_intrinsic_sizes.minimum_inline_size = max(computation.content_intrinsic_sizes.minimum_inline_size, child_base.intrinsic_inline_sizes.minimum_inline_size); computation.content_intrinsic_sizes.preferred_inline_size = max(computation.content_intrinsic_sizes.preferred_inline_size, child_base.intrinsic_inline_sizes.preferred_inline_size); } } } self.block_flow.base.intrinsic_inline_sizes = computation.finish(); } // TODO(zentner): This function needs to be radically different for multi-line flexbox. // Currently, this is the core of BlockFlow::propagate_assigned_inline_size_to_children() with // all float and table logic stripped out. fn block_mode_assign_inline_sizes(&mut self, _layout_context: &LayoutContext, inline_start_content_edge: Au, inline_end_content_edge: Au, content_inline_size: Au) { let _scope = layout_debug_scope!("flex::block_mode_assign_inline_sizes"); debug!("block_mode_assign_inline_sizes"); // Calculate non-auto block size to pass to children. let content_block_size = self.block_flow.fragment.style().content_block_size(); let explicit_content_size = match (content_block_size, self.block_flow.base.block_container_explicit_block_size) { (LengthOrPercentageOrAuto::Percentage(percent), Some(container_size)) => { Some(container_size.scale_by(percent)) } (LengthOrPercentageOrAuto::Percentage(_), None) | (LengthOrPercentageOrAuto::Auto, _) => None, (LengthOrPercentageOrAuto::Calc(_), _) => None, (LengthOrPercentageOrAuto::Length(length), _) => Some(length), }; // FIXME (mbrubeck): Get correct mode for absolute containing block let containing_block_mode = self.block_flow.base.writing_mode; let mut iterator = self.block_flow.base.child_iter().enumerate().peekable(); while let Some((_, kid)) = iterator.next() { { let kid_base = flow::mut_base(kid); kid_base.block_container_explicit_block_size = explicit_content_size; } // The inline-start margin edge of the child flow is at our inline-start content edge, // and its inline-size is our content inline-size. let kid_mode = flow::base(kid).writing_mode; { let kid_base = flow::mut_base(kid); if kid_base.flags.contains(INLINE_POSITION_IS_STATIC) { kid_base.position.start.i = if kid_mode.is_bidi_ltr() == containing_block_mode.is_bidi_ltr() { inline_start_content_edge } else { // The kid's inline 'start' is at the parent's 'end' inline_end_content_edge }; } kid_base.block_container_inline_size = content_inline_size; kid_base.block_container_writing_mode = containing_block_mode; } } } // TODO(zentner): This function should actually flex elements! // Currently, this is the core of InlineFlow::propagate_assigned_inline_size_to_children() with // fragment logic stripped out. fn inline_mode_assign_inline_sizes(&mut self, _layout_context: &LayoutContext, inline_start_content_edge: Au, _inline_end_content_edge: Au, content_inline_size: Au) { let _scope = layout_debug_scope!("flex::inline_mode_assign_inline_sizes"); debug!("inline_mode_assign_inline_sizes"); debug!("content_inline_size = {:?}", content_inline_size); let child_count = ImmutableFlowUtils::child_count(self as &Flow) as i32; debug!("child_count = {:?}", child_count); if child_count == 0 { return; } let even_content_inline_size = content_inline_size / child_count; let inline_size = self.block_flow.base.block_container_inline_size; let container_mode = self.block_flow.base.block_container_writing_mode; self.block_flow.base.position.size.inline = inline_size; let block_container_explicit_block_size = self.block_flow.base.block_container_explicit_block_size; let mut inline_child_start = inline_start_content_edge; for kid in self.block_flow.base.child_iter() { let kid_base = flow::mut_base(kid); kid_base.block_container_inline_size = even_content_inline_size; kid_base.block_container_writing_mode = container_mode; kid_base.block_container_explicit_block_size = block_container_explicit_block_size; kid_base.position.start.i = inline_child_start; inline_child_start = inline_child_start + even_content_inline_size; } } // TODO(zentner): This function should actually flex elements! fn block_mode_assign_block_size<'a>(&mut self, layout_context: &'a LayoutContext<'a>) { self.block_flow.assign_block_size(layout_context) } // TODO(zentner): This function should actually flex elements! // Currently, this is the core of TableRowFlow::assign_block_size() with // float related logic stripped out. fn inline_mode_assign_block_size<'a>(&mut self, layout_context: &'a LayoutContext<'a>) { let _scope = layout_debug_scope!("flex::inline_mode_assign_block_size"); let mut max_block_size = Au(0); let thread_id = self.block_flow.base.thread_id; for kid in self.block_flow.base.child_iter() { kid.assign_block_size_for_inorder_child_if_necessary(layout_context, thread_id); { let child_fragment = &mut kid.as_mut_block().fragment; // TODO: Percentage block-size let child_specified_block_size = MaybeAuto::from_style(child_fragment.style().content_block_size(), Au(0)).specified_or_zero(); max_block_size = max(max_block_size, child_specified_block_size + child_fragment.border_padding.block_start_end()); } let child_node = flow::mut_base(kid); child_node.position.start.b = Au(0); max_block_size = max(max_block_size, child_node.position.size.block); } let mut block_size = max_block_size; // TODO: Percentage block-size block_size = match MaybeAuto::from_style(self.block_flow .fragment .style() .content_block_size(), Au(0)) { MaybeAuto::Auto => block_size, MaybeAuto::Specified(value) => max(value, block_size), }; // Assign the block-size of own fragment let mut position = self.block_flow.fragment.border_box; position.size.block = block_size; self.block_flow.fragment.border_box = position; self.block_flow.base.position.size.block = block_size; // Assign the block-size of kid fragments, which is the same value as own block-size. for kid in self.block_flow.base.child_iter() { { let kid_fragment = &mut kid.as_mut_block().fragment; let mut position = kid_fragment.border_box; position.size.block = block_size; kid_fragment.border_box = position; } // Assign the child's block size. flow::mut_base(kid).position.size.block = block_size } } } impl Flow for FlexFlow { fn class(&self) -> FlowClass { FlowClass::Flex } fn as_mut_block(&mut self) -> &mut BlockFlow { &mut self.block_flow } fn mark_as_root(&mut self) { self.block_flow.mark_as_root(); } fn bubble_inline_sizes(&mut self) { let _scope = layout_debug_scope!("flex::bubble_inline_sizes {:x}", self.block_flow.base.debug_id()); // Flexbox Section 9.0: Generate anonymous flex items: // This part was handled in the flow constructor. // Flexbox Section 9.1: Re-order the flex items (and any absolutely positioned flex // container children) according to their order. // TODO(zentner): We need to re-order the items at some point. However, all the operations // here ignore order, so we can afford to do it later, if necessary. // `flex item`s (our children) cannot be floated. Furthermore, they all establish BFC's. // Therefore, we do not have to handle any floats here. let mut flags = self.block_flow.base.flags; flags.remove(HAS_LEFT_FLOATED_DESCENDANTS); flags.remove(HAS_RIGHT_FLOATED_DESCENDANTS); match self.main_mode { Mode::Inline => self.inline_mode_bubble_inline_sizes(), Mode::Block => self.block_mode_bubble_inline_sizes() } // Although our children can't be floated, we can. match self.block_flow.fragment.style().get_box().float { float::T::none => {} float::T::left => flags.insert(HAS_LEFT_FLOATED_DESCENDANTS), float::T::right => flags.insert(HAS_RIGHT_FLOATED_DESCENDANTS), } self.block_flow.base.flags = flags } fn assign_inline_sizes(&mut self, layout_context: &LayoutContext) { let _scope = layout_debug_scope!("flex::assign_inline_sizes {:x}", self.block_flow.base.debug_id()); debug!("assign_inline_sizes"); if !self.block_flow.base.restyle_damage.intersects(REFLOW_OUT_OF_FLOW | REFLOW) { return } // Our inline-size was set to the inline-size of the containing block by the flow's parent. // Now compute the real value. let containing_block_inline_size = self.block_flow.base.block_container_inline_size; self.block_flow.compute_used_inline_size(layout_context, containing_block_inline_size); if self.block_flow.base.flags.is_float() { self.block_flow.float.as_mut().unwrap().containing_inline_size = containing_block_inline_size } // Move in from the inline-start border edge. let inline_start_content_edge = self.block_flow.fragment.border_box.start.i + self.block_flow.fragment.border_padding.inline_start; debug!("inline_start_content_edge = {:?}", inline_start_content_edge); let padding_and_borders = self.block_flow.fragment.border_padding.inline_start_end(); // Distance from the inline-end margin edge to the inline-end content edge. let inline_end_content_edge = self.block_flow.fragment.margin.inline_end + self.block_flow.fragment.border_padding.inline_end; debug!("padding_and_borders = {:?}", padding_and_borders); debug!("self.block_flow.fragment.border_box.size.inline = {:?}", self.block_flow.fragment.border_box.size.inline); let content_inline_size = self.block_flow.fragment.border_box.size.inline - padding_and_borders; match self.main_mode { Mode::Inline => self.inline_mode_assign_inline_sizes(layout_context, inline_start_content_edge, inline_end_content_edge, content_inline_size), Mode::Block => self.block_mode_assign_inline_sizes(layout_context, inline_start_content_edge, inline_end_content_edge, content_inline_size) } } fn assign_block_size<'a>(&mut self, layout_context: &'a LayoutContext<'a>) { self.block_flow.assign_block_size(layout_context); match self.main_mode { Mode::Inline => self.inline_mode_assign_block_size(layout_context), Mode::Block => self.block_mode_assign_block_size(layout_context) } } fn compute_absolute_position(&mut self, layout_context: &LayoutContext) { self.block_flow.compute_absolute_position(layout_context) } fn place_float_if_applicable<'a>(&mut self, layout_context: &'a LayoutContext<'a>) { self.block_flow.place_float_if_applicable(layout_context) } fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) { self.block_flow.update_late_computed_inline_position_if_necessary(inline_position) } fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) { self.block_flow.update_late_computed_block_position_if_necessary(block_position) } fn build_display_list(&mut self, state: &mut DisplayListBuildState) { self.build_display_list_for_flex(state); } fn collect_stacking_contexts(&mut self, parent_id: StackingContextId, contexts: &mut Vec<Box<StackingContext>>) -> StackingContextId { self.block_flow.collect_stacking_contexts(parent_id, contexts) } fn repair_style(&mut self, new_style: &Arc<ComputedValues>) { self.block_flow.repair_style(new_style) } fn compute_overflow(&self) -> Overflow { self.block_flow.compute_overflow() } fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> { self.block_flow.generated_containing_block_size(flow) } fn iterate_through_fragment_border_boxes(&self, iterator: &mut FragmentBorderBoxIterator, level: i32, stacking_context_position: &Point2D<Au>) { self.block_flow.iterate_through_fragment_border_boxes(iterator, level, stacking_context_position); } fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) { self.block_flow.mutate_fragments(mutator); } }<|fim▁end|>
use context::LayoutContext; use display_list_builder::{DisplayListBuildState, FlexFlowDisplayListBuilding}; use euclid::Point2D; use floats::FloatKind;
<|file_name|>friend.go<|end_file_name|><|fim▁begin|>package personal import ( "encoding/xml" "fmt" ) type FriendsArray []Friend func (self FriendsArray) String() (s string) { s = "[" i := 0 m := len(self) for _, f := range self { t := fmt.Sprintf( `{"expertise":"%s", "name":"%s", "userid":%d, "gender":%d, "portrait" : "%s"}`, f.Expertise, f.Name, f.UserId, f.Gender, f.Portrait) s += t if i != m-1 { s += "," } i++ } s += "]" return } type FriendsList struct { XMLName xml.Name `xml:"oschina"` Friends Friends `xml:"friends"` }<|fim▁hole|>} func (self FriendsList) StringFriendsArray() (s string) { return self.Friends.FriendsArray.String() } type Friend struct { Expertise string `xml:"expertise"` Name string `xml:"name"` UserId int `xml:"userid"` Gender int `xml:"gender"` //1-man|2-lady Portrait string `xml:"portrait"` } func (self Friend) String() (s string) { json, _ := xml.Marshal(&self) s = string(json) return }<|fim▁end|>
type Friends struct { FriendsArray FriendsArray `xml:"friend"`
<|file_name|>checks.py<|end_file_name|><|fim▁begin|>import os from home.models import ReplicaSet, WhatTorrent, WhatFulltext def run_checks(): errors = [] warnings = [] # Check WhatFulltext integrity def check_whatfulltext(): w_torrents = dict((w.id, w) for w in WhatTorrent.objects.defer('torrent_file').all()) w_fulltext = dict((w.id, w) for w in WhatFulltext.objects.all()) for id, w_t in w_torrents.items(): if id not in w_fulltext: errors.append(u'{0} does not have a matching fulltext entry.'.format(w_t)) elif not w_fulltext[id].match(w_t): errors.append(u'{0} does not match info with fulltext entry.'.format(w_t)) for id, w_f in w_fulltext.items(): if id not in w_torrents: errors.append(u'{0} does not have a matching whattorrent entry.'.format(w_f)) check_whatfulltext() <|fim▁hole|> for instance in replica_set.transinstance_set.all(): i_m_torrents = instance.get_m_torrents_by_hash() i_t_torrents = instance.get_t_torrents_by_hash(['id', 'hashString']) for hash, m_torrent in i_m_torrents.items(): # Check if this torrent is already in another instance if hash in m_torrents: warnings.append(u'{0} is already in another instance of ' u'the same replica set: {1}' .format(m_torrent, m_torrents[hash].instance)) # Check if the instance has the torrent if hash not in i_t_torrents: errors.append(u'{0} is in DB, but not in Transmission at instance {1}' .format(m_torrent, instance)) m_torrents[hash] = m_torrent # Check for the presence of metafiles if the instance is a master if replica_set.is_master: files_in_dir = os.listdir(m_torrent.path) if not any('.torrent' in f for f in files_in_dir): errors.append(u'Missing .torrent file for {0} at {1}' .format(m_torrent, instance)) if not any('ReleaseInfo2.txt' == f for f in files_in_dir): errors.append(u'Missing ReleaseInfo2.txt for {0} at {1}' .format(m_torrent, instance)) for hash, t_torrent in i_t_torrents.items(): # Check if the database has the torrent if hash not in i_m_torrents: errors.append(u'{0} is in Transmission, but not in DB at instance {1}' .format(t_torrent, instance)) return { 'errors': errors, 'warnings': warnings }<|fim▁end|>
for replica_set in ReplicaSet.objects.all(): m_torrents = {}
<|file_name|>events.rs<|end_file_name|><|fim▁begin|>use std::sync::mpsc::{Sender, Receiver, channel}; use std::iter::Iterator; use std::error::Error; use error; use frame::events::{ServerEvent as FrameServerEvent, SimpleServerEvent as FrameSimpleServerEvent, SchemaChange as FrameSchemaChange}; use frame::parser::parse_frame; use compression::Compression; use transport::CDRSTransport; /// Full Server Event which includes all details about occured change. pub type ServerEvent = FrameServerEvent; /// Simplified Server event. It should be used to represent an event /// which consumer wants listen to. pub type SimpleServerEvent = FrameSimpleServerEvent; /// Reexport of `FrameSchemaChange`. pub type SchemaChange = FrameSchemaChange; /// Factory function which returns a `Listener` and related `EventStream.` /// /// `Listener` provides only one function `start` to start listening. It /// blocks a thread so should be moved into a separate one to no release /// main thread. /// /// `EventStream` is an iterator which returns new events once they come. /// It is similar to `Receiver::iter`. pub fn new_listener<X>(transport: X) -> (Listener<X>, EventStream) { let (tx, rx) = channel(); let listener = Listener { transport: transport, tx: tx, }; let stream = EventStream { rx: rx }; (listener, stream) } /// `Listener` provides only one function `start` to start listening. It /// blocks a thread so should be moved into a separate one to no release /// main thread. pub struct Listener<X> { transport: X,<|fim▁hole|> impl<X: CDRSTransport> Listener<X> { /// It starts a process of listening to new events. Locks a frame. pub fn start(&mut self, compressor: &Compression) -> error::Result<()> { loop { let event_opt = try!(parse_frame(&mut self.transport, compressor)) .get_body()? .into_server_event(); let event = if event_opt.is_some() { // unwrap is safe is we've checked that event_opt.is_some() event_opt.unwrap().event as ServerEvent } else { continue; }; match self.tx.send(event) { Err(err) => return Err(error::Error::General(err.description().to_string())), _ => continue, } } } } /// `EventStream` is an iterator which returns new events once they come. /// It is similar to `Receiver::iter`. pub struct EventStream { rx: Receiver<ServerEvent>, } impl Iterator for EventStream { type Item = ServerEvent; fn next(&mut self) -> Option<Self::Item> { self.rx.recv().ok() } }<|fim▁end|>
tx: Sender<ServerEvent>, }
<|file_name|>main.js<|end_file_name|><|fim▁begin|>// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue'; import BootstrapVue from 'bootstrap-vue'; import 'bootstrap-vue/dist/bootstrap-vue.css'; import 'bootstrap/dist/css/bootstrap.css'; import { mapActions } from 'vuex'; import App from './App'; import websock from './websock'; import * as mtype from './store/mutation-types'; import store from './store'; Vue.config.productionTip = false; Vue.use(BootstrapVue); /* eslint-disable no-new */<|fim▁hole|> el: '#app', template: '<App/>', store, components: { App }, created() { websock.connect(message => this.newMessage(message)); setInterval(() => { store.commit(mtype.UPDATE_CALLS_DUR); }, 1000); }, methods: mapActions(['newMessage']), });<|fim▁end|>
new Vue({
<|file_name|>test_event_recurrence.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.exceptions import UserError import pytz from datetime import datetime, date from dateutil.relativedelta import relativedelta from odoo.tests.common import TransactionCase class TestRecurrentEvents(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() lang = cls.env['res.lang']._lang_get(cls.env.user.lang) lang.week_start = '1' # Monday def assertEventDates(self, events, dates): events = events.sorted('start') self.assertEqual(len(events), len(dates), "Wrong number of events in the recurrence") self.assertTrue(all(events.mapped('active')), "All events should be active") for event, dates in zip(events, dates): start, stop = dates self.assertEqual(event.start, start) self.assertEqual(event.stop, stop) class TestCreateRecurrentEvents(TestRecurrentEvents): @classmethod def setUpClass(cls): super().setUpClass() cls.event = cls.env['calendar.event'].create({ 'name': 'Recurrent Event', 'start': datetime(2019, 10, 21, 8, 0), 'stop': datetime(2019, 10, 23, 18, 0), 'recurrency': True, }) def test_weekly_count(self): """ Every week, on Tuesdays, for 3 occurences """ detached_events = self.event._apply_recurrence_values({ 'rrule_type': 'weekly', 'tue': True, 'interval': 1, 'count': 3, 'event_tz': 'UTC', }) self.assertEqual(detached_events, self.event, "It should be detached from the recurrence") self.assertFalse(self.event.recurrence_id, "It should be detached from the recurrence") recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)]) events = recurrence.calendar_event_ids self.assertEqual(len(events), 3, "It should have 3 events in the recurrence") self.assertEventDates(events, [ (datetime(2019, 10, 22, 8, 0), datetime(2019, 10, 24, 18, 0)), (datetime(2019, 10, 29, 8, 0), datetime(2019, 10, 31, 18, 0)), (datetime(2019, 11, 5, 8, 0), datetime(2019, 11, 7, 18, 0)), ]) def test_weekly_interval_2(self): self.event._apply_recurrence_values({ 'interval': 2, 'rrule_type': 'weekly', 'tue': True, 'count': 2, 'event_tz': 'UTC', }) recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)]) events = recurrence.calendar_event_ids self.assertEventDates(events, [ (datetime(2019, 10, 22, 8, 0), datetime(2019, 10, 24, 18, 0)), (datetime(2019, 11, 5, 8, 0), datetime(2019, 11, 7, 18, 0)), ]) def test_weekly_interval_2_week_start_sunday(self): lang = self.env['res.lang']._lang_get(self.env.user.lang) lang.week_start = '7' # Sunday self.event._apply_recurrence_values({ 'interval': 2, 'rrule_type': 'weekly', 'tue': True, 'count': 2, 'event_tz': 'UTC', }) recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)]) events = recurrence.calendar_event_ids self.assertEventDates(events, [ (datetime(2019, 10, 22, 8, 0), datetime(2019, 10, 24, 18, 0)), (datetime(2019, 11, 5, 8, 0), datetime(2019, 11, 7, 18, 0)), ]) lang.week_start = '1' # Monday def test_weekly_until(self): self.event._apply_recurrence_values({ 'rrule_type': 'weekly', 'tue': True, 'interval': 2, 'end_type': 'end_date', 'until': datetime(2019, 11, 15), 'event_tz': 'UTC', }) recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)]) events = recurrence.calendar_event_ids self.assertEqual(len(events), 2, "It should have 2 events in the recurrence") self.assertEventDates(events, [ (datetime(2019, 10, 22, 8, 0), datetime(2019, 10, 24, 18, 0)), (datetime(2019, 11, 5, 8, 0), datetime(2019, 11, 7, 18, 0)), ]) def test_monthly_count_by_date(self): self.event._apply_recurrence_values({ 'rrule_type': 'monthly', 'interval': 2, 'month_by': 'date', 'day': 27, 'end_type': 'count', 'count': 3, 'event_tz': 'UTC', }) recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)]) events = recurrence.calendar_event_ids self.assertEqual(len(events), 3, "It should have 3 events in the recurrence") self.assertEventDates(events, [ (datetime(2019, 10, 27, 8, 0), datetime(2019, 10, 29, 18, 0)), (datetime(2019, 12, 27, 8, 0), datetime(2019, 12, 29, 18, 0)), (datetime(2020, 2, 27, 8, 0), datetime(2020, 2, 29, 18, 0)), ]) def test_monthly_count_by_date_31(self): self.event._apply_recurrence_values({ 'rrule_type': 'monthly', 'interval': 1, 'month_by': 'date', 'day': 31, 'end_type': 'count', 'count': 3, 'event_tz': 'UTC', }) recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)]) events = recurrence.calendar_event_ids self.assertEqual(len(events), 3, "It should have 3 events in the recurrence") self.assertEventDates(events, [ (datetime(2019, 10, 31, 8, 0), datetime(2019, 11, 2, 18, 0)), # Missing 31th in November (datetime(2019, 12, 31, 8, 0), datetime(2020, 1, 2, 18, 0)), (datetime(2020, 1, 31, 8, 0), datetime(2020, 2, 2, 18, 0)), ]) def test_monthly_until_by_day(self): """ Every 2 months, on the third Tuesday, until 27th March 2020 """ self.event.start = datetime(2019, 10, 1, 8, 0) self.event.stop = datetime(2019, 10, 3, 18, 0) self.event._apply_recurrence_values({ 'rrule_type': 'monthly', 'interval': 2, 'month_by': 'day', 'byday': '3', 'weekday': 'TUE', 'end_type': 'end_date', 'until': date(2020, 3, 27), 'event_tz': 'UTC', }) recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)]) events = recurrence.calendar_event_ids self.assertEqual(len(events), 3, "It should have 3 events in the recurrence") self.assertEventDates(events, [ (datetime(2019, 10, 15, 8, 0), datetime(2019, 10, 17, 18, 0)), (datetime(2019, 12, 17, 8, 0), datetime(2019, 12, 19, 18, 0)), (datetime(2020, 2, 18, 8, 0), datetime(2020, 2, 20, 18, 0)), ]) def test_monthly_until_by_day_last(self): """ Every 2 months, on the last Wednesday, until 15th January 2020 """ self.event._apply_recurrence_values({ 'interval': 2, 'rrule_type': 'monthly', 'month_by': 'day', 'weekday': 'WED', 'byday': '-1', 'end_type': 'end_date', 'until': date(2020, 1, 15), 'event_tz': 'UTC', }) recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)]) events = recurrence.calendar_event_ids self.assertEqual(len(events), 2, "It should have 3 events in the recurrence") self.assertEventDates(events, [ (datetime(2019, 10, 30, 8, 0), datetime(2019, 11, 1, 18, 0)), (datetime(2019, 12, 25, 8, 0), datetime(2019, 12, 27, 18, 0)), ]) def test_yearly_count(self): self.event._apply_recurrence_values({ 'interval': 2, 'rrule_type': 'yearly', 'count': 2, 'event_tz': 'UTC', }) events = self.event.recurrence_id.calendar_event_ids self.assertEqual(len(events), 2, "It should have 3 events in the recurrence") self.assertEventDates(events, [ (self.event.start, self.event.stop), (self.event.start + relativedelta(years=2), self.event.stop + relativedelta(years=2)), ]) def test_dst_timezone(self): """ Test hours stays the same, regardless of DST changes """ self.event.start = datetime(2002, 10, 28, 10, 0) self.event.stop = datetime(2002, 10, 28, 12, 0) self.event._apply_recurrence_values({ 'interval': 2, 'rrule_type': 'weekly', 'mon': True, 'count': '2', 'event_tz': 'US/Eastern', # DST change on 2002/10/27 }) recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)]) self.assertEventDates(recurrence.calendar_event_ids, [ (datetime(2002, 10, 28, 10, 0), datetime(2002, 10, 28, 12, 0)), (datetime(2002, 11, 11, 10, 0), datetime(2002, 11, 11, 12, 0)), ]) def test_ambiguous_dst_time_winter(self): """ Test hours stays the same, regardless of DST changes """ eastern = pytz.timezone('US/Eastern') dt = eastern.localize(datetime(2002, 10, 20, 1, 30, 00)).astimezone(pytz.utc).replace(tzinfo=None) # Next occurence happens at 1:30am on 27th Oct 2002 which happened twice in the US/Eastern # timezone when the clocks where put back at the end of Daylight Saving Time self.event.start = dt self.event.stop = dt + relativedelta(hours=1) self.event._apply_recurrence_values({ 'interval': 1, 'rrule_type': 'weekly', 'sun': True, 'count': '2', 'event_tz': 'US/Eastern' # DST change on 2002/4/7 }) events = self.event.recurrence_id.calendar_event_ids self.assertEqual(events.mapped('duration'), [1, 1]) self.assertEventDates(events, [ (datetime(2002, 10, 20, 5, 30), datetime(2002, 10, 20, 6, 30)), (datetime(2002, 10, 27, 6, 30), datetime(2002, 10, 27, 7, 30)), ]) def test_ambiguous_dst_time_spring(self): """ Test hours stays the same, regardless of DST changes """ eastern = pytz.timezone('US/Eastern') dt = eastern.localize(datetime(2002, 3, 31, 2, 30, 00)).astimezone(pytz.utc).replace(tzinfo=None) # Next occurence happens 2:30am on 7th April 2002 which never happened at all in the # US/Eastern timezone, as the clocks where put forward at 2:00am skipping the entire hour self.event.start = dt self.event.stop = dt + relativedelta(hours=1) self.event._apply_recurrence_values({ 'interval': 1, 'rrule_type': 'weekly', 'sun': True, 'count': '2', 'event_tz': 'US/Eastern' # DST change on 2002/4/7 }) events = self.event.recurrence_id.calendar_event_ids self.assertEqual(events.mapped('duration'), [1, 1]) # The event begins at "the same time" (i.e. 2h30 after midnight), but that day, 2h30 after midnight happens to be at 3:30 am self.assertEventDates(events, [ (datetime(2002, 3, 31, 7, 30), datetime(2002, 3, 31, 8, 30)), (datetime(2002, 4, 7, 7, 30), datetime(2002, 4, 7, 8, 30)), ]) def test_ambiguous_full_day(self): """ Test date stays the same, regardless of DST changes """ self.event.write({ 'start': datetime(2020, 3, 23, 0, 0), 'stop': datetime(2020, 3, 23, 23, 59), }) self.event.allday = True self.event._apply_recurrence_values({ 'interval': 1, 'rrule_type': 'weekly', 'mon': True, 'count': 2, 'event_tz': 'Europe/Brussels' # DST change on 2020/3/23 }) events = self.event.recurrence_id.calendar_event_ids self.assertEventDates(events, [ (datetime(2020, 3, 23, 0, 0), datetime(2020, 3, 23, 23, 59)), (datetime(2020, 3, 30, 0, 0), datetime(2020, 3, 30, 23, 59)), ]) class TestUpdateRecurrentEvents(TestRecurrentEvents): @classmethod def setUpClass(cls): super().setUpClass() event = cls.env['calendar.event'].create({ 'name': 'Recurrent Event', 'start': datetime(2019, 10, 22, 1, 0), 'stop': datetime(2019, 10, 24, 18, 0), 'recurrency': True, 'rrule_type': 'weekly', 'tue': True, 'interval': 1, 'count': 3, 'event_tz': 'Etc/GMT-4', }) cls.recurrence = event.recurrence_id cls.events = event.recurrence_id.calendar_event_ids.sorted('start') def test_shift_future(self): event = self.events[1] self.events[1].write({ 'recurrence_update': 'future_events', 'start': event.start + relativedelta(days=4), 'stop': event.stop + relativedelta(days=5), }) self.assertEqual(self.recurrence.end_type, 'end_date') self.assertEqual(self.recurrence.until, date(2019, 10, 27)) self.assertEventDates(self.recurrence.calendar_event_ids, [ (datetime(2019, 10, 22, 1, 0), datetime(2019, 10, 24, 18, 0)), ]) new_recurrence = event.recurrence_id self.assertNotEqual(self.recurrence, new_recurrence) self.assertEqual(new_recurrence.count, 2) self.assertEqual(new_recurrence.dtstart, datetime(2019, 11, 2, 1, 0)) self.assertFalse(new_recurrence.tue) self.assertTrue(new_recurrence.sat) self.assertEventDates(new_recurrence.calendar_event_ids, [ (datetime(2019, 11, 2, 1, 0), datetime(2019, 11, 5, 18, 0)), (datetime(2019, 11, 9, 1, 0), datetime(2019, 11, 12, 18, 0)), ]) def test_shift_future_first(self): event = self.events[0] self.events[0].write({ 'recurrence_update': 'future_events', 'start': event.start + relativedelta(days=4), 'stop': event.stop + relativedelta(days=5), }) new_recurrence = event.recurrence_id self.assertFalse(self.recurrence.exists()) self.assertEqual(new_recurrence.count, 3) self.assertEqual(new_recurrence.dtstart, datetime(2019, 10, 26, 1, 0)) self.assertFalse(new_recurrence.tue) self.assertTrue(new_recurrence.sat) self.assertEventDates(new_recurrence.calendar_event_ids, [ (datetime(2019, 10, 26, 1, 0), datetime(2019, 10, 29, 18, 0)), (datetime(2019, 11, 2, 1, 0), datetime(2019, 11, 5, 18, 0)), (datetime(2019, 11, 9, 1, 0), datetime(2019, 11, 12, 18, 0)), ]) def test_shift_reapply(self): event = self.events[2] self.events[2].write({ 'recurrence_update': 'future_events', 'start': event.start + relativedelta(days=4), 'stop': event.stop + relativedelta(days=5), }) # re-Applying the first recurrence should be idempotent self.recurrence._apply_recurrence() self.assertEventDates(self.recurrence.calendar_event_ids, [ (datetime(2019, 10, 22, 1, 0), datetime(2019, 10, 24, 18, 0)), (datetime(2019, 10, 29, 1, 0), datetime(2019, 10, 31, 18, 0)), ]) def test_shift_all(self): event = self.events[1] self.assertEventDates(event.recurrence_id.calendar_event_ids, [ (datetime(2019, 10, 22, 1, 0), datetime(2019, 10, 24, 18, 0)), (datetime(2019, 10, 29, 1, 0), datetime(2019, 10, 31, 18, 0)), (datetime(2019, 11, 5, 1, 0), datetime(2019, 11, 7, 18, 0)), ]) event.write({ 'recurrence_update': 'all_events', 'tue': False, 'fri': False, 'sat': True, 'start': event.start + relativedelta(days=4), 'stop': event.stop + relativedelta(days=5), }) recurrence = self.env['calendar.recurrence'].search([]) self.assertEventDates(recurrence.calendar_event_ids, [ (datetime(2019, 10, 26, 1, 0), datetime(2019, 10, 29, 18, 0)), (datetime(2019, 11, 2, 1, 0), datetime(2019, 11, 5, 18, 0)), (datetime(2019, 11, 9, 1, 0), datetime(2019, 11, 12, 18, 0)), ]) def test_change_week_day_rrule(self): recurrence = self.events.recurrence_id recurrence.rrule = 'FREQ=WEEKLY;COUNT=3;BYDAY=WE' # from TU to WE self.assertFalse(self.recurrence.tue) self.assertTrue(self.recurrence.wed) def test_shift_all_base_inactive(self): self.recurrence.base_event_id.active = False event = self.events[1] event.write({ 'recurrence_update': 'all_events', 'start': event.start + relativedelta(days=4), 'stop': event.stop + relativedelta(days=5), }) self.assertFalse(self.recurrence.calendar_event_ids, "Inactive event should not create recurrent events") def test_shift_all_with_outlier(self): outlier = self.events[1] outlier.write({ 'recurrence_update': 'self_only', 'start': datetime(2019, 10, 31, 1, 0), # Thursday 'stop': datetime(2019, 10, 31, 18, 0), }) event = self.events[0] event.write({<|fim▁hole|> 'sat': True, 'start': event.start + relativedelta(days=4), 'stop': event.stop + relativedelta(days=4), }) self.assertEventDates(event.recurrence_id.calendar_event_ids, [ (datetime(2019, 10, 26, 1, 0), datetime(2019, 10, 28, 18, 0)), (datetime(2019, 11, 2, 1, 0), datetime(2019, 11, 4, 18, 0)), (datetime(2019, 11, 9, 1, 0), datetime(2019, 11, 11, 18, 0)) ]) self.assertFalse(outlier.exists(), 'The outlier should have been deleted') def test_update_recurrence_future(self): event = self.events[1] event.write({ 'recurrence_update': 'future_events', 'fri': True, # recurrence is now Tuesday AND Friday 'count': 4, }) self.assertEventDates(self.recurrence.calendar_event_ids, [ (datetime(2019, 10, 22, 1, 0), datetime(2019, 10, 24, 18, 0)), # Tu ]) self.assertEventDates(event.recurrence_id.calendar_event_ids, [ (datetime(2019, 10, 29, 1, 0), datetime(2019, 10, 31, 18, 0)), # Tu (datetime(2019, 11, 1, 1, 0), datetime(2019, 11, 3, 18, 0)), # Fr (datetime(2019, 11, 5, 1, 0), datetime(2019, 11, 7, 18, 0)), # Tu (datetime(2019, 11, 8, 1, 0), datetime(2019, 11, 10, 18, 0)), # Fr ]) events = event.recurrence_id.calendar_event_ids.sorted('start') self.assertEqual(events[0], self.events[1], "Events on Tuesdays should not have changed") self.assertEqual(events[2], self.events[2], "Events on Tuesdays should not have changed") self.assertNotEqual(events.recurrence_id, self.recurrence, "Events should no longer be linked to the original recurrence") self.assertEqual(events.recurrence_id.count, 4, "The new recurrence should have 4") self.assertTrue(event.recurrence_id.tue) self.assertTrue(event.recurrence_id.fri) def test_update_recurrence_all(self): self.events[1].write({ 'recurrence_update': 'all_events', 'mon': True, # recurrence is now Tuesday AND Monday }) recurrence = self.env['calendar.recurrence'].search([]) self.assertEventDates(recurrence.calendar_event_ids, [ (datetime(2019, 10, 22, 1, 0), datetime(2019, 10, 24, 18, 0)), (datetime(2019, 10, 28, 1, 0), datetime(2019, 10, 30, 18, 0)), (datetime(2019, 10, 29, 1, 0), datetime(2019, 10, 31, 18, 0)), ]) def test_shift_single(self): event = self.events[1] event.write({ 'recurrence_update': 'self_only', 'name': "Updated event", 'start': event.start - relativedelta(hours=2) }) self.events[0].write({ 'recurrence_update': 'future_events', 'start': event.start + relativedelta(hours=4), 'stop': event.stop + relativedelta(hours=5), }) def test_break_recurrence_future(self): event = self.events[1] event.write({ 'recurrence_update': 'future_events', 'recurrency': False, }) self.assertFalse(event.recurrence_id) self.assertTrue(self.events[0].active) self.assertTrue(self.events[1].active) self.assertFalse(self.events[2].exists()) self.assertEqual(self.recurrence.until, date(2019, 10, 27)) self.assertEqual(self.recurrence.end_type, 'end_date') self.assertEventDates(self.recurrence.calendar_event_ids, [ (datetime(2019, 10, 22, 1, 0), datetime(2019, 10, 24, 18, 0)), ]) def test_break_recurrence_all(self): event = self.events[1] event.write({ 'recurrence_update': 'all_events', 'recurrency': False, 'count': 0, # In practice, JS framework sends updated recurrency fields, since they have been recomputed, triggered by the `recurrency` change }) self.assertFalse(self.events[0].exists()) self.assertTrue(event.active) self.assertFalse(self.events[2].exists()) self.assertFalse(event.recurrence_id) self.assertFalse(self.recurrence.exists()) def test_all_day_shift(self): recurrence = self.env['calendar.event'].create({ 'name': 'Recurrent Event', 'start_date': datetime(2019, 10, 22), 'stop_date': datetime(2019, 10, 24), 'recurrency': True, 'rrule_type': 'weekly', 'tue': True, 'interval': 1, 'count': 3, 'event_tz': 'Etc/GMT-4', 'allday': True, }).recurrence_id events = recurrence.calendar_event_ids.sorted('start') event = events[1] event.write({ 'recurrence_update': 'future_events', 'start': event.start + relativedelta(days=4), 'stop': event.stop + relativedelta(days=5), }) self.assertEqual(recurrence.end_type, 'end_date') self.assertEqual(recurrence.until, date(2019, 10, 27)) self.assertEventDates(recurrence.calendar_event_ids, [ (datetime(2019, 10, 22, 8, 0), datetime(2019, 10, 24, 18, 0)), ]) new_recurrence = event.recurrence_id self.assertNotEqual(recurrence, new_recurrence) self.assertEqual(new_recurrence.count, 2) self.assertEqual(new_recurrence.dtstart, datetime(2019, 11, 2, 8, 0)) self.assertFalse(new_recurrence.tue) self.assertTrue(new_recurrence.sat) self.assertEventDates(new_recurrence.calendar_event_ids, [ (datetime(2019, 11, 2, 8, 0), datetime(2019, 11, 5, 18, 0)), (datetime(2019, 11, 9, 8, 0), datetime(2019, 11, 12, 18, 0)), ]) def test_archive_recurrence_all(self): self.events[1].action_mass_archive('all_events') self.assertEqual([False, False, False], self.events.mapped('active')) def test_archive_recurrence_future(self): event = self.events[1] event.action_mass_archive('future_events') self.assertEqual([True, False, False], self.events.mapped('active')) def test_unlink_recurrence_all(self): event = self.events[1] event.action_mass_deletion('all_events') self.assertFalse(self.recurrence.exists()) self.assertFalse(self.events.exists()) def test_unlink_recurrence_future(self): event = self.events[1] event.action_mass_deletion('future_events') self.assertTrue(self.recurrence) self.assertEqual(self.events.exists(), self.events[0]) class TestUpdateMultiDayWeeklyRecurrentEvents(TestRecurrentEvents): @classmethod def setUpClass(cls): super().setUpClass() event = cls.env['calendar.event'].create({ 'name': 'Recurrent Event', 'start': datetime(2019, 10, 22, 1, 0), 'stop': datetime(2019, 10, 24, 18, 0), 'recurrency': True, 'rrule_type': 'weekly', 'tue': True, 'fri': True, 'interval': 1, 'count': 3, 'event_tz': 'Etc/GMT-4', }) cls.recurrence = event.recurrence_id cls.events = event.recurrence_id.calendar_event_ids.sorted('start') # Tuesday datetime(2019, 10, 22, 1, 0) # Friday datetime(2019, 10, 25, 1, 0) # Tuesday datetime(2019, 10, 29, 1, 0) def test_shift_all_multiple_weekdays(self): event = self.events[0] # Tuesday # We go from 2 days a week Thuesday and Friday to one day a week, Thursday event.write({ 'recurrence_update': 'all_events', 'tue': False, 'thu': True, 'fri': False, 'start': event.start + relativedelta(days=2), 'stop': event.stop + relativedelta(days=2), }) recurrence = self.env['calendar.recurrence'].search([]) # We don't try to do magic tricks. First event is moved, other remain self.assertEventDates(recurrence.calendar_event_ids, [ (datetime(2019, 10, 24, 1, 0), datetime(2019, 10, 26, 18, 0)), (datetime(2019, 10, 31, 1, 0), datetime(2019, 11, 2, 18, 0)), (datetime(2019, 11, 7, 1, 0), datetime(2019, 11, 9, 18, 0)), ]) def test_shift_all_multiple_weekdays_duration(self): event = self.events[0] # Tuesday event.write({ 'recurrence_update': 'all_events', 'tue': False, 'thu': True, 'fri': False, 'start': event.start + relativedelta(days=2), 'stop': event.stop + relativedelta(days=3), }) recurrence = self.env['calendar.recurrence'].search([]) self.assertEventDates(recurrence.calendar_event_ids, [ (datetime(2019, 10, 24, 1, 0), datetime(2019, 10, 27, 18, 0)), (datetime(2019, 10, 31, 1, 0), datetime(2019, 11, 3, 18, 0)), (datetime(2019, 11, 7, 1, 0), datetime(2019, 11, 10, 18, 0)), ]) def test_shift_future_multiple_weekdays(self): event = self.events[1] # Friday event.write({ 'recurrence_update': 'future_events', 'start': event.start + relativedelta(days=3), 'stop': event.stop + relativedelta(days=3), }) self.assertTrue(self.recurrence.fri) self.assertTrue(self.recurrence.tue) self.assertTrue(event.recurrence_id.tue) self.assertTrue(event.recurrence_id.mon) self.assertFalse(event.recurrence_id.fri) self.assertEqual(event.recurrence_id.count, 2) class TestUpdateMonthlyByDay(TestRecurrentEvents): @classmethod def setUpClass(cls): super().setUpClass() event = cls.env['calendar.event'].create({ 'name': 'Recurrent Event', 'start': datetime(2019, 10, 15, 1, 0), 'stop': datetime(2019, 10, 16, 18, 0), 'recurrency': True, 'rrule_type': 'monthly', 'interval': 1, 'count': 3, 'month_by': 'day', 'weekday': 'TUE', 'byday': '3', 'event_tz': 'Etc/GMT-4', }) cls.recurrence = event.recurrence_id cls.events = event.recurrence_id.calendar_event_ids.sorted('start') # datetime(2019, 10, 15, 1, 0) # datetime(2019, 11, 19, 1, 0) # datetime(2019, 12, 17, 1, 0) def test_shift_all(self): event = self.events[1] event.write({ 'recurrence_update': 'all_events', 'start': event.start + relativedelta(hours=5), 'stop': event.stop + relativedelta(hours=5), }) recurrence = self.env['calendar.recurrence'].search([]) self.assertEventDates(recurrence.calendar_event_ids, [ (datetime(2019, 10, 15, 6, 0), datetime(2019, 10, 16, 23, 0)), (datetime(2019, 11, 19, 6, 0), datetime(2019, 11, 20, 23, 0)), (datetime(2019, 12, 17, 6, 0), datetime(2019, 12, 18, 23, 0)), ]) class TestUpdateMonthlyByDate(TestRecurrentEvents): @classmethod def setUpClass(cls): super().setUpClass() event = cls.env['calendar.event'].create({ 'name': 'Recurrent Event', 'start': datetime(2019, 10, 22, 1, 0), 'stop': datetime(2019, 10, 24, 18, 0), 'recurrency': True, 'rrule_type': 'monthly', 'interval': 1, 'count': 3, 'month_by': 'date', 'day': 22, 'event_tz': 'Etc/GMT-4', }) cls.recurrence = event.recurrence_id cls.events = event.recurrence_id.calendar_event_ids.sorted('start') # datetime(2019, 10, 22, 1, 0) # datetime(2019, 11, 22, 1, 0) # datetime(2019, 12, 22, 1, 0) def test_shift_future(self): event = self.events[1] event.write({ 'recurrence_update': 'future_events', 'start': event.start + relativedelta(days=4), 'stop': event.stop + relativedelta(days=5), }) self.assertEventDates(self.recurrence.calendar_event_ids, [ (datetime(2019, 10, 22, 1, 0), datetime(2019, 10, 24, 18, 0)), ]) self.assertEventDates(event.recurrence_id.calendar_event_ids, [ (datetime(2019, 11, 26, 1, 0), datetime(2019, 11, 29, 18, 0)), (datetime(2019, 12, 26, 1, 0), datetime(2019, 12, 29, 18, 0)), ]) def test_update_all(self): event = self.events[1] event.write({ 'recurrence_update': 'all_events', 'day': 25, }) recurrence = self.env['calendar.recurrence'].search([('day', '=', 25)]) self.assertEventDates(recurrence.calendar_event_ids, [ (datetime(2019, 10, 25, 1, 0), datetime(2019, 10, 27, 18, 0)), (datetime(2019, 11, 25, 1, 0), datetime(2019, 11, 27, 18, 0)), (datetime(2019, 12, 25, 1, 0), datetime(2019, 12, 27, 18, 0)), ])<|fim▁end|>
'recurrence_update': 'all_events', 'tue': False, 'fri': False,
<|file_name|>power_of_2.rs<|end_file_name|><|fim▁begin|>use integer::Integer; use malachite_base::num::arithmetic::traits::PowerOf2; use malachite_base::num::basic::traits::One; impl PowerOf2<u64> for Integer { /// Computes 2<sup>`pow`</sup>.<|fim▁hole|> /// Additional memory: worst case O(`pow`) /// /// # Examples /// ``` /// extern crate malachite_base; /// extern crate malachite_nz; /// /// use malachite_base::num::arithmetic::traits::PowerOf2; /// use malachite_nz::integer::Integer; /// /// assert_eq!(Integer::power_of_2(0).to_string(), "1"); /// assert_eq!(Integer::power_of_2(3).to_string(), "8"); /// assert_eq!(Integer::power_of_2(100).to_string(), "1267650600228229401496703205376"); /// ``` #[inline] fn power_of_2(pow: u64) -> Integer { Integer::ONE << pow } }<|fim▁end|>
/// /// Time: worst case O(`pow`) ///
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>//! The SMTP transport sends emails using the SMTP protocol. //! //! This SMTP client follows [RFC //! 5321](https://tools.ietf.org/html/rfc5321), and is designed to efficiently send emails from an //! application to a relay email server, as it relies as much as possible on the relay server //! for sanity and RFC compliance checks. //! //! It implements the following extensions: //! //! * 8BITMIME ([RFC 6152](https://tools.ietf.org/html/rfc6152)) //! * AUTH ([RFC 4954](https://tools.ietf.org/html/rfc4954)) with PLAIN, LOGIN and XOAUTH2 mechanisms //! * STARTTLS ([RFC 2487](https://tools.ietf.org/html/rfc2487)) //! //! #### SMTP Transport //! //! This transport uses the SMTP protocol to send emails over the network (locally or remotely). //! //! It is designed to be: //! //! * Secured: connections are encrypted by default //! * Modern: unicode support for email contents and sender/recipient addresses when compatible //! * Fast: supports connection reuse and pooling //! //! This client is designed to send emails to a relay server, and should *not* be used to send //! emails directly to the destination server. //! //! The relay server can be the local email server, a specific host or a third-party service. //! //! #### Simple example //! //! This is the most basic example of usage: //! //! ```rust,no_run //! # #[cfg(all(feature = "builder", any(feature = "native-tls", feature = "rustls-tls")))] //! # fn test() -> Result<(), Box<dyn std::error::Error>> { //! use lettre::{Message, Transport, SmtpTransport}; //! //! let email = Message::builder() //! .from("NoBody <nobody@domain.tld>".parse()?) //! .reply_to("Yuin <yuin@domain.tld>".parse()?) //! .to("Hei <hei@domain.tld>".parse()?) //! .subject("Happy new year") //! .body(String::from("Be happy!"))?; //! //! // Create TLS transport on port 465 //! let sender = SmtpTransport::relay("smtp.example.com")? //! .build(); //! // Send the email via remote relay //! let result = sender.send(&email); //! assert!(result.is_ok()); //! # Ok(()) //! # } //! ``` //! //! #### Authentication //! //! Example with authentication and connection pool: //! //! ```rust,no_run //! # #[cfg(all(feature = "builder", any(feature = "native-tls", feature = "rustls-tls")))] //! # fn test() -> Result<(), Box<dyn std::error::Error>> { //! use lettre::{Message, Transport, SmtpTransport, transport::smtp::{PoolConfig, authentication::{Credentials, Mechanism}}}; //! //! let email = Message::builder() //! .from("NoBody <nobody@domain.tld>".parse()?) //! .reply_to("Yuin <yuin@domain.tld>".parse()?) //! .to("Hei <hei@domain.tld>".parse()?) //! .subject("Happy new year") //! .body(String::from("Be happy!"))?; //! //! // Create TLS transport on port 587 with STARTTLS //! let sender = SmtpTransport::starttls_relay("smtp.example.com")? //! // Add credentials for authentication //! .credentials(Credentials::new("username".to_string(), "password".to_string())) //! // Configure expected authentication mechanism //! .authentication(vec![Mechanism::Plain]) //! // Connection pool settings //! .pool_config( PoolConfig::new().max_size(20)) //! .build(); //! //! // Send the email via remote relay //! let result = sender.send(&email); //! assert!(result.is_ok()); //! # Ok(()) //! # } //! ``` //! //! You can specify custom TLS settings: //! //! ```rust,no_run //! # #[cfg(all(feature = "builder", any(feature = "native-tls", feature = "rustls-tls")))] //! # fn test() -> Result<(), Box<dyn std::error::Error>> { //! use lettre::{Message, Transport, SmtpTransport, transport::smtp::client::{TlsParameters, Tls}}; //! //! let email = Message::builder() //! .from("NoBody <nobody@domain.tld>".parse()?) //! .reply_to("Yuin <yuin@domain.tld>".parse()?) //! .to("Hei <hei@domain.tld>".parse()?) //! .subject("Happy new year") //! .body(String::from("Be happy!"))?; //! //! // Custom TLS configuration //! let tls = TlsParameters::builder("smtp.example.com".to_string()) //! .dangerous_accept_invalid_certs(true).build()?; //! //! // Create TLS transport on port 465 //! let sender = SmtpTransport::relay("smtp.example.com")? //! // Custom TLS configuration //! .tls(Tls::Required(tls)) //! .build(); //! //! // Send the email via remote relay //! let result = sender.send(&email); //! assert!(result.is_ok()); //! # Ok(()) //! # } //! ``` #[cfg(any(feature = "tokio1", feature = "async-std1"))] pub use self::async_transport::{AsyncSmtpTransport, AsyncSmtpTransportBuilder}; #[cfg(feature = "pool")] pub use self::pool::PoolConfig; pub use self::{ error::Error, transport::{SmtpTransport, SmtpTransportBuilder}, }; #[cfg(any(feature = "native-tls", feature = "rustls-tls"))] use crate::transport::smtp::client::TlsParameters; use crate::transport::smtp::{ authentication::{Credentials, Mechanism, DEFAULT_MECHANISMS}, client::SmtpConnection, extension::ClientId, response::Response, }; use client::Tls; use std::time::Duration; #[cfg(any(feature = "tokio1", feature = "async-std1"))] mod async_transport; pub mod authentication; pub mod client; pub mod commands; mod error; pub mod extension; #[cfg(feature = "pool")] mod pool; pub mod response; mod transport; pub(super) mod util; // Registered port numbers: // https://www.iana. // org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml /// Default smtp port pub const SMTP_PORT: u16 = 25; /// Default submission port pub const SUBMISSION_PORT: u16 = 587; /// Default submission over TLS port /// /// Defined in [RFC8314](https://tools.ietf.org/html/rfc8314) pub const SUBMISSIONS_PORT: u16 = 465; /// Default timeout const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60); #[derive(Debug, Clone)] struct SmtpInfo { /// Name sent during EHLO hello_name: ClientId, /// Server we are connecting to server: String, /// Port to connect to port: u16, /// TLS security configuration tls: Tls, /// Optional enforced authentication mechanism authentication: Vec<Mechanism>, /// Credentials credentials: Option<Credentials>, /// Define network timeout /// It can be changed later for specific needs (like a different timeout for each SMTP command) timeout: Option<Duration>, } impl Default for SmtpInfo { fn default() -> Self { Self { server: "localhost".to_string(), port: SMTP_PORT, hello_name: ClientId::default(), credentials: None, authentication: DEFAULT_MECHANISMS.into(), timeout: Some(DEFAULT_TIMEOUT), tls: Tls::None, }<|fim▁hole|><|fim▁end|>
} }
<|file_name|>storage_extensions.go<|end_file_name|><|fim▁begin|>/* Copyright 2016 The Kubernetes 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. */ package master import ( "time" "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/rest" "k8s.io/kubernetes/pkg/apis/extensions" extensionsapiv1beta1 "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/genericapiserver" daemonetcd "k8s.io/kubernetes/pkg/registry/daemonset/etcd" deploymentetcd "k8s.io/kubernetes/pkg/registry/deployment/etcd" expcontrolleretcd "k8s.io/kubernetes/pkg/registry/experimental/controller/etcd" horizontalpodautoscaleretcd "k8s.io/kubernetes/pkg/registry/horizontalpodautoscaler/etcd" ingressetcd "k8s.io/kubernetes/pkg/registry/ingress/etcd" jobetcd "k8s.io/kubernetes/pkg/registry/job/etcd" networkpolicyetcd "k8s.io/kubernetes/pkg/registry/networkpolicy/etcd" pspetcd "k8s.io/kubernetes/pkg/registry/podsecuritypolicy/etcd" replicasetetcd "k8s.io/kubernetes/pkg/registry/replicaset/etcd" thirdpartyresourceetcd "k8s.io/kubernetes/pkg/registry/thirdpartyresource/etcd" "k8s.io/kubernetes/pkg/util/wait" ) type ExtensionsRESTStorageProvider struct { ResourceInterface resourceInterface DisableThirdPartyControllerForTesting bool } var _ RESTStorageProvider = &ExtensionsRESTStorageProvider{} func (p ExtensionsRESTStorageProvider) NewRESTStorage(apiResourceConfigSource genericapiserver.APIResourceConfigSource, restOptionsGetter RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) { apiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(extensions.GroupName) if apiResourceConfigSource.AnyResourcesForVersionEnabled(extensionsapiv1beta1.SchemeGroupVersion) { apiGroupInfo.VersionedResourcesStorageMap[extensionsapiv1beta1.SchemeGroupVersion.Version] = p.v1beta1Storage(apiResourceConfigSource, restOptionsGetter) apiGroupInfo.GroupMeta.GroupVersion = extensionsapiv1beta1.SchemeGroupVersion } return apiGroupInfo, true } func (p ExtensionsRESTStorageProvider) v1beta1Storage(apiResourceConfigSource genericapiserver.APIResourceConfigSource, restOptionsGetter RESTOptionsGetter) map[string]rest.Storage { version := extensionsapiv1beta1.SchemeGroupVersion storage := map[string]rest.Storage{} if apiResourceConfigSource.ResourceEnabled(version.WithResource("horizontalpodautoscalers")) { hpaStorage, hpaStatusStorage := horizontalpodautoscaleretcd.NewREST(restOptionsGetter(extensions.Resource("horizontalpodautoscalers"))) storage["horizontalpodautoscalers"] = hpaStorage storage["horizontalpodautoscalers/status"] = hpaStatusStorage controllerStorage := expcontrolleretcd.NewStorage(restOptionsGetter(api.Resource("replicationControllers"))) storage["replicationcontrollers"] = controllerStorage.ReplicationController storage["replicationcontrollers/scale"] = controllerStorage.Scale } if apiResourceConfigSource.ResourceEnabled(version.WithResource("thirdpartyresources")) { thirdPartyResourceStorage := thirdpartyresourceetcd.NewREST(restOptionsGetter(extensions.Resource("thirdpartyresources"))) thirdPartyControl := ThirdPartyController{ master: p.ResourceInterface, thirdPartyResourceRegistry: thirdPartyResourceStorage, } if !p.DisableThirdPartyControllerForTesting { go wait.Forever(func() { if err := thirdPartyControl.SyncResources(); err != nil { glog.Warningf("third party resource sync failed: %v", err) } }, 10*time.Second) } storage["thirdpartyresources"] = thirdPartyResourceStorage } if apiResourceConfigSource.ResourceEnabled(version.WithResource("daemonsets")) { daemonSetStorage, daemonSetStatusStorage := daemonetcd.NewREST(restOptionsGetter(extensions.Resource("daemonsets"))) storage["daemonsets"] = daemonSetStorage storage["daemonsets/status"] = daemonSetStatusStorage } if apiResourceConfigSource.ResourceEnabled(version.WithResource("deployments")) { deploymentStorage := deploymentetcd.NewStorage(restOptionsGetter(extensions.Resource("deployments"))) storage["deployments"] = deploymentStorage.Deployment storage["deployments/status"] = deploymentStorage.Status storage["deployments/rollback"] = deploymentStorage.Rollback storage["deployments/scale"] = deploymentStorage.Scale } if apiResourceConfigSource.ResourceEnabled(version.WithResource("jobs")) { jobsStorage, jobsStatusStorage := jobetcd.NewREST(restOptionsGetter(extensions.Resource("jobs"))) storage["jobs"] = jobsStorage storage["jobs/status"] = jobsStatusStorage } if apiResourceConfigSource.ResourceEnabled(version.WithResource("ingresses")) { ingressStorage, ingressStatusStorage := ingressetcd.NewREST(restOptionsGetter(extensions.Resource("ingresses")))<|fim▁hole|> podSecurityExtensionsStorage := pspetcd.NewREST(restOptionsGetter(extensions.Resource("podsecuritypolicy"))) storage["podSecurityPolicies"] = podSecurityExtensionsStorage } if apiResourceConfigSource.ResourceEnabled(version.WithResource("replicasets")) { replicaSetStorage := replicasetetcd.NewStorage(restOptionsGetter(extensions.Resource("replicasets"))) storage["replicasets"] = replicaSetStorage.ReplicaSet storage["replicasets/status"] = replicaSetStorage.Status storage["replicasets/scale"] = replicaSetStorage.Scale } if apiResourceConfigSource.ResourceEnabled(version.WithResource("networkpolicies")) { networkExtensionsStorage := networkpolicyetcd.NewREST(restOptionsGetter(extensions.Resource("networkpolicies"))) storage["networkpolicies"] = networkExtensionsStorage } return storage }<|fim▁end|>
storage["ingresses"] = ingressStorage storage["ingresses/status"] = ingressStatusStorage } if apiResourceConfigSource.ResourceEnabled(version.WithResource("podsecuritypolicy")) {
<|file_name|>00-fulfills-promise.exp.js<|end_file_name|><|fim▁begin|>var compilerSupport=require('../../src/compilerSupport');var main = function () { var __builder = new compilerSupport.TaskBuilder(), __state = 0, __continue = __builder.CONT, __ex; var data; return __builder.run(function () { switch (__state) { case 0: { data = 12345; console.log("data: " + data);<|fim▁hole|> } default: throw 'Internal error: encountered wrong state'; } }); }; main().then(function(x) { console.log("returned: " + x); }, function(y) { console.log("failed: " + y); });<|fim▁end|>
__state = -1; __builder.ret(data); break;
<|file_name|>common.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_camel_case_types)] use std::cast; use syntax::crateid::CrateId; use back::svh::Svh; // EBML enum definitions and utils shared by the encoder and decoder pub static tag_items: uint = 0x00; pub static tag_paths_data_name: uint = 0x01; pub static tag_def_id: uint = 0x02; pub static tag_items_data: uint = 0x03; pub static tag_items_data_item: uint = 0x04; pub static tag_items_data_item_family: uint = 0x05; pub static tag_items_data_item_ty_param_bounds: uint = 0x06; pub static tag_items_data_item_type: uint = 0x07; pub static tag_items_data_item_symbol: uint = 0x08; pub static tag_items_data_item_variant: uint = 0x09; pub static tag_items_data_parent_item: uint = 0x0a; pub static tag_items_data_item_is_tuple_struct_ctor: uint = 0x0b; pub static tag_index: uint = 0x0c; pub static tag_index_buckets: uint = 0x0d; pub static tag_index_buckets_bucket: uint = 0x0e; pub static tag_index_buckets_bucket_elt: uint = 0x0f; pub static tag_index_table: uint = 0x10; pub static tag_meta_item_name_value: uint = 0x11; pub static tag_meta_item_name: uint = 0x12; pub static tag_meta_item_value: uint = 0x13; pub static tag_attributes: uint = 0x14; pub static tag_attribute: uint = 0x15; pub static tag_meta_item_word: uint = 0x16; pub static tag_meta_item_list: uint = 0x17; // The list of crates that this crate depends on pub static tag_crate_deps: uint = 0x18; // A single crate dependency pub static tag_crate_dep: uint = 0x19; pub static tag_crate_hash: uint = 0x1a; pub static tag_crate_crateid: uint = 0x1b; pub static tag_crate_dep_crateid: uint = 0x1d; pub static tag_crate_dep_hash: uint = 0x1e; pub static tag_mod_impl: uint = 0x1f; pub static tag_item_trait_method: uint = 0x20; pub static tag_item_trait_ref: uint = 0x21; pub static tag_item_super_trait_ref: uint = 0x22; // discriminator value for variants pub static tag_disr_val: uint = 0x23; // used to encode ast_map::PathElem pub static tag_path: uint = 0x24; pub static tag_path_len: uint = 0x25; pub static tag_path_elem_mod: uint = 0x26; pub static tag_path_elem_name: uint = 0x27; pub static tag_item_field: uint = 0x28; pub static tag_item_variances: uint = 0x2a; /* trait items contain tag_item_trait_method elements, impl items contain tag_item_impl_method elements, and classes have both. That's because some code treats classes like traits, and other code treats them like impls. Because classes can contain both, tag_item_trait_method and tag_item_impl_method have to be two different tags. */ pub static tag_item_impl_method: uint = 0x2c; pub static tag_item_trait_method_explicit_self: uint = 0x2d; // Reexports are found within module tags. Each reexport contains def_ids // and names. pub static tag_items_data_item_reexport: uint = 0x2f; pub static tag_items_data_item_reexport_def_id: uint = 0x30; pub static tag_items_data_item_reexport_name: uint = 0x31; // used to encode crate_ctxt side tables #[deriving(Eq)] #[repr(uint)]<|fim▁hole|> tag_tree = 0x33, tag_id_range = 0x34, tag_table = 0x35, tag_table_id = 0x36, tag_table_val = 0x37, tag_table_def = 0x38, tag_table_node_type = 0x39, tag_table_node_type_subst = 0x3a, tag_table_freevars = 0x3b, tag_table_tcache = 0x3c, tag_table_param_defs = 0x3d, tag_table_mutbl = 0x3e, tag_table_last_use = 0x3f, tag_table_spill = 0x40, tag_table_method_map = 0x41, tag_table_vtable_map = 0x42, tag_table_adjustments = 0x43, tag_table_moves_map = 0x44, tag_table_capture_map = 0x45 } static first_astencode_tag: uint = tag_ast as uint; static last_astencode_tag: uint = tag_table_capture_map as uint; impl astencode_tag { pub fn from_uint(value : uint) -> Option<astencode_tag> { let is_a_tag = first_astencode_tag <= value && value <= last_astencode_tag; if !is_a_tag { None } else { Some(unsafe { cast::transmute(value) }) } } } pub static tag_item_trait_method_sort: uint = 0x46; pub static tag_item_impl_type_basename: uint = 0x47; // Language items are a top-level directory (for speed). Hierarchy: // // tag_lang_items // - tag_lang_items_item // - tag_lang_items_item_id: u32 // - tag_lang_items_item_node_id: u32 pub static tag_lang_items: uint = 0x48; pub static tag_lang_items_item: uint = 0x49; pub static tag_lang_items_item_id: uint = 0x4a; pub static tag_lang_items_item_node_id: uint = 0x4b; pub static tag_item_unnamed_field: uint = 0x4c; pub static tag_items_data_item_visibility: uint = 0x4e; pub static tag_item_method_tps: uint = 0x51; pub static tag_item_method_fty: uint = 0x52; pub static tag_mod_child: uint = 0x53; pub static tag_misc_info: uint = 0x54; pub static tag_misc_info_crate_items: uint = 0x55; pub static tag_item_method_provided_source: uint = 0x56; pub static tag_item_impl_vtables: uint = 0x57; pub static tag_impls: uint = 0x58; pub static tag_impls_impl: uint = 0x59; pub static tag_items_data_item_inherent_impl: uint = 0x5a; pub static tag_items_data_item_extension_impl: uint = 0x5b; pub static tag_region_param_def: uint = 0x5c; pub static tag_region_param_def_ident: uint = 0x5d; pub static tag_region_param_def_def_id: uint = 0x5e; pub static tag_native_libraries: uint = 0x5f; pub static tag_native_libraries_lib: uint = 0x60; pub static tag_native_libraries_name: uint = 0x61; pub static tag_native_libraries_kind: uint = 0x62; pub static tag_macro_registrar_fn: uint = 0x63; pub static tag_exported_macros: uint = 0x64; pub static tag_macro_def: uint = 0x65; #[deriving(Clone, Show)] pub struct LinkMeta { pub crateid: CrateId, pub crate_hash: Svh, }<|fim▁end|>
pub enum astencode_tag { // Reserves 0x32 -- 0x45 tag_ast = 0x32,
<|file_name|>index.js<|end_file_name|><|fim▁begin|>import Ember from 'ember-metal/core'; // reexports import Test from 'ember-testing/test'; import Adapter from 'ember-testing/adapters/adapter'; import setupForTesting from 'ember-testing/setup_for_testing'; import require from 'require'; import 'ember-testing/support'; // to handle various edge cases import 'ember-testing/ext/application'; import 'ember-testing/ext/rsvp'; import 'ember-testing/helpers'; // adds helpers to helpers object in Test import 'ember-testing/initializers'; // to setup initializer /** @module ember @submodule ember-testing<|fim▁hole|>*/ Ember.Test = Test; Ember.Test.Adapter = Adapter; Ember.setupForTesting = setupForTesting; Object.defineProperty(Test, 'QUnitAdapter', { get: () => require('ember-testing/adapters/qunit').default });<|fim▁end|>
<|file_name|>AppController.js<|end_file_name|><|fim▁begin|>angular.module('App')<|fim▁hole|> .controller('AppController', function($scope, $http, URL) { $http.get(URL, {headers: {"X-Requested-With" : "XMLHttpRequest"}}) .success(function (response) {$scope.examples = response.examples;}); });<|fim▁end|>
<|file_name|>test_sass_to_scss.py<|end_file_name|><|fim▁begin|>import logging from unittest import TestCase from sass_to_scss import SassToSCSS class TestSassToSCSS(TestCase): def setUp(self): self.sassy = SassToSCSS(loglevel=logging.DEBUG) def trim_docstring(self, docstring): return '\n'.join(docstring.split('\n')[1:-1]) def test_double_spaces(self): self.sassy.spaces = 2 sass = """ body background: red header background: blue """ scss = """ body { background: red; header { background: blue; } } """ actual = self.sassy.convert(self.trim_docstring(sass).split('\n')) expected = self.trim_docstring(scss) self.assertEquals(expected, actual) def test_triple_nested_class(self): sass = """ @import bourbon/bourbon @import "http://fonts.googleapis.com/css?family=PT+Serif:400,700,400italic,700italic|Oswald:400,300,700|Droid+Sans:400,700" $teal: #00917d $serif: 'PT Serif', serif =red-text color: red background-color: $teal =rounded($amount, $background_color) -moz-border-radius: $amount -webkit-border-radius: $amount border-radius: $amount background-color: saturate(lighten($background_color, 30%), 100%) .error<|fim▁hole|> +red-text .details border: 3px solid #777 +rounded(0.5em, desaturate(#5336a2, 10%)) .container position: absolute top: 0 color: green bottom: 0 .right, .row:hover, &.touch .row right: 0 border: 1px solid #fff h1 color: blue .left left: 0 h1 color: red """ scss = """ @import "bourbon/bourbon"; @import "http://fonts.googleapis.com/css?family=PT+Serif:400,700,400italic,700italic|Oswald:400,300,700|Droid+Sans:400,700"; $teal: #00917d; $serif: 'PT Serif', serif; @mixin red-text { color: red; background-color: $teal; } @mixin rounded($amount, $background_color) { -moz-border-radius: $amount; -webkit-border-radius: $amount; border-radius: $amount; background-color: saturate(lighten($background_color, 30%), 100%); } .error { @include red-text; .details { border: 3px solid #777; @include rounded(0.5em, desaturate(#5336a2, 10%)); } } .container { position: absolute; top: 0; color: green; bottom: 0; .right, .row:hover, &.touch .row { right: 0; border: 1px solid #fff; h1 { color: blue; } } .left { left: 0; h1 { color: red; } } } """ actual = self.sassy.convert(self.trim_docstring(sass).split('\n')) expected = self.trim_docstring(scss) self.assertEquals(expected, actual)<|fim▁end|>
<|file_name|>constants.ts<|end_file_name|><|fim▁begin|>/** moduleBank constants * */ import { ModuleCode } from '../types/modules'; export const FETCH_MODULE = 'FETCH_MODULE' as const; // Action to fetch modules export const FETCH_MODULE_LIST = 'FETCH_MODULE_LIST' as const; export const UPDATE_MODULE_TIMESTAMP = 'UPDATE_MODULE_TIMESTAMP' as const; export const REMOVE_LRU_MODULE = 'REMOVE_LRU_MODULE' as const; export const FETCH_ARCHIVE_MODULE = 'FETCH_ARCHIVE_MODULE' as const; // Action to fetch module from previous years export type RequestType = | typeof FETCH_MODULE | typeof FETCH_MODULE_LIST<|fim▁hole|> export function fetchModuleRequest(moduleCode: ModuleCode) { return `${FETCH_MODULE}/${moduleCode}`; } export function getRequestModuleCode(key: string): ModuleCode | null { const parts = key.split('/'); if (parts.length === 2 && parts[0] === FETCH_MODULE) return parts[1]; return null; } export function fetchArchiveRequest(moduleCode: ModuleCode, year: string) { return `${FETCH_ARCHIVE_MODULE}_${moduleCode}_${year}`; } /** undoHistory constants * */ export const UNDO = 'UNDO' as const; export const REDO = 'REDO' as const; /** export constant(s) * */ export const SET_EXPORTED_DATA = 'SET_EXPORTED_DATA' as const;<|fim▁end|>
| typeof UPDATE_MODULE_TIMESTAMP | typeof REMOVE_LRU_MODULE | typeof FETCH_ARCHIVE_MODULE;
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::IOHCR { #[doc = r" Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, {<|fim▁hole|> f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct G6_IO4R { bits: bool, } impl G6_IO4R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G6_IO3R { bits: bool, } impl G6_IO3R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G6_IO2R { bits: bool, } impl G6_IO2R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G6_IO1R { bits: bool, } impl G6_IO1R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G5_IO4R { bits: bool, } impl G5_IO4R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G5_IO3R { bits: bool, } impl G5_IO3R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G5_IO2R { bits: bool, } impl G5_IO2R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G5_IO1R { bits: bool, } impl G5_IO1R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G4_IO4R { bits: bool, } impl G4_IO4R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G4_IO3R { bits: bool, } impl G4_IO3R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G4_IO2R { bits: bool, } impl G4_IO2R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G4_IO1R { bits: bool, } impl G4_IO1R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G3_IO4R { bits: bool, } impl G3_IO4R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G3_IO3R { bits: bool, } impl G3_IO3R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G3_IO2R { bits: bool, } impl G3_IO2R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G3_IO1R { bits: bool, } impl G3_IO1R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G2_IO4R { bits: bool, } impl G2_IO4R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G2_IO3R { bits: bool, } impl G2_IO3R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G2_IO2R { bits: bool, } impl G2_IO2R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G2_IO1R { bits: bool, } impl G2_IO1R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G1_IO4R { bits: bool, } impl G1_IO4R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G1_IO3R { bits: bool, } impl G1_IO3R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G1_IO2R { bits: bool, } impl G1_IO2R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct G1_IO1R { bits: bool, } impl G1_IO1R { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Proxy"] pub struct _G6_IO4W<'a> { w: &'a mut W, } impl<'a> _G6_IO4W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 23; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G6_IO3W<'a> { w: &'a mut W, } impl<'a> _G6_IO3W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 22; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G6_IO2W<'a> { w: &'a mut W, } impl<'a> _G6_IO2W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 21; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G6_IO1W<'a> { w: &'a mut W, } impl<'a> _G6_IO1W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 20; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G5_IO4W<'a> { w: &'a mut W, } impl<'a> _G5_IO4W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 19; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G5_IO3W<'a> { w: &'a mut W, } impl<'a> _G5_IO3W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 18; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G5_IO2W<'a> { w: &'a mut W, } impl<'a> _G5_IO2W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 17; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G5_IO1W<'a> { w: &'a mut W, } impl<'a> _G5_IO1W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G4_IO4W<'a> { w: &'a mut W, } impl<'a> _G4_IO4W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 15; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G4_IO3W<'a> { w: &'a mut W, } impl<'a> _G4_IO3W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 14; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G4_IO2W<'a> { w: &'a mut W, } impl<'a> _G4_IO2W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 13; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G4_IO1W<'a> { w: &'a mut W, } impl<'a> _G4_IO1W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 12; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G3_IO4W<'a> { w: &'a mut W, } impl<'a> _G3_IO4W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 11; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G3_IO3W<'a> { w: &'a mut W, } impl<'a> _G3_IO3W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 10; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G3_IO2W<'a> { w: &'a mut W, } impl<'a> _G3_IO2W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 9; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G3_IO1W<'a> { w: &'a mut W, } impl<'a> _G3_IO1W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 8; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G2_IO4W<'a> { w: &'a mut W, } impl<'a> _G2_IO4W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 7; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G2_IO3W<'a> { w: &'a mut W, } impl<'a> _G2_IO3W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 6; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G2_IO2W<'a> { w: &'a mut W, } impl<'a> _G2_IO2W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 5; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G2_IO1W<'a> { w: &'a mut W, } impl<'a> _G2_IO1W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 4; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G1_IO4W<'a> { w: &'a mut W, } impl<'a> _G1_IO4W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 3; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G1_IO3W<'a> { w: &'a mut W, } impl<'a> _G1_IO3W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 2; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G1_IO2W<'a> { w: &'a mut W, } impl<'a> _G1_IO2W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 1; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _G1_IO1W<'a> { w: &'a mut W, } impl<'a> _G1_IO1W<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 23 - G6_IO4 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g6_io4(&self) -> G6_IO4R { let bits = { const MASK: bool = true; const OFFSET: u8 = 23; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G6_IO4R { bits } } #[doc = "Bit 22 - G6_IO3 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g6_io3(&self) -> G6_IO3R { let bits = { const MASK: bool = true; const OFFSET: u8 = 22; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G6_IO3R { bits } } #[doc = "Bit 21 - G6_IO2 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g6_io2(&self) -> G6_IO2R { let bits = { const MASK: bool = true; const OFFSET: u8 = 21; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G6_IO2R { bits } } #[doc = "Bit 20 - G6_IO1 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g6_io1(&self) -> G6_IO1R { let bits = { const MASK: bool = true; const OFFSET: u8 = 20; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G6_IO1R { bits } } #[doc = "Bit 19 - G5_IO4 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g5_io4(&self) -> G5_IO4R { let bits = { const MASK: bool = true; const OFFSET: u8 = 19; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G5_IO4R { bits } } #[doc = "Bit 18 - G5_IO3 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g5_io3(&self) -> G5_IO3R { let bits = { const MASK: bool = true; const OFFSET: u8 = 18; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G5_IO3R { bits } } #[doc = "Bit 17 - G5_IO2 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g5_io2(&self) -> G5_IO2R { let bits = { const MASK: bool = true; const OFFSET: u8 = 17; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G5_IO2R { bits } } #[doc = "Bit 16 - G5_IO1 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g5_io1(&self) -> G5_IO1R { let bits = { const MASK: bool = true; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G5_IO1R { bits } } #[doc = "Bit 15 - G4_IO4 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g4_io4(&self) -> G4_IO4R { let bits = { const MASK: bool = true; const OFFSET: u8 = 15; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G4_IO4R { bits } } #[doc = "Bit 14 - G4_IO3 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g4_io3(&self) -> G4_IO3R { let bits = { const MASK: bool = true; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G4_IO3R { bits } } #[doc = "Bit 13 - G4_IO2 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g4_io2(&self) -> G4_IO2R { let bits = { const MASK: bool = true; const OFFSET: u8 = 13; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G4_IO2R { bits } } #[doc = "Bit 12 - G4_IO1 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g4_io1(&self) -> G4_IO1R { let bits = { const MASK: bool = true; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G4_IO1R { bits } } #[doc = "Bit 11 - G3_IO4 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g3_io4(&self) -> G3_IO4R { let bits = { const MASK: bool = true; const OFFSET: u8 = 11; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G3_IO4R { bits } } #[doc = "Bit 10 - G3_IO3 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g3_io3(&self) -> G3_IO3R { let bits = { const MASK: bool = true; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G3_IO3R { bits } } #[doc = "Bit 9 - G3_IO2 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g3_io2(&self) -> G3_IO2R { let bits = { const MASK: bool = true; const OFFSET: u8 = 9; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G3_IO2R { bits } } #[doc = "Bit 8 - G3_IO1 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g3_io1(&self) -> G3_IO1R { let bits = { const MASK: bool = true; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G3_IO1R { bits } } #[doc = "Bit 7 - G2_IO4 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g2_io4(&self) -> G2_IO4R { let bits = { const MASK: bool = true; const OFFSET: u8 = 7; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G2_IO4R { bits } } #[doc = "Bit 6 - G2_IO3 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g2_io3(&self) -> G2_IO3R { let bits = { const MASK: bool = true; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G2_IO3R { bits } } #[doc = "Bit 5 - G2_IO2 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g2_io2(&self) -> G2_IO2R { let bits = { const MASK: bool = true; const OFFSET: u8 = 5; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G2_IO2R { bits } } #[doc = "Bit 4 - G2_IO1 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g2_io1(&self) -> G2_IO1R { let bits = { const MASK: bool = true; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G2_IO1R { bits } } #[doc = "Bit 3 - G1_IO4 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g1_io4(&self) -> G1_IO4R { let bits = { const MASK: bool = true; const OFFSET: u8 = 3; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G1_IO4R { bits } } #[doc = "Bit 2 - G1_IO3 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g1_io3(&self) -> G1_IO3R { let bits = { const MASK: bool = true; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G1_IO3R { bits } } #[doc = "Bit 1 - G1_IO2 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g1_io2(&self) -> G1_IO2R { let bits = { const MASK: bool = true; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G1_IO2R { bits } } #[doc = "Bit 0 - G1_IO1 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g1_io1(&self) -> G1_IO1R { let bits = { const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }; G1_IO1R { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline(always)] pub fn reset_value() -> W { W { bits: 4294967295 } } #[doc = r" Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 23 - G6_IO4 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g6_io4(&mut self) -> _G6_IO4W { _G6_IO4W { w: self } } #[doc = "Bit 22 - G6_IO3 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g6_io3(&mut self) -> _G6_IO3W { _G6_IO3W { w: self } } #[doc = "Bit 21 - G6_IO2 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g6_io2(&mut self) -> _G6_IO2W { _G6_IO2W { w: self } } #[doc = "Bit 20 - G6_IO1 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g6_io1(&mut self) -> _G6_IO1W { _G6_IO1W { w: self } } #[doc = "Bit 19 - G5_IO4 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g5_io4(&mut self) -> _G5_IO4W { _G5_IO4W { w: self } } #[doc = "Bit 18 - G5_IO3 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g5_io3(&mut self) -> _G5_IO3W { _G5_IO3W { w: self } } #[doc = "Bit 17 - G5_IO2 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g5_io2(&mut self) -> _G5_IO2W { _G5_IO2W { w: self } } #[doc = "Bit 16 - G5_IO1 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g5_io1(&mut self) -> _G5_IO1W { _G5_IO1W { w: self } } #[doc = "Bit 15 - G4_IO4 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g4_io4(&mut self) -> _G4_IO4W { _G4_IO4W { w: self } } #[doc = "Bit 14 - G4_IO3 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g4_io3(&mut self) -> _G4_IO3W { _G4_IO3W { w: self } } #[doc = "Bit 13 - G4_IO2 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g4_io2(&mut self) -> _G4_IO2W { _G4_IO2W { w: self } } #[doc = "Bit 12 - G4_IO1 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g4_io1(&mut self) -> _G4_IO1W { _G4_IO1W { w: self } } #[doc = "Bit 11 - G3_IO4 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g3_io4(&mut self) -> _G3_IO4W { _G3_IO4W { w: self } } #[doc = "Bit 10 - G3_IO3 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g3_io3(&mut self) -> _G3_IO3W { _G3_IO3W { w: self } } #[doc = "Bit 9 - G3_IO2 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g3_io2(&mut self) -> _G3_IO2W { _G3_IO2W { w: self } } #[doc = "Bit 8 - G3_IO1 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g3_io1(&mut self) -> _G3_IO1W { _G3_IO1W { w: self } } #[doc = "Bit 7 - G2_IO4 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g2_io4(&mut self) -> _G2_IO4W { _G2_IO4W { w: self } } #[doc = "Bit 6 - G2_IO3 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g2_io3(&mut self) -> _G2_IO3W { _G2_IO3W { w: self } } #[doc = "Bit 5 - G2_IO2 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g2_io2(&mut self) -> _G2_IO2W { _G2_IO2W { w: self } } #[doc = "Bit 4 - G2_IO1 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g2_io1(&mut self) -> _G2_IO1W { _G2_IO1W { w: self } } #[doc = "Bit 3 - G1_IO4 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g1_io4(&mut self) -> _G1_IO4W { _G1_IO4W { w: self } } #[doc = "Bit 2 - G1_IO3 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g1_io3(&mut self) -> _G1_IO3W { _G1_IO3W { w: self } } #[doc = "Bit 1 - G1_IO2 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g1_io2(&mut self) -> _G1_IO2W { _G1_IO2W { w: self } } #[doc = "Bit 0 - G1_IO1 Schmitt trigger hysteresis mode"] #[inline(always)] pub fn g1_io1(&mut self) -> _G1_IO1W { _G1_IO1W { w: self } } }<|fim▁end|>
let mut w = W::reset_value();
<|file_name|>match-arm-statics.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct NewBool(bool); enum Direction { North, East, South, West } static TRUE_TRUE: (bool, bool) = (true, true); fn nonexhaustive_1() { match (true, false) { //~^ ERROR non-exhaustive patterns: `(true, false)` not covered TRUE_TRUE => (), (false, false) => (), (false, true) => () } } fn unreachable_1() { match (true, false) { TRUE_TRUE => (), (false, false) => (), (false, true) => (), (true, false) => (), (true, true) => () //~^ ERROR unreachable pattern } } <|fim▁hole|>static EAST: Direction = East; fn nonexhaustive_2() { match Some(Some(North)) { //~^ ERROR non-exhaustive patterns: `Some(Some(West))` not covered Some(NONE) => (), Some(Some(North)) => (), Some(Some(EAST)) => (), Some(Some(South)) => (), None => () } } fn unreachable_2() { match Some(Some(North)) { Some(NONE) => (), Some(Some(North)) => (), Some(Some(EAST)) => (), Some(Some(South)) => (), Some(Some(West)) => (), Some(Some(East)) => (), //~^ ERROR unreachable pattern None => () } } static NEW_FALSE: NewBool = NewBool(false); struct Foo { bar: Option<Direction>, baz: NewBool } static STATIC_FOO: Foo = Foo { bar: None, baz: NEW_FALSE }; fn nonexhaustive_3() { match (Foo { bar: Some(North), baz: NewBool(true) }) { //~^ ERROR non-exhaustive patterns: `Foo { bar: Some(North), baz: NewBool(true) }` Foo { bar: None, baz: NewBool(true) } => (), Foo { bar: _, baz: NEW_FALSE } => (), Foo { bar: Some(West), baz: NewBool(true) } => (), Foo { bar: Some(South), .. } => (), Foo { bar: Some(EAST), .. } => () } } fn unreachable_3() { match (Foo { bar: Some(EAST), baz: NewBool(true) }) { Foo { bar: None, baz: NewBool(true) } => (), Foo { bar: _, baz: NEW_FALSE } => (), Foo { bar: Some(West), baz: NewBool(true) } => (), Foo { bar: Some(South), .. } => (), Foo { bar: Some(EAST), .. } => (), Foo { bar: Some(North), baz: NewBool(true) } => (), Foo { bar: Some(EAST), baz: NewBool(false) } => () //~^ ERROR unreachable pattern } } fn main() { nonexhaustive_1(); nonexhaustive_2(); nonexhaustive_3(); unreachable_1(); unreachable_2(); unreachable_3(); }<|fim▁end|>
static NONE: Option<Direction> = None;
<|file_name|>MultiSelect.java<|end_file_name|><|fim▁begin|>/** * Copyright (c) 2013 Andre Ricardo Schaffer * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.wiselenium.elements.component; import java.util.List; /** * Represents a HTML Multiple Select. * * @author Andre Ricardo Schaffer * @since 0.3.0 */ public interface MultiSelect extends Component<MultiSelect> { /** * Deselects all options. * * @return This select instance to allow chain calls. * @since 0.3.0 */ MultiSelect deselectAll(); /** * Deselects all options at the given indexes. This is done by examing the "index" attribute of * an element, and not merely by counting. * * @param indexes The option at this index will be selected. * @return This select element to allow chain calls. * @since 0.3.0 */ MultiSelect deselectByIndex(int... indexes); /** * Deselects all options that have a value matching the argument. That is, when given "foo" this * would select an option like: &lt;option value="foo"&gt;Bar&lt;/option&gt; * * @param values The values to match against. * @return This select element to allow chain calls. * @since 0.3.0 */ MultiSelect deselectByValue(String... values); /** * Deselects all options that display text matching the argument. That is, when given "Bar" this * would select an option like: &lt;option value="foo"&gt;Bar&lt;/option&gt; * * @param texts The visible texts to match against.<|fim▁hole|> /** * Deselects some options of this select if not already deselected. * * @param options The options to be deselected. * @return This select instance in order to allow chain calls. * @since 0.3.0 */ MultiSelect deselectOptions(Option... options); /** * Gets the options of this select. * * @return The options of this select. * @since 0.3.0 */ List<Option> getOptions(); /** * Returns the selected options. * * @return The selected options. * @since 0.3.0 */ List<Option> getSelectedOptions(); /** * Returns the selected values. * * @return The selected values. * @since 0.3.0 */ List<String> getSelectedValues(); /** * Returns the selected visible texts. * * @return The selected visible texts. * @since 0.3.0 */ List<String> getSelectedVisibleTexts(); /** * Selects all options. * * @return This select instance to allow chain calls. * @since 0.3.0 */ MultiSelect selectAll(); /** * Selects all options at the given indexes. This is done by examing the "index" attribute of an * element, and not merely by counting. * * @param indexes The option at this index will be selected. * @return This select element to allow chain calls. * @since 0.3.0 */ MultiSelect selectByIndex(int... indexes); /** * Selects all options that have a value matching the argument. That is, when given "foo" this * would select an option like: &lt;option value="foo"&gt;Bar&lt;/option&gt; * * @param values The values to match against. * @return This select element to allow chain calls. * @since 0.3.0 */ MultiSelect selectByValue(String... values); /** * Selects all options that display text matching the argument. That is, when given "Bar" this * would select an option like: &lt;option value="foo"&gt;Bar&lt;/option&gt; * * @param texts The visible texts to match against. * @return This select element to allow chain calls. * @since 0.3.0 */ MultiSelect selectByVisibleText(String... texts); /** * Selects some options of this select if not already selected. * * @param options The options to be selected. * @return This select instance in order to allow chain calls. * @since 0.3.0 */ MultiSelect selectOptions(Option... options); }<|fim▁end|>
* @return This select element to allow chain calls. * @since 0.3.0 */ MultiSelect deselectByVisibleText(String... texts);
<|file_name|>DatabaseConfig.java<|end_file_name|><|fim▁begin|>/* * Copyright 2020 Google LLC * * 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 * * https://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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/orchestration/airflow/service/v1/environments.proto package com.google.cloud.orchestration.airflow.service.v1; /** * * * <pre> * The configuration of Cloud SQL instance that is used by the Apache Airflow * software. * </pre> * * Protobuf type {@code google.cloud.orchestration.airflow.service.v1.DatabaseConfig} */ public final class DatabaseConfig extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.orchestration.airflow.service.v1.DatabaseConfig) DatabaseConfigOrBuilder { private static final long serialVersionUID = 0L; // Use DatabaseConfig.newBuilder() to construct. private DatabaseConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private DatabaseConfig() { machineType_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new DatabaseConfig(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private DatabaseConfig( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); machineType_ = s; break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.orchestration.airflow.service.v1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1_DatabaseConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.orchestration.airflow.service.v1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1_DatabaseConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig.class, com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig.Builder.class); } public static final int MACHINE_TYPE_FIELD_NUMBER = 1; private volatile java.lang.Object machineType_; /** * * * <pre> * Optional. Cloud SQL machine type used by Airflow database. * It has to be one of: db-n1-standard-2, db-n1-standard-4, db-n1-standard-8 * or db-n1-standard-16. If not specified, db-n1-standard-2 will be used. * </pre> * * <code>string machine_type = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The machineType. */ @java.lang.Override public java.lang.String getMachineType() { java.lang.Object ref = machineType_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); machineType_ = s; return s; } } /** * * * <pre> * Optional. Cloud SQL machine type used by Airflow database. * It has to be one of: db-n1-standard-2, db-n1-standard-4, db-n1-standard-8 * or db-n1-standard-16. If not specified, db-n1-standard-2 will be used. * </pre> * * <code>string machine_type = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for machineType. */ @java.lang.Override public com.google.protobuf.ByteString getMachineTypeBytes() { java.lang.Object ref = machineType_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); machineType_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(machineType_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, machineType_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(machineType_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, machineType_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig)) { return super.equals(obj); } com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig other = (com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig) obj; if (!getMachineType().equals(other.getMachineType())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() {<|fim▁hole|> int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + MACHINE_TYPE_FIELD_NUMBER; hash = (53 * hash) + getMachineType().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The configuration of Cloud SQL instance that is used by the Apache Airflow * software. * </pre> * * Protobuf type {@code google.cloud.orchestration.airflow.service.v1.DatabaseConfig} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.orchestration.airflow.service.v1.DatabaseConfig) com.google.cloud.orchestration.airflow.service.v1.DatabaseConfigOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.orchestration.airflow.service.v1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1_DatabaseConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.orchestration.airflow.service.v1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1_DatabaseConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig.class, com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig.Builder.class); } // Construct using com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); machineType_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.orchestration.airflow.service.v1.EnvironmentsOuterClass .internal_static_google_cloud_orchestration_airflow_service_v1_DatabaseConfig_descriptor; } @java.lang.Override public com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig getDefaultInstanceForType() { return com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig.getDefaultInstance(); } @java.lang.Override public com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig build() { com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig buildPartial() { com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig result = new com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig(this); result.machineType_ = machineType_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig) { return mergeFrom((com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig other) { if (other == com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig.getDefaultInstance()) return this; if (!other.getMachineType().isEmpty()) { machineType_ = other.machineType_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object machineType_ = ""; /** * * * <pre> * Optional. Cloud SQL machine type used by Airflow database. * It has to be one of: db-n1-standard-2, db-n1-standard-4, db-n1-standard-8 * or db-n1-standard-16. If not specified, db-n1-standard-2 will be used. * </pre> * * <code>string machine_type = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The machineType. */ public java.lang.String getMachineType() { java.lang.Object ref = machineType_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); machineType_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. Cloud SQL machine type used by Airflow database. * It has to be one of: db-n1-standard-2, db-n1-standard-4, db-n1-standard-8 * or db-n1-standard-16. If not specified, db-n1-standard-2 will be used. * </pre> * * <code>string machine_type = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for machineType. */ public com.google.protobuf.ByteString getMachineTypeBytes() { java.lang.Object ref = machineType_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); machineType_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. Cloud SQL machine type used by Airflow database. * It has to be one of: db-n1-standard-2, db-n1-standard-4, db-n1-standard-8 * or db-n1-standard-16. If not specified, db-n1-standard-2 will be used. * </pre> * * <code>string machine_type = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The machineType to set. * @return This builder for chaining. */ public Builder setMachineType(java.lang.String value) { if (value == null) { throw new NullPointerException(); } machineType_ = value; onChanged(); return this; } /** * * * <pre> * Optional. Cloud SQL machine type used by Airflow database. * It has to be one of: db-n1-standard-2, db-n1-standard-4, db-n1-standard-8 * or db-n1-standard-16. If not specified, db-n1-standard-2 will be used. * </pre> * * <code>string machine_type = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearMachineType() { machineType_ = getDefaultInstance().getMachineType(); onChanged(); return this; } /** * * * <pre> * Optional. Cloud SQL machine type used by Airflow database. * It has to be one of: db-n1-standard-2, db-n1-standard-4, db-n1-standard-8 * or db-n1-standard-16. If not specified, db-n1-standard-2 will be used. * </pre> * * <code>string machine_type = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for machineType to set. * @return This builder for chaining. */ public Builder setMachineTypeBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); machineType_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.orchestration.airflow.service.v1.DatabaseConfig) } // @@protoc_insertion_point(class_scope:google.cloud.orchestration.airflow.service.v1.DatabaseConfig) private static final com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig(); } public static com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DatabaseConfig> PARSER = new com.google.protobuf.AbstractParser<DatabaseConfig>() { @java.lang.Override public DatabaseConfig parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new DatabaseConfig(input, extensionRegistry); } }; public static com.google.protobuf.Parser<DatabaseConfig> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DatabaseConfig> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.orchestration.airflow.service.v1.DatabaseConfig getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }<|fim▁end|>
if (memoizedHashCode != 0) { return memoizedHashCode; }
<|file_name|>data_key_test.go<|end_file_name|><|fim▁begin|>/* Licensed to the Apache Software Foundation (ASF) under one<|fim▁hole|>to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package buckettree import ( "testing" "github.com/openblockchain/obc-peer/openchain/ledger/testutil" ) func TestDataKey(t *testing.T) { conf = newConfig(26, 3, fnvHash) dataKey := newDataKey("chaincodeID", "key") encodedBytes := dataKey.getEncodedBytes() dataKeyFromEncodedBytes := newDataKeyFromEncodedBytes(encodedBytes) testutil.AssertEquals(t, dataKey, dataKeyFromEncodedBytes) } func TestDataKeyGetBucketKey(t *testing.T) { conf = newConfig(26, 3, fnvHash) newDataKey("chaincodeID1", "key1").getBucketKey() newDataKey("chaincodeID1", "key2").getBucketKey() newDataKey("chaincodeID2", "key1").getBucketKey() newDataKey("chaincodeID2", "key2").getBucketKey() }<|fim▁end|>
or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file
<|file_name|>main.go<|end_file_name|><|fim▁begin|>// Copyright 2016 David Lavieri. All rights reserved. // Use of this source code is governed by a MIT License // License that can be found in the LICENSE file. package main import ( "fmt" "github.com/falmar/goradix" ) func main() { radix := goradix.New(false) radix.Insert("romanus", 1) radix.Insert("romane", 100) radix.Insert("romulus", 1000) value, err := radix.LookUp("romane") if err != nil { // No Match Found return<|fim▁hole|>}<|fim▁end|>
} // Output: Found node, Value: 100 fmt.Println("Found node, Value: ", value)
<|file_name|>UserInfosModel.py<|end_file_name|><|fim▁begin|>class UserInfoModel(object): PartenaireID = 0 Mail = "" CodeUtilisateur = "" TypeAbonnement = "" DateExpiration = "" DateSouscription = "" AccountExist = False def __init__(self, **kwargs): self.__dict__.update(kwargs) def create_dummy_model(self): self.Mail = "dummy@gmail.com"<|fim▁hole|> self.CodeUtilisateur = "dummy1234" self.AccountExist = True self.PartenaireID = 0<|fim▁end|>
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin from .models import Contact # Register your models here.<|fim▁hole|><|fim▁end|>
admin.site.register(Contact)
<|file_name|>basic_effect.py<|end_file_name|><|fim▁begin|>from razer.client import DeviceManager from razer.client import constants as razer_constants # Create a DeviceManager. This is used to get specific devices device_manager = DeviceManager()<|fim▁hole|> # Disable daemon effect syncing. # Without this, the daemon will try to set the lighting effect to every device. device_manager.sync_effects = False # Iterate over each device and set the wave effect for device in device_manager.devices: print("Setting {} to wave".format(device.name)) # Set the effect to wave. # wave requires a direction, but different effect have different arguments. device.fx.wave(razer_constants.WAVE_LEFT)<|fim▁end|>
print("Found {} Razer devices".format(len(device_manager.devices))) print()
<|file_name|>BukkitRegistry.java<|end_file_name|><|fim▁begin|>package net.minecraft.server; import java.util.Iterator; import java.util.List; import net.minecraft.src.BiomeGenBase; import cpw.mods.fml.common.registry.IMinecraftRegistry; import cpw.mods.fml.server.FMLBukkitHandler; public class BukkitRegistry implements IMinecraftRegistry { @Override public void addRecipe(net.minecraft.src.ItemStack output, Object... params) { CraftingManager.getInstance().registerShapedRecipe((ItemStack) output, params); } @Override public void addShapelessRecipe(net.minecraft.src.ItemStack output, Object... params) { CraftingManager.getInstance().registerShapelessRecipe((ItemStack) output, params); } @SuppressWarnings("unchecked") @Override public void addRecipe(net.minecraft.src.IRecipe recipe) { CraftingManager.getInstance().getRecipies().add(recipe); } @Override public void addSmelting(int input, net.minecraft.src.ItemStack output) { FurnaceRecipes.getInstance().registerRecipe(input, (ItemStack) output); } @Override public void registerBlock(net.minecraft.src.Block block) { registerBlock(block, ItemBlock.class); } @Override public void registerBlock(net.minecraft.src.Block block, Class <? extends net.minecraft.src.ItemBlock > itemclass) { try { assert block != null : "registerBlock: block cannot be null"; assert itemclass != null : "registerBlock: itemclass cannot be null"; int blockItemId = ((Block)block).id - 256; itemclass.getConstructor(int.class).newInstance(blockItemId); } catch (Exception e) { //HMMM } } @SuppressWarnings("unchecked") @Override public void registerEntityID(Class <? extends net.minecraft.src.Entity > entityClass, String entityName, int id) { EntityTypes.addNewEntityListMapping((Class<? extends Entity>) entityClass, entityName, id); } @SuppressWarnings("unchecked") @Override public void registerEntityID(Class <? extends net.minecraft.src.Entity > entityClass, String entityName, int id, int backgroundEggColour, int foregroundEggColour) { EntityTypes.addNewEntityListMapping((Class<? extends Entity>) entityClass, entityName, id, backgroundEggColour, foregroundEggColour); } @SuppressWarnings("unchecked") @Override public void registerTileEntity(Class <? extends net.minecraft.src.TileEntity > tileEntityClass, String id) { TileEntity.addNewTileEntityMapping((Class<? extends TileEntity>) tileEntityClass, id); } @Override public void addBiome(BiomeGenBase biome) { FMLBukkitHandler.instance().addBiomeToDefaultWorldGenerator((BiomeBase) biome); } @Override public void addSpawn(Class <? extends net.minecraft.src.EntityLiving > entityClass, int weightedProb, int min, int max, net.minecraft.src.EnumCreatureType typeOfCreature, BiomeGenBase... biomes) { BiomeBase[] realBiomes=(BiomeBase[]) biomes; for (BiomeBase biome : realBiomes) { @SuppressWarnings("unchecked") List<BiomeMeta> spawns = ((BiomeBase)biome).getMobs((EnumCreatureType)typeOfCreature); for (BiomeMeta entry : spawns) { //Adjusting an existing spawn entry if (entry.a == entityClass) { entry.d = weightedProb; entry.b = min; entry.c = max; break; } } spawns.add(new BiomeMeta(entityClass, weightedProb, min, max)); } } @Override @SuppressWarnings("unchecked") public void addSpawn(String entityName, int weightedProb, int min, int max, net.minecraft.src.EnumCreatureType spawnList, BiomeGenBase... biomes) { Class <? extends Entity > entityClazz = EntityTypes.getEntityToClassMapping().get(entityName); if (EntityLiving.class.isAssignableFrom(entityClazz))<|fim▁hole|> } @Override public void removeBiome(BiomeGenBase biome) { FMLBukkitHandler.instance().removeBiomeFromDefaultWorldGenerator((BiomeBase)biome); } @Override public void removeSpawn(Class <? extends net.minecraft.src.EntityLiving > entityClass, net.minecraft.src.EnumCreatureType typeOfCreature, BiomeGenBase... biomesO) { BiomeBase[] biomes=(BiomeBase[]) biomesO; for (BiomeBase biome : biomes) { @SuppressWarnings("unchecked") List<BiomeMeta> spawns = ((BiomeBase)biome).getMobs((EnumCreatureType) typeOfCreature); Iterator<BiomeMeta> entries = spawns.iterator(); while (entries.hasNext()) { BiomeMeta entry = entries.next(); if (entry.a == entityClass) { entries.remove(); } } } } @Override @SuppressWarnings("unchecked") public void removeSpawn(String entityName, net.minecraft.src.EnumCreatureType spawnList, BiomeGenBase... biomes) { Class <? extends Entity > entityClazz = EntityTypes.getEntityToClassMapping().get(entityName); if (EntityLiving.class.isAssignableFrom(entityClazz)) { removeSpawn((Class <? extends net.minecraft.src.EntityLiving >) entityClazz, spawnList, biomes); } } }<|fim▁end|>
{ addSpawn((Class <? extends net.minecraft.src.EntityLiving >) entityClazz, weightedProb, min, max, spawnList, biomes); }
<|file_name|>test_individual.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # encoding: utf-8 """ test_indivdual.py Test the individual class. Created by Måns Magnusson on 2013-03-07. Copyright (c) 2013 __MyCompanyName__. All rights reserved. """ import sys import os from ped_parser import individual class TestIndividual(object): """Test class for testing how the individual class behave""" def setup_class(self): """Setup a simple family with family id 1, sick daughter id 1, healthy father id 2, healthy mother id 3""" self.daughter = individual.Individual( ind='1', family='1', mother='3', father='2', sex=2, phenotype=2 ) self.father = individual.Individual( ind='2', family='1', mother='0', father='0', sex=1, phenotype=1 ) self.mother = individual.Individual( ind='3', family='1', mother='0', father='0', sex=2, phenotype=1 ) self.random_individual = individual.Individual(ind='0') def test_daughter(self): """Test if the information about the daughter comes out correctly.""" assert self.daughter.affected assert self.daughter.has_parents assert self.daughter.sex == 2 def test_father(self): """Test if the information about the father comes out correctly.""" assert not self.father.affected assert not self.father.has_parents assert self.father.sex == 1 def test_mother(self): """Test if the information about the mother comes out correctly.""" assert not self.mother.affected assert not self.mother.has_parents<|fim▁hole|> def test_random_individual(self): """Test if the information about the father comes out correctly.""" assert not self.random_individual.affected assert not self.random_individual.has_parents assert self.random_individual.sex == 0 def main(): pass if __name__ == '__main__': main()<|fim▁end|>
assert self.mother.sex == 2
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># flake8: noqa: F401 from pandas.core.arrays.sparse.accessor import SparseAccessor, SparseFrameAccessor from pandas.core.arrays.sparse.array import ( BlockIndex, IntIndex, SparseArray,<|fim▁hole|>from pandas.core.arrays.sparse.dtype import SparseDtype<|fim▁end|>
_make_index, )
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python from __future__ import print_function from __future__ import unicode_literals import os import sys import time import argparse from datetime import datetime, timedelta, tzinfo from textwrap import dedent import json from random import choice import webbrowser import itertools import logging import threading from threading import Thread from os.path import expanduser, expandvars, dirname, exists, join log = logging.getLogger() logging.basicConfig() import pendulum import six from six.moves import input from tzlocal import get_localzone from kazoo.client import KazooClient from kazoo.client import KazooState from kazoo.protocol.states import EventType from kazoo.handlers.threading import KazooTimeoutError import colorama from colorama import Fore, Back, Style from solrzkutil.util import netcat, text_type, parse_zk_hosts, get_leader, get_server_by_id from solrzkutil.parser import parse_admin_dump, parse_admin_cons from solrzkutil.healthy import (check_zookeeper_connectivity, check_ephemeral_sessions_fast, check_ephemeral_znode_consistency, check_ephemeral_dump_consistency, check_watch_sessions_clients, check_watch_sessions_duplicate, check_queue_sizes, check_watch_sessions_valid, check_overseer_election, get_solr_session_ids, multi_admin_command) __application__ = 'solr-zkutil' COMMANDS = { # key: cli-value # do not change the keys, but you may freely change the values of the tuple, to modify # the command or description. 'solr': ('live-nodes', 'List Solr Live Nodes from ZooKeeper'), 'clusterstate': ('clusterstate', 'List Solr Collections and Nodes'), 'watch': ('watch', 'Watch a ZooKeeper Node for Changes'), 'test': ('test', 'Test Each Zookeeper Ensemble node for replication and client connectivity'), # TODO 'status': ('stat', 'Check ZooKeeper ensemble status'), 'config': ('config', 'Show connection strings, or set environment configuration'), 'admin': ('admin', 'Execute a ZooKeeper administrative command'), 'ls': ('ls', 'List a ZooKeeper Node'), 'sessions': ('session-reset', 'Reset ZooKeeper sessions, each client will receive a SESSION EXPIRED notification, and will automatically reconnect. Solr ephemeral nodes should re-register themselves.'), 'health': ('health', 'Test/Check the health of Zookeeper and Solr, any errors or problems will be printed to the console.') } CONFIG_DIRNAME = __application__ HEADER_STYLE = Back.CYAN + Fore.WHITE + Style.BRIGHT HEADER_JUST = 10 TITLE_STYLE = Fore.CYAN + Style.BRIGHT INFO_STYLE = Fore.YELLOW + Style.BRIGHT ERROR_STYLE = Back.WHITE + Fore.RED + Style.BRIGHT INPUT_STYLE = Fore.WHITE + Style.BRIGHT BLUE_STYLE = Fore.BLUE + Style.BRIGHT DIFF_STYLE = Fore.MAGENTA + Style.BRIGHT STATS_STYLE = Fore.MAGENTA + Style.BRIGHT GREEN_STYLE = Fore.GREEN + Style.BRIGHT ZK_LIVE_NODES = '/live_nodes' ZK_CLUSTERSTATE = '/clusterstate.json' MODE_LEADER = 'leader' # the first event will always be triggered immediately to show the existing state of the node # instead of saying 'watch event' tell the user we are just displaying initial state. WATCH_COUNTER = 0 ZK_ADMIN_CMDS = { 'conf': { 'help': 'Print details about serving configuration.', 'example': '', 'version': '3.3.0', }, 'cons': { 'help': ('List full connection/session details for all clients connected to this server. ' 'Includes information on numbers of packets received/sent, session id, operation ' 'latencies, last operation performed, etc...'), 'example': '', 'version': '3.3.0', }, 'crst':{ 'help': 'Reset connection/session statistics for all connections.', 'example': '', 'version': '3.3.0', }, 'dump':{ 'help': 'Lists the outstanding sessions and ephemeral nodes. This only works on the leader.', 'example': '', 'version': '', }, 'envi':{ 'help': 'Print details about serving environment', 'example': '', 'version': '', }, 'ruok':{ 'help': 'Tests if server is running in a non-error state. The server will respond with imok if it is running. Otherwise it will not respond at all.', 'example': '', 'version': '', }, 'srst':{ 'help': 'Reset server statistics.', 'example': '', 'version': '', }, 'srvr':{ 'help': 'Lists full details for the server.', 'example': '', 'version': '3.3.0', }, 'stat':{ 'help': 'Lists brief details for the server and connected clients.', 'example': '', 'version': '', }, 'wchs':{ 'help': 'Lists brief information on watches for the server.', 'example': '', 'version': '3.3.0', }, 'wchc':{ 'help': 'Lists detailed information on watches for the server, by session. (may be expensive)', 'example': '', 'version': '3.3.0', }, 'dirs':{ 'help': 'Shows the total size of snapshot and log files in bytes', 'example': '', 'version': '3.5.1', }, 'wchp':{ 'help': 'Lists detailed information on watches for the server, by path. This outputs a list of paths (znodes) with associated sessions.', 'example': '', 'version': '3.3.0', }, 'mntr': { 'help': 'Outputs a list of variables that could be used for monitoring the health of the cluster.', 'example': '3.4.0' }, 'isro':{ 'help': 'Tests if server is running in read-only mode. The server will respond with "ro" if in read-only mode or "rw" if not in read-only mode.', 'example': '', 'version': '3.4.0', }, 'gtmk':{ 'help': 'Gets the current trace mask as a 64-bit signed long value in decimal format. See stmk for an explanation of the possible values.', 'example': '', 'version': '', }, 'stmk':{ 'help': 'Sets the current trace mask. The trace mask is 64 bits, where each bit enables or disables a specific category of trace logging on the server.', 'example': '', 'version': '', }, } ZNODE_DEBUG_ATTRS = [ 'aversion', 'cversion', 'version', 'numChildren', 'ctime', 'mtime', 'czxid', 'mzxid', 'pzxid', 'dataLength', 'ephemeralOwner', ] NEW_TAB = 2 def config_path(): conf = None if os.name == 'nt': conf = os.path.expandvars("%%appdata%%/.%s/environments.json" % CONFIG_DIRNAME) else: conf = os.path.expanduser("~/.%s/environments.json" % CONFIG_DIRNAME) return conf def config(): conf = config_path() if not exists(conf): if not exists(dirname(conf)): os.makedirs(dirname(conf)) open(conf, mode='w').write(dedent(''' { "DEV": "localhost:2181", "QA": "localhost:2181", "PILOT": "localhost:2181", "PROD": "localhost:2181" } ''')) return json.loads(open(conf, mode='r').read().strip()) def style_header(text, width = 0): if not text: return '' width = max(len(text) + HEADER_JUST * 2, width) pad = ' ' * width output = '\n%s%s\n%s\n%s%s\n' % (HEADER_STYLE, pad, text.center(width), pad, Style.RESET_ALL) return output def style_text(text, styles, ljust=0, rjust=0, cen=0, lpad=0, rpad=0, pad=0, char=' ', restore=''): if not text: return '' # Ensure we have unicode in both python 2/3 text = text_type(text) styles = text_type(styles) char = text_type(char) restore = text_type(restore) reset_all = text_type(Style.RESET_ALL) style = ''.join(styles) text = text.ljust(ljust, char) text = text.rjust(rjust, char) text = text.center(cen, char) text = char*(lpad+pad) + text + char*(rpad+pad) return '%s%s%s%s' % (style, text, reset_all, restore) #return style + text + Style.RESET_ALL + restore def style_multiline(text, styles, ljust=0, rjust=0, cen=0, lpad=0, rpad=0, pad=0, char=' '): if not text: return '' lines = text.split('\n') fmt_text = '' for text in lines: text = style_text(text, styles, ljust, rjust, cen, lpad, rpad, pad, char) fmt_text += text + '\n' return fmt_text def update_config(configuration=None, add=None): """ Update the environments configuration on-disk. """ existing_config = config() conf = config_path() print(style_header('Zookeeper Environments')) print("") print(style_text('config:', TITLE_STYLE, pad=2), end='') print(style_text(conf, INPUT_STYLE)) print(style_multiline(json.dumps(existing_config, indent=4, sort_keys=True), INFO_STYLE, lpad=4)) if not configuration and not add: return new_config = existing_config if configuration: new_config = configuration if add: new_config.update(add) new_config = json.dumps(new_config, indent=4, sort_keys=True) print("") print(style_text('new config:', TITLE_STYLE, pad=2)) print(style_multiline(new_config, INFO_STYLE, lpad=4)) print("") # Get permission to replace the existing configuration. if input(style_text("Replace configuration? (y/n): ", INPUT_STYLE)).lower() not in ('y', 'yes'): print(" ...Cancel") return open(conf, mode='w').write(new_config) print(style_text(' ...Saved', INPUT_STYLE, pad=2)) def clusterstate(zookeepers, all_hosts, node='clusterstate.json'): """ Print clusterstatus.json contents """ zk_hosts = parse_zk_hosts(zookeepers, all_hosts=all_hosts) print('') # we'll keep track of differences for this node between zookeepers. # because zookeeper keeps all nodes in-sync, there shouldn't be differences between the # nodes... but there might be if you are having replication problems. first_state = None for host in zk_hosts: # connect to zookeeper zk = KazooClient(hosts=host, read_only=True) try: zk.start() except KazooTimeoutError as e: print('ZK Timeout host: [%s], %s' % (host, e)) continue # If the node doesn't exist... just let the user know. if not zk.exists(node): node_str = style_text(node, BLUE_STYLE, restore=ERROR_STYLE) zk_str = style_text(host, BLUE_STYLE, restore=ERROR_STYLE) print(style_text('No node [%s] on %s' % (node_str, zk_str), ERROR_STYLE)) continue print(style_header('Response From: %s [%s]' % (host, node))) state = bytes.decode(zk.get(node)[0]) if not first_state: first_state = state lines_1 = first_state.split('\n') lines_2 = state.split('\n') # Print the content of the file, highlighting lines that do not match between hosts. for idx, line in enumerate(lines_2): if len(lines_1)-1 < idx or line != lines_1[idx]: style = DIFF_STYLE else: style = INFO_STYLE print(style_text(line, style, lpad=4)) zk.stop() def show_node(zookeepers, node, all_hosts=False, leader=False, debug=False, interactive=False): """ Show a zookeeper node on one or more servers. If the node has children, the children are displayed, If the node doesn't have children, the contents of the node are displayed. If leader is specified, only the leader is queried for the node If all_hosts is specified, each zk host provided is queried individually... if the results are different between nodes, the child nodes that are different will be highlighted. returns children of the requested node. """ zk_hosts = parse_zk_hosts(zookeepers, all_hosts=all_hosts, leader=leader) # we'll keep track of differences for this node between zookeepers. # because zookeeper keeps all nodes in-sync, there shouldn't be differences between the # nodes... but there might be if you are having replication problems. all_children = set() for host in zk_hosts: # connect to zookeeper zk = KazooClient(hosts=host, read_only=True) try: zk.start() except KazooTimeoutError as e: print('ZK Timeout host: [%s], %s' % (host, e)) continue print('') # If the node doesn't exist... just let the user know. if not zk.exists(node): node_str = style_text(node, BLUE_STYLE, restore=ERROR_STYLE) zk_str = style_text(host, BLUE_STYLE, restore=ERROR_STYLE) print(style_text('No node [%s] on %s' % (node_str, zk_str), ERROR_STYLE, pad=2)) continue if len(zk_hosts) == 1: print(style_header('Response From: %s [%s]' % (host, node))) else: print(style_text('Response From: %s [%s]' % (host, node), HEADER_STYLE, pad=2)) # Query ZooKeeper for the node. content, zstats = zk.get(node) # print(dir(zstats)) # print(getattr(zstats, 'czxid')) # --- Print Node Stats ------------------------- znode_unix_time = zstats.mtime / 1000 # # local_timezone = time.tzname[time.localtime().tm_isdst] DO NOT USE THIS is_dst = time.daylight and time.localtime().tm_isdst offset_hour = time.altzone / 3600 if is_dst else time.timezone / 3600 timezone = 'Etc/GMT%+d' % offset_hour mod_time = pendulum.fromtimestamp(znode_unix_time, timezone) mod_time = mod_time.in_timezone(timezone) local_time_str = mod_time.to_day_datetime_string() version = str(zstats.version) or str(zstats.cversion) if debug: dbg_rjust = max(map(len, ZNODE_DEBUG_ATTRS)) print(style_text("Node Stats:", TITLE_STYLE, lpad=2)) for attr_name in ZNODE_DEBUG_ATTRS: attr_val = getattr(zstats, attr_name) if 'time' in attr_name and attr_val > 1: attr_val = pendulum.fromtimestamp(int(attr_val) / 1000, timezone).in_timezone(timezone).to_day_datetime_string() print(style_text(attr_name, STATS_STYLE, lpad=4, rjust=dbg_rjust), style_text(attr_val, INPUT_STYLE)) else: print(style_text('Modified:', STATS_STYLE, lpad=2, rjust=9), style_text(local_time_str, INPUT_STYLE)) print(style_text('Version:', STATS_STYLE, lpad=2, rjust=9), style_text(version, INPUT_STYLE)) print('') # --- Print Child Nodes, or Node Content ------- if not zstats.numChildren: zcontent = bytes.decode(content or b'') if zcontent: print(style_text("Contents:", TITLE_STYLE, lpad=2)) print(style_multiline(zcontent, INFO_STYLE, lpad=4)) else: print(style_text("... No child nodes", INFO_STYLE, lpad=2)) else: children = zk.get_children(node) children.sort() cwidth = max([len(c) for c in children]) print(style_text("Child Nodes:", TITLE_STYLE, lpad=2)) for ch in children: child_path = node+ch if node.endswith('/') else node+'/'+ch _, czstats = zk.get(child_path) if all_children and ch not in all_children: # if this child is unique / different to this zk host, color it differently. print(style_text(ch, INPUT_STYLE, lpad=4, ljust=cwidth), end='') else: print(style_text(ch, INFO_STYLE, lpad=4, ljust=cwidth), end='') mod_ver = czstats.version or czstats.cversion print(style_text('v:', STATS_STYLE, lpad=3), style_text(str(mod_ver), INPUT_STYLE, ljust=3), end='') print(style_text('eph:', STATS_STYLE, lpad=3), style_text('yes' if czstats.ephemeralOwner else 'no', INPUT_STYLE), end='') mod_datetime = datetime.utcfromtimestamp(czstats.mtime / 1000) mod_elapsed = datetime.utcnow() - mod_datetime if mod_elapsed >= timedelta(hours=48): mod_style = '' elif mod_elapsed >= timedelta(hours=2): mod_style = INPUT_STYLE elif mod_elapsed >= timedelta(minutes=10): mod_style = GREEN_STYLE elif mod_elapsed >= timedelta(minutes=1): mod_style = INFO_STYLE else: mod_style = STATS_STYLE if mod_datetime.year != 1970: mod_desc = pendulum.fromtimestamp(czstats.mtime / 1000, 'UTC').diff_for_humans() else: mod_desc = 'none' print(style_text('mod:', STATS_STYLE, lpad=3), style_text(mod_desc, mod_style)) zk.stop() all_children = all_children | set(children) return list(all_children) def watch(zookeepers, node, leader=False): """ Watch a particular zookeeper node for changes. """ zk_hosts = parse_zk_hosts(zookeepers, leader=leader)[0] def my_listener(state): if state == KazooState.LOST: # Register somewhere that the session was lost print(style_text('Connection Lost', ERROR_STYLE, pad=2)) elif state == KazooState.SUSPENDED: # Handle being disconnected from Zookeeper print(style_text('Connection Suspended', ERROR_STYLE, pad=2)) else: # Handle being connected/reconnected to Zookeeper # what are we supposed to do here? print(style_text('Connected/Reconnected', INFO_STYLE, pad=2)) zk = KazooClient(hosts=zk_hosts, read_only=True) try: zk.start() except KazooTimeoutError as e: print('ZK Timeout host: [%s], %s' % (host, e)) zk_ver = '.'.join(map(str, zk.server_version())) zk_host = zk.hosts[zk.last_zxid] zk_host = ':'.join(map(str, zk_host)) zk.add_listener(my_listener) # check if the node exists ... if not zk.exists(node): node_str = style_text(node, BLUE_STYLE, restore=ERROR_STYLE) zk_str = style_text(zk_host, BLUE_STYLE, restore=ERROR_STYLE) print('') print(style_text('No node [%s] on %s' % (node_str, zk_str), ERROR_STYLE, pad=2)) return print(style_header('Watching [%s] on %s v%s' % (node, zk_host, zk_ver))) # put a watch on my znode children = zk.get_children(node) # If there are children, watch them. if children or node.endswith('/'): @zk.ChildrenWatch(node) def watch_children(children): global WATCH_COUNTER WATCH_COUNTER += 1 if WATCH_COUNTER <= 1: child_watch_str = 'Child Nodes:' else: child_watch_str = 'Node Watch Event: ' children.sort() print('') print(style_text(child_watch_str, TITLE_STYLE)) for ch in children: print(style_text(ch, INFO_STYLE, lpad=2)) print('') else: # otherwise watch the node itself. @zk.DataWatch(node) def watch_data(data, stat, event): global WATCH_COUNTER WATCH_COUNTER += 1 data = data.decode('utf-8') if WATCH_COUNTER <= 1: data_watch_str = 'Content: (%s)' else: data_watch_str = 'Data Watch Event: (v%s)' print('') print(style_text(data_watch_str % stat.version, TITLE_STYLE)) print(style_multiline(data, INFO_STYLE, lpad=2)) print('') CHAR_WIDTH = 60 counter = 0 while True: # draw a .... animation while we wait, so the user knows its working. counter += 1 if not counter % CHAR_WIDTH: print('\r', ' '*CHAR_WIDTH, '\r', end='') print(style_text('.', INFO_STYLE), end='') time.sleep(0.05) zk.stop() def admin_command(zookeepers, command, all_hosts=False, leader=False): """ Execute an administrative command """ command = text_type(command) # ensure we have unicode py2/py3 zk_hosts = parse_zk_hosts(zookeepers, all_hosts=all_hosts, leader=leader) for host in zk_hosts: print('') # use netcat, so we don't modify any transaction values by executing an admin command. strcmd = command.encode('utf-8') hostaddr, port = host.split(':') status = netcat(hostaddr, port, strcmd) if len(zk_hosts) == 1: print(style_header('ZK Command [%s] on %s' % (command, host))) else: print(style_text('ZK Command [%s] on %s' % (command, host), HEADER_STYLE, pad=2)) print(style_multiline(status, INFO_STYLE, lpad=2)) def sessions_reset(zookeepers, server_id=None, ephemeral=False, solr=False): """ Reset connections/sessions to Zookeeper. """ # TODO support --clients / --solrj option ? if server_id: zk_host = parse_zk_hosts(zookeepers, server_id=server_id)[0] else: zk_host = parse_zk_hosts(zookeepers, leader=True)[0] def get_all_sessions(zk_client): # Get connection/session information conn_results = multi_admin_command(zk_client, b'cons') conn_data = map(parse_admin_cons, conn_results) conn_data = list(itertools.chain.from_iterable(conn_data)) # Get a dict of all valid zookeeper sessions as integers return {con['sid']: con['client'][0] for con in conn_data if con.get('sid')} search = [] if ephemeral: search += ["ephemeral sessions"] else: search += ["sessions"] if solr: if search: search += ['that are'] search += ['solr servers'] if server_id: search += ['on serverId: %d (%s)' % (server_id, zk_host)] else: search += ['on all ensemble members'] print(style_header('RESETTING %s' % ' '.join(search))) hostaddr, port = zk_host.split(':') dump = netcat(hostaddr, port, b'dump') dump_data = parse_admin_dump(dump) all_sessions = get_all_sessions(KazooClient(zookeepers)) sessions_before = set(all_sessions.keys()) sessions = [] if server_id is not None: sessions = sorted(all_sessions.keys()) else: sessions = sorted(all_sessions.keys()) if ephemeral: sessions = [s for s in sessions if s in dump_data['ephemerals']] if solr: sessions = healthy.get_solr_session_ids(KazooClient(zookeepers)) if not sessions: print(style_text("No sessions matching criteria", STATS_STYLE, lpad=2)) <|fim▁hole|> SESSION_TIMEOUT = 30 print(style_text("Sessions will now be reset. This will take %d secs\n" % SESSION_TIMEOUT, TITLE_STYLE, lpad=2)) tlock = threading.Lock() def break_session(zookeepers, session): with tlock: s_style = style_text("%s" % str(session_id), STATS_STYLE) print(style_text("Resetting session: %s(%s)" % (s_style, all_sessions[session_id]), INFO_STYLE, lpad=2)) zk = None try: zk = KazooClient(hosts=zk_host, client_id=(session_id, b''), max_retries=3, retry_delay=0.5) zk.start(SESSION_TIMEOUT) zk.get('/live_nodes') time.sleep(SESSION_TIMEOUT) except KazooTimeoutError as e: with tlock: print('ZK Timeout host: [%s], %s' % (zk_host, e)) except Exception as e: with tlock: print(style_text("Error Resetting session: %s" % e, ERROR_STYLE, lpad=2)) finally: if zk: zk.stop() with tlock: print(style_text("Disconnect session: %s" % s_style, INFO_STYLE, lpad=2)) wait = [] for session_id in sessions: t = Thread(target=break_session, args=(zookeepers, session_id)) t.start() wait.append(t) # wait for all threads to finish for wait_thread in wait: wait_thread.join() ######################################### # wait some time for sessions to come back. time.sleep(5) sessions_after = get_all_sessions(KazooClient(zookeepers)) sessions_kept = sessions_before & set(sessions_after.keys()) print(style_text("\nSESSIONS BEFORE RESET (%d)" % len(sessions_before), TITLE_STYLE, lpad=2)) for sid in sorted(sessions_before): if sid in sessions_kept: print(style_text(str(sid), INFO_STYLE, lpad=4)) else: print(style_text(str(sid), STATS_STYLE, lpad=4)) print(style_text("\nSESSIONS AFTER RESET (%d)" % len(sessions_after), TITLE_STYLE, lpad=2)) for sid in sorted(sessions_after): if sid in sessions_kept: print(style_text(str(sid), INFO_STYLE, lpad=4)) else: print(style_text(str(sid)+'(new)', STATS_STYLE, lpad=4)) def health_check(zookeepers): zk_client = KazooClient(zookeepers) for check in (check_zookeeper_connectivity, check_ephemeral_sessions_fast, check_ephemeral_znode_consistency, check_ephemeral_dump_consistency, check_watch_sessions_clients, check_watch_sessions_duplicate, check_queue_sizes, check_watch_sessions_valid, check_overseer_election): print(style_text("RUNNING: %s" % check.__name__, TITLE_STYLE, lpad=2)) try: errors = check(zk_client) except Exception as e: print(healthy.get_exception_traceback()) print(style_text("ERROR RUNNING %s" % check.__name__, ERROR_STYLE, lpad=4)) if not errors: print(style_text("NO ERRORS in %s" % check.__name__, STATS_STYLE, lpad=4)) else: print(style_text("ERRORS from %s" % check.__name__, INFO_STYLE, lpad=4)) for err in errors: print(style_text(err, ERROR_STYLE, lpad=8)) def cli(): """ Build the CLI menu """ def verify_json(arg): try: data = json.loads(arg) except ValueError as e: raise argparse.ArgumentTypeError("invalid json: %s" % e) return data def verify_env(arg): try: env_config = config() except ValueError as e: raise argparse.ArgumentTypeError('Cannot read configuration %s' % e) if arg not in env_config: raise argparse.ArgumentTypeError('Invalid Environment %s ... Valid: [%s]' % (arg, ', '.join(list(env_config)))) return env_config[arg] def verify_zk(arg): hosts = arg.split('/')[0] hosts = hosts.split(',') if ' ' in arg: raise argparse.ArgumentTypeError("There should be no spaces between zookeeper hosts: %s" % arg) for zk in hosts: hostport = zk.split(':') if len(hostport) == 1: raise argparse.ArgumentTypeError("Port is required for: %s... default: 2181" % zk) else: _, port = hostport if not port.isdigit(): raise argparse.ArgumentTypeError("Port must be numeric for: %s" % zk) return arg def verify_add(arg): if '=' not in arg: raise argparse.ArgumentTypeError("You must use the syntax ENVIRONMENT=127.0.0.1:2181") env, zk = arg.split('=') verify_zk(zk) return {env.strip(): zk.strip()} def verify_node(arg): if not arg.startswith('/'): raise argparse.ArgumentTypeError("Zookeeper nodes start with /") return arg def verify_cmd(arg): if arg.lower() not in ZK_ADMIN_CMDS: raise argparse.ArgumentTypeError("Invalid command '%s'... \nValid Commands: %s" % (arg, '\n '.join(ZK_ADMIN_CMDS))) return arg.lower() # Top level parser parser = argparse.ArgumentParser(prog=__application__) subparsers = parser.add_subparsers(help='--- available sub-commands ---', dest='command') try: env_config = config() except ValueError: env_config = {} zk_argument = { 'args': ['-z', '--zookeepers'], 'kwargs': { 'required': False, 'default': None, 'type': verify_zk, 'help': ('Zookeeper connection string, with optional root... \n' 'eg. 127.0.0.1:2181 or 10.10.1.5:2181/root \n' 'NOTE: --zookeepers or --env must be specified!') } } env_argument = { 'args': ['-e', '--env'], 'kwargs': { 'required': False, 'default': None, 'type': verify_env, 'help': ('Connect to zookeeper using one of the configured environments. \n' 'Note: to view or modify config use the "%s" sub-command. \n' 'Configured Environments: [%s]' % (COMMANDS['config'][0], ', '.join(list(env_config)))) } } all_argument = { 'args': ['-a', '--all-hosts'], 'kwargs': { 'default': False, 'required': False, 'action': 'store_true', 'help': 'Show response from all zookeeper hosts' } } leader_argument = { 'args': ['-l', '--leader'], 'kwargs': { 'default': False, 'required': False, 'action': 'store_true', 'help': 'Query ensemble leader only' } } debug_argument = { 'args': ['--debug'], 'kwargs': { 'default': False, 'required': False, 'action': 'store_true', 'help': 'Show debug stats' } } # -- SOLR - LIVE NODES ----------- cmd, about = COMMANDS['solr'] solr = subparsers.add_parser(cmd, help=about) solr.add_argument(*zk_argument['args'], **zk_argument['kwargs']) solr.add_argument(*env_argument['args'], **env_argument['kwargs']) solr.add_argument(*all_argument['args'], **all_argument['kwargs']) solr.add_argument('-b', '--browser', default=False, required=False, action='store_true', help='Open solr-admin in web-browser for resolved host') solr.add_argument(*leader_argument['args'], **leader_argument['kwargs']) # -- SOLR - CLUSTERSTATE ------- cmd, about = COMMANDS['clusterstate'] cluster = subparsers.add_parser(cmd, help=about) cluster.add_argument(*zk_argument['args'], **zk_argument['kwargs']) cluster.add_argument(*env_argument['args'], **env_argument['kwargs']) cluster.add_argument(*all_argument['args'], **all_argument['kwargs']) # -- WATCH ---------------------- cmd, about = COMMANDS['watch'] watches = subparsers.add_parser(cmd, help=about) watches.add_argument('node', help='Zookeeper node', type=verify_node) watches.add_argument(*zk_argument['args'], **zk_argument['kwargs']) watches.add_argument(*env_argument['args'], **env_argument['kwargs']) watches.add_argument(*leader_argument['args'], **leader_argument['kwargs']) # -- LS ------------------------- cmd, about = COMMANDS['ls'] ls = subparsers.add_parser(cmd, help=about) ls.add_argument('node', help='Zookeeper node', type=verify_node) # positional argument ls.add_argument(*zk_argument['args'], **zk_argument['kwargs']) ls.add_argument(*env_argument['args'], **env_argument['kwargs']) ls.add_argument(*all_argument['args'], **all_argument['kwargs']) ls.add_argument(*leader_argument['args'], **leader_argument['kwargs']) ls.add_argument(*debug_argument['args'], **debug_argument['kwargs']) # -- STATUS --------------------- cmd, about = COMMANDS['status'] status = subparsers.add_parser(cmd, help=about) status.add_argument(*zk_argument['args'], **zk_argument['kwargs']) status.add_argument(*env_argument['args'], **env_argument['kwargs']) status.add_argument(*leader_argument['args'], **leader_argument['kwargs']) # -- ADMIN --------------------- cmd, about = COMMANDS['admin'] admin = subparsers.add_parser(cmd, help=about) admin.add_argument('cmd', help='ZooKeeper Administrative Command', type=verify_cmd) admin.add_argument(*zk_argument['args'], **zk_argument['kwargs']) admin.add_argument(*env_argument['args'], **env_argument['kwargs']) admin.add_argument(*all_argument['args'], **all_argument['kwargs']) admin.add_argument(*leader_argument['args'], **leader_argument['kwargs']) # -- CONFIG --------------------- cmd, about = COMMANDS['config'] envs = subparsers.add_parser(cmd, help=about) envs.add_argument('-c', '--configuration', default=None, required=False, type=verify_json, help='Set the environments configuration located at %s, string passed must be valid json ' % config_path()) envs.add_argument('-a', '--add', default=None, required=False, type=verify_add, help=('add/update an environment variable using the syntax KEY=VALUE,\n' 'eg. DEV=zk01.dev.com:2181,zk02.dev.com:2181')) # -- SESSIONS RESET ------------- cmd, about = COMMANDS['sessions'] session = subparsers.add_parser(cmd, help=about) session.add_argument(*zk_argument['args'], **zk_argument['kwargs']) session.add_argument(*env_argument['args'], **env_argument['kwargs']) session.add_argument('-id', '--server-id', type=int, default=None, required=False, help='reset connections only for the matched server id, if not specified ALL sessions are reset') session.add_argument('--ephemeral', action='store_true', required=False, help='reset sessions with ephemeral nodes only') session.add_argument('--solr', action='store_true', required=False, help='reset sessions from solr nodes only') # -- HEALTH ------------------- cmd, about = COMMANDS['health'] session = subparsers.add_parser(cmd, help=about) session.add_argument(*zk_argument['args'], **zk_argument['kwargs']) session.add_argument(*env_argument['args'], **env_argument['kwargs']) return parser def main(argv=None): colorama.init(autoreset=True) # initialize color handling for windows terminals. parser = cli() args = vars(parser.parse_args(argv[1:])) cmd = args['command'] if (('zookeepers' in args and 'env' in args) and not any((args['env'], args['zookeepers']))): print(" 'zookeepers', or 'env' argument is required", end='') print(' ', style_text("Add --help to your command for help", ERROR_STYLE, pad=1)) return if args.get('env') and not args.get('zookeepers'): # when env is specified and valid, but zookeepers is not # env should have been resolved to a zookeeper host string. args['zookeepers'] = args['env'] # -- COMMAND HANDLERS -------------------------------------------------------------------------- if cmd == COMMANDS['solr'][0]: hosts = show_node(zookeepers=args['zookeepers'], node=ZK_LIVE_NODES, all_hosts=args['all_hosts'], leader=args['leader']) if args.get('browser') and hosts: solr_admin = choice(hosts).replace('_solr', '/solr') # C:\Users\Scott\AppData\Local\Google\Chrome\Application\chrome.exe # webbrowser._tryorder webbrowser.get().open('http://'+solr_admin, new=NEW_TAB, autoraise=True) elif cmd == COMMANDS['clusterstate'][0]: clusterstate(zookeepers=args['zookeepers'], all_hosts=args['all_hosts']) elif cmd == COMMANDS['ls'][0]: show_node(zookeepers=args['zookeepers'], node=args['node'], all_hosts=args['all_hosts'], leader=args['leader'], debug=args['debug']) elif cmd == COMMANDS['watch'][0]: watch(zookeepers=args['zookeepers'], node=args['node'], leader=args['leader']) elif cmd == COMMANDS['config'][0]: update_config(configuration=args['configuration'], add=args['add']) elif cmd == COMMANDS['status'][0]: # TODO improve this command so it is a combination of mntr, stat, cons, and ruok admin_command(zookeepers=args['zookeepers'], command='stat', leader=args['leader']) elif cmd == COMMANDS['admin'][0]: admin_command(zookeepers=args['zookeepers'], command=args['cmd'], all_hosts=args['all_hosts'], leader=args['leader']) elif cmd == COMMANDS['sessions'][0]: sessions_reset(zookeepers=args['zookeepers'], server_id=args['server_id'], ephemeral=args['ephemeral'], solr=args['solr']) elif cmd == COMMANDS['health'][0]: health_check(zookeepers=args['zookeepers']) else: parser.print_help() print("") if __name__ == '__main__': try: sys.exit(main(sys.argv)) except KeyboardInterrupt: sys.exit('\n')<|fim▁end|>
return ################################## ### THREADING IMPLEMENTATION #####
<|file_name|>console.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- mode: python; sh-basic-offset: 4; indent-tabs-mode: nil; coding: utf-8 -*- # vim: tabstop=4 softtabstop=4 expandtab shiftwidth=4 fileencoding=utf-8 # # Shell command # Copyright 2010, Jeremy Grosser <synack@digg.com> import argparse import os import sys import clusto from clusto import script_helper class Console(script_helper.Script): '''<|fim▁hole|> def __init__(self): script_helper.Script.__init__(self) def _add_arguments(self, parser): user = os.environ.get('USER') parser.add_argument('--user', '-u', default=user, help='SSH User (you can also set this in clusto.conf too' 'in console.user: --user > clusto.conf:console.user > "%s")' % user) parser.add_argument('server', nargs=1, help='Object to console to (IP or name)') def add_subparser(self, subparsers): parser = self._setup_subparser(subparsers) self._add_arguments(parser) def run(self, args): try: server = clusto.get(args.server[0]) if not server: raise LookupError('Object "%s" does not exist' % args.server) except Exception as e: self.debug(e) self.error('No object like "%s" was found' % args.server) return 1 server = server[0] if not hasattr(server, 'console'): self.error('The object %s lacks a console method' % server.name) return 2 user = os.environ.get('USER') if args.user: self.debug('Grabbing user from parameter') user = args.user else: self.debug('Grabbing user from config file or default') user = self.get_conf('console.user', user) self.debug('User is "%s"' % user) return(server.console(ssh_user=user)) def main(): console, args = script_helper.init_arguments(Console) return(console.run(args)) if __name__ == '__main__': sys.exit(main())<|fim▁end|>
Use clusto's hardware port mappings to console to a remote server using the serial console. '''
<|file_name|>qdisc.go<|end_file_name|><|fim▁begin|>package netlink import ( "fmt" "math" ) const ( HANDLE_NONE = 0 HANDLE_INGRESS = 0xFFFFFFF1 HANDLE_CLSACT = HANDLE_INGRESS HANDLE_ROOT = 0xFFFFFFFF PRIORITY_MAP_LEN = 16 ) const ( HANDLE_MIN_INGRESS = 0xFFFFFFF2 HANDLE_MIN_EGRESS = 0xFFFFFFF3 ) type Qdisc interface { Attrs() *QdiscAttrs Type() string } // QdiscAttrs represents a netlink qdisc. A qdisc is associated with a link, // has a handle, a parent and a refcnt. The root qdisc of a device should // have parent == HANDLE_ROOT. type QdiscAttrs struct { LinkIndex int Handle uint32 Parent uint32 Refcnt uint32 // read only } func (q QdiscAttrs) String() string { return fmt.Sprintf("{LinkIndex: %d, Handle: %s, Parent: %s, Refcnt: %d}", q.LinkIndex, HandleStr(q.Handle), HandleStr(q.Parent), q.Refcnt) } func MakeHandle(major, minor uint16) uint32 { return (uint32(major) << 16) | uint32(minor) } func MajorMinor(handle uint32) (uint16, uint16) { return uint16((handle & 0xFFFF0000) >> 16), uint16(handle & 0x0000FFFFF) } func HandleStr(handle uint32) string { switch handle { case HANDLE_NONE: return "none" case HANDLE_INGRESS: return "ingress" case HANDLE_ROOT: return "root" default: major, minor := MajorMinor(handle) return fmt.Sprintf("%x:%x", major, minor) } } func Percentage2u32(percentage float32) uint32 { // FIXME this is most likely not the best way to convert from % to uint32 if percentage == 100 { return math.MaxUint32 } return uint32(math.MaxUint32 * (percentage / 100)) } // PfifoFast is the default qdisc created by the kernel if one has not // been defined for the interface type PfifoFast struct { QdiscAttrs Bands uint8 PriorityMap [PRIORITY_MAP_LEN]uint8 } func (qdisc *PfifoFast) Attrs() *QdiscAttrs { return &qdisc.QdiscAttrs } func (qdisc *PfifoFast) Type() string { return "pfifo_fast" } // Prio is a basic qdisc that works just like PfifoFast type Prio struct { QdiscAttrs Bands uint8 PriorityMap [PRIORITY_MAP_LEN]uint8 } func NewPrio(attrs QdiscAttrs) *Prio { return &Prio{ QdiscAttrs: attrs, Bands: 3, PriorityMap: [PRIORITY_MAP_LEN]uint8{1, 2, 2, 2, 1, 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1}, } } func (qdisc *Prio) Attrs() *QdiscAttrs { return &qdisc.QdiscAttrs } func (qdisc *Prio) Type() string { return "prio" } // Htb is a classful qdisc that rate limits based on tokens type Htb struct { QdiscAttrs Version uint32 Rate2Quantum uint32 Defcls uint32 Debug uint32 DirectPkts uint32 } func NewHtb(attrs QdiscAttrs) *Htb { return &Htb{ QdiscAttrs: attrs, Version: 3, Defcls: 0, Rate2Quantum: 10, Debug: 0, DirectPkts: 0, } } func (qdisc *Htb) Attrs() *QdiscAttrs { return &qdisc.QdiscAttrs } func (qdisc *Htb) Type() string { return "htb" } // Netem is a classless qdisc that rate limits based on tokens type NetemQdiscAttrs struct { Latency uint32 // in us DelayCorr float32 // in % Limit uint32 Loss float32 // in % LossCorr float32 // in % Gap uint32 Duplicate float32 // in % DuplicateCorr float32 // in % Jitter uint32 // in us ReorderProb float32 // in % ReorderCorr float32 // in % CorruptProb float32 // in % CorruptCorr float32 // in % } func (q NetemQdiscAttrs) String() string { return fmt.Sprintf( "{Latency: %d, Limit: %d, Loss: %f, Gap: %d, Duplicate: %f, Jitter: %d}", q.Latency, q.Limit, q.Loss, q.Gap, q.Duplicate, q.Jitter, ) } type Netem struct { QdiscAttrs Latency uint32 DelayCorr uint32 Limit uint32 Loss uint32 LossCorr uint32 Gap uint32 Duplicate uint32 DuplicateCorr uint32 Jitter uint32 ReorderProb uint32 ReorderCorr uint32 CorruptProb uint32 CorruptCorr uint32 } func (netem *Netem) String() string { return fmt.Sprintf( "{Latency: %v, Limit: %v, Loss: %v, Gap: %v, Duplicate: %v, Jitter: %v}", netem.Latency, netem.Limit, netem.Loss, netem.Gap, netem.Duplicate, netem.Jitter, ) } func (qdisc *Netem) Attrs() *QdiscAttrs { return &qdisc.QdiscAttrs } func (qdisc *Netem) Type() string { return "netem" } // Tbf is a classless qdisc that rate limits based on tokens type Tbf struct { QdiscAttrs Rate uint64 Limit uint32 Buffer uint32 Peakrate uint64 Minburst uint32 // TODO: handle other settings } func (qdisc *Tbf) Attrs() *QdiscAttrs { return &qdisc.QdiscAttrs } func (qdisc *Tbf) Type() string { return "tbf" } // Ingress is a qdisc for adding ingress filters type Ingress struct { QdiscAttrs } func (qdisc *Ingress) Attrs() *QdiscAttrs { return &qdisc.QdiscAttrs } func (qdisc *Ingress) Type() string { return "ingress" } // GenericQdisc qdiscs represent types that are not currently understood // by this netlink library. type GenericQdisc struct { QdiscAttrs QdiscType string } func (qdisc *GenericQdisc) Attrs() *QdiscAttrs { return &qdisc.QdiscAttrs } func (qdisc *GenericQdisc) Type() string { return qdisc.QdiscType } type Hfsc struct { QdiscAttrs Defcls uint16 } func NewHfsc(attrs QdiscAttrs) *Hfsc { return &Hfsc{ QdiscAttrs: attrs, Defcls: 1, } } func (hfsc *Hfsc) Attrs() *QdiscAttrs { return &hfsc.QdiscAttrs } func (hfsc *Hfsc) Type() string { return "hfsc" } func (hfsc *Hfsc) String() string { return fmt.Sprintf( "{%v -- default: %d}", hfsc.Attrs(), hfsc.Defcls, ) } // Fq is a classless packet scheduler meant to be mostly used for locally generated traffic. type Fq struct { QdiscAttrs PacketLimit uint32 FlowPacketLimit uint32 // In bytes Quantum uint32 InitialQuantum uint32 // called RateEnable under the hood Pacing uint32<|fim▁hole|> // called BucketsLog under the hood Buckets uint32 FlowRefillDelay uint32 LowRateThreshold uint32 } func (fq *Fq) String() string { return fmt.Sprintf( "{PacketLimit: %v, FlowPacketLimit: %v, Quantum: %v, InitialQuantum: %v, Pacing: %v, FlowDefaultRate: %v, FlowMaxRate: %v, Buckets: %v, FlowRefillDelay: %v, LowRateThreshold: %v}", fq.PacketLimit, fq.FlowPacketLimit, fq.Quantum, fq.InitialQuantum, fq.Pacing, fq.FlowDefaultRate, fq.FlowMaxRate, fq.Buckets, fq.FlowRefillDelay, fq.LowRateThreshold, ) } func NewFq(attrs QdiscAttrs) *Fq { return &Fq{ QdiscAttrs: attrs, Pacing: 1, } } func (qdisc *Fq) Attrs() *QdiscAttrs { return &qdisc.QdiscAttrs } func (qdisc *Fq) Type() string { return "fq" } // FQ_Codel (Fair Queuing Controlled Delay) is queuing discipline that combines Fair Queuing with the CoDel AQM scheme. type FqCodel struct { QdiscAttrs Target uint32 Limit uint32 Interval uint32 ECN uint32 Flows uint32 Quantum uint32 CEThreshold uint32 DropBatchSize uint32 MemoryLimit uint32 } func (fqcodel *FqCodel) String() string { return fmt.Sprintf( "{%v -- Target: %v, Limit: %v, Interval: %v, ECM: %v, Flows: %v, Quantum: %v}", fqcodel.Attrs(), fqcodel.Target, fqcodel.Limit, fqcodel.Interval, fqcodel.ECN, fqcodel.Flows, fqcodel.Quantum, ) } func NewFqCodel(attrs QdiscAttrs) *FqCodel { return &FqCodel{ QdiscAttrs: attrs, ECN: 1, } } func (qdisc *FqCodel) Attrs() *QdiscAttrs { return &qdisc.QdiscAttrs } func (qdisc *FqCodel) Type() string { return "fq_codel" } type Sfq struct { QdiscAttrs // TODO: Only the simplified options for SFQ are handled here. Support for the extended one can be added later. Quantum uint8 Perturb uint8 Limit uint32 Divisor uint8 } func (sfq *Sfq) String() string { return fmt.Sprintf( "{%v -- Quantum: %v, Perturb: %v, Limit: %v, Divisor: %v}", sfq.Attrs(), sfq.Quantum, sfq.Perturb, sfq.Limit, sfq.Divisor, ) } func (qdisc *Sfq) Attrs() *QdiscAttrs { return &qdisc.QdiscAttrs } func (qdisc *Sfq) Type() string { return "sfq" }<|fim▁end|>
FlowDefaultRate uint32 FlowMaxRate uint32
<|file_name|>libpath.py<|end_file_name|><|fim▁begin|># coding: utf-8 """Find the path to picasso dynamic library files.""" import os import platform<|fim▁hole|> pass def find_lib_path(): """Find the path to picasso dynamic library files. :return: List of all found library path to picasso :rtype: list(string) """ curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) dll_path = [os.path.join(curr_path, './lib/')] if sys.platform == 'win32': dll_path = [os.path.join(p, 'picasso.dll') for p in dll_path] \ +[os.path.join(p, 'libpicasso.so') for p in dll_path] elif sys.platform.startswith('linux'): dll_path = [os.path.join(p, 'libpicasso.so') for p in dll_path] elif sys.platform == 'darwin': dll_path = [os.path.join(p, 'libpicasso.so') for p in dll_path] \ +[os.path.join(p, 'libpicasso.dylib') for p in dll_path] lib_path = [p for p in dll_path if os.path.exists(p) and os.path.isfile(p)] if not lib_path: print('Library file does not exist. Need to be updated!') return lib_path # From github issues, most of installation errors come from machines w/o compilers if not lib_path and not os.environ.get('PICASSO_BUILD_DOC', False): raise PicassoLibraryNotFound( 'Cannot find Picasso Library in the candidate path, ' + 'did you install compilers and make the project in root path?\n' 'List of candidates:\n' + ('\n'.join(dll_path))) return lib_path<|fim▁end|>
import sys class PicassoLibraryNotFound(Exception): """Error thrown by when picasso is not found"""
<|file_name|>builtin_time_vec_generated_test.go<|end_file_name|><|fim▁begin|>// Copyright 2019 PingCAP, Inc. // // 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, // See the License for the specific language governing permissions and // limitations under the License. // Code generated by go generate in expression/generator; DO NOT EDIT. package expression import ( "math" "testing" . "github.com/pingcap/check" "github.com/pingcap/parser/ast" "github.com/pingcap/parser/mysql" "github.com/pingcap/tidb/types" ) type gener struct { defaultGener } func (g gener) gen() interface{} { result := g.defaultGener.gen() if _, ok := result.(string); ok { dg := newDefaultGener(0, types.ETDuration) d := dg.gen().(types.Duration) if int8(d.Duration)%2 == 0 { d.Fsp = 0 } else { d.Fsp = 1 } result = d.String() } return result } var vecBuiltinTimeGeneratedCases = map[string][]vecExprBenchCase{ ast.AddTime: { // builtinAddDatetimeAndDurationSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDuration}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETDatetime)}, gener{*newDefaultGener(0.2, types.ETDuration)}, }, }, // builtinAddDatetimeAndStringSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETDatetime)}, gener{*newDefaultGener(0.2, types.ETString)}, }, }, // builtinAddDurationAndDurationSig { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDuration}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETDuration)}, gener{*newDefaultGener(0.2, types.ETDuration)}, }, }, // builtinAddDurationAndStringSig { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETDuration)}, gener{*newDefaultGener(0.2, types.ETString)}, }, }, // builtinAddStringAndDurationSig { retEvalType: types.ETString, childrenTypes: []types.EvalType{types.ETString, types.ETDuration}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETString)}, gener{*newDefaultGener(0.2, types.ETDuration)}, }, }, // builtinAddStringAndStringSig { retEvalType: types.ETString, childrenTypes: []types.EvalType{types.ETString, types.ETString}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETString)}, gener{*newDefaultGener(0.2, types.ETString)}, }, }, // builtinAddDateAndDurationSig { retEvalType: types.ETString, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDuration}, childrenFieldTypes: []*types.FieldType{types.NewFieldType(mysql.TypeDate), types.NewFieldType(mysql.TypeDuration)}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETDatetime)}, gener{*newDefaultGener(0.2, types.ETDuration)}, }, }, // builtinAddDateAndStringSig { retEvalType: types.ETString, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString}, childrenFieldTypes: []*types.FieldType{types.NewFieldType(mysql.TypeDate), types.NewFieldType(mysql.TypeString)}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETDatetime)}, gener{*newDefaultGener(0.2, types.ETString)}, }, }, // builtinAddTimeDateTimeNullSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDatetime}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETDatetime)}, gener{*newDefaultGener(0.2, types.ETDatetime)}, }, }, // builtinAddTimeStringNullSig { retEvalType: types.ETString, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDatetime}, childrenFieldTypes: []*types.FieldType{types.NewFieldType(mysql.TypeDate), types.NewFieldType(mysql.TypeDatetime)}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETDatetime)}, gener{*newDefaultGener(0.2, types.ETDatetime)}, }, }, // builtinAddTimeDurationNullSig { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDatetime}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETDuration)}, gener{*newDefaultGener(0.2, types.ETDatetime)}, }, }, }, ast.SubTime: { // builtinSubDatetimeAndDurationSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDuration}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETDatetime)}, gener{*newDefaultGener(0.2, types.ETDuration)}, }, }, // builtinSubDatetimeAndStringSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETDatetime)}, gener{*newDefaultGener(0.2, types.ETString)}, }, }, // builtinSubDurationAndDurationSig { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDuration}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETDuration)}, gener{*newDefaultGener(0.2, types.ETDuration)}, }, }, // builtinSubDurationAndStringSig { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETDuration)}, gener{*newDefaultGener(0.2, types.ETString)}, }, }, // builtinSubStringAndDurationSig { retEvalType: types.ETString, childrenTypes: []types.EvalType{types.ETString, types.ETDuration}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETString)}, gener{*newDefaultGener(0.2, types.ETDuration)}, }, }, // builtinSubStringAndStringSig { retEvalType: types.ETString, childrenTypes: []types.EvalType{types.ETString, types.ETString}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETString)}, gener{*newDefaultGener(0.2, types.ETString)}, }, }, // builtinSubDateAndDurationSig { retEvalType: types.ETString, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDuration}, childrenFieldTypes: []*types.FieldType{types.NewFieldType(mysql.TypeDate), types.NewFieldType(mysql.TypeDuration)}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETDatetime)}, gener{*newDefaultGener(0.2, types.ETDuration)}, }, }, // builtinSubDateAndStringSig { retEvalType: types.ETString, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString}, childrenFieldTypes: []*types.FieldType{types.NewFieldType(mysql.TypeDate), types.NewFieldType(mysql.TypeString)}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETDatetime)}, gener{*newDefaultGener(0.2, types.ETString)}, }, }, // builtinSubTimeDateTimeNullSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDatetime}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETDatetime)}, gener{*newDefaultGener(0.2, types.ETDatetime)}, }, }, // builtinSubTimeStringNullSig { retEvalType: types.ETString, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDatetime}, childrenFieldTypes: []*types.FieldType{types.NewFieldType(mysql.TypeDate), types.NewFieldType(mysql.TypeDatetime)}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETDatetime)}, gener{*newDefaultGener(0.2, types.ETDatetime)}, }, }, // builtinSubTimeDurationNullSig { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDatetime}, geners: []dataGenerator{ gener{*newDefaultGener(0.2, types.ETDuration)}, gener{*newDefaultGener(0.2, types.ETDatetime)}, }, }, }, ast.TimeDiff: { // builtinNullTimeDiffSig {retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDatetime}}, {retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETTimestamp}}, {retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDuration}}, {retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETTimestamp, types.ETDuration}}, // builtinDurationDurationTimeDiffSig {retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDuration}}, // builtinDurationStringTimeDiffSig {retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString}, geners: []dataGenerator{nil, &dateTimeStrGener{Year: 2019, Month: 11, randGen: newDefaultRandGen()}}}, {retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString}, geners: []dataGenerator{nil, &dateTimeStrGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}}}, {retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString}, geners: []dataGenerator{nil, &dateTimeStrGener{Year: 2019, Month: 10, Fsp: 4, randGen: newDefaultRandGen()}}}, // builtinTimeTimeTimeDiffSig {retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDatetime}, geners: []dataGenerator{&dateTimeGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}, &dateTimeGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}}}, {retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDatetime, types.ETTimestamp}, geners: []dataGenerator{&dateTimeGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}, &dateTimeGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}}}, {retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETTimestamp, types.ETTimestamp}, geners: []dataGenerator{&dateTimeGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}, &dateTimeGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}}}, {retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETTimestamp, types.ETDatetime}, geners: []dataGenerator{&dateTimeGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}, &dateTimeGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}}}, // builtinTimeStringTimeDiffSig {retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString}, geners: []dataGenerator{&dateTimeGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}, &dateTimeStrGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}}}, {retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETTimestamp, types.ETString}, geners: []dataGenerator{&dateTimeGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}, &dateTimeStrGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}}}, // builtinStringDurationTimeDiffSig {retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETString, types.ETDuration}, geners: []dataGenerator{&dateTimeStrGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}, nil}}, // builtinStringTimeTimeDiffSig {retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETString, types.ETDatetime}, geners: []dataGenerator{&dateTimeStrGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}, &dateTimeGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}}}, {retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETString, types.ETTimestamp}, geners: []dataGenerator{&dateTimeStrGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}, &dateTimeGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}}}, // builtinStringStringTimeDiffSig {retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETString, types.ETString}, geners: []dataGenerator{&dateTimeStrGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}, &dateTimeStrGener{Year: 2019, Month: 10, randGen: newDefaultRandGen()}}}, }, ast.AddDate: { // builtinAddDateStringStringSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinAddDateStringIntSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinAddDateStringRealSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinAddDateStringDecimalSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinAddDateIntStringSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinAddDateIntIntSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinAddDateIntRealSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinAddDateIntDecimalSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinAddDateDatetimeStringSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinAddDateDatetimeIntSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinAddDateDatetimeRealSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinAddDateDatetimeDecimalSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinAddDateDurationStringSig { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}},<|fim▁hole|> retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinAddDateDurationIntSig { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinAddDateDurationRealSig { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinAddDateDurationDecimalSig { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, }, ast.SubDate: { // builtinSubDateStringStringSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinSubDateStringIntSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinSubDateStringRealSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinSubDateStringDecimalSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateStrGener{NullRation: 0.2, randGen: newDefaultRandGen()}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinSubDateIntStringSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETString, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinSubDateIntIntSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETInt, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinSubDateIntRealSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETReal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinSubDateIntDecimalSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETInt, types.ETDecimal, types.ETString}, geners: []dataGenerator{ &dateTimeIntGener{dateTimeGener: dateTimeGener{randGen: newDefaultRandGen()}, nullRation: 0.2}, newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinSubDateDatetimeStringSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinSubDateDatetimeIntSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinSubDateDatetimeRealSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinSubDateDatetimeDecimalSig { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETDatetime, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDatetime), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinSubDateDurationStringSig { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETString, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), &numStrGener{rangeInt64Gener{math.MinInt32 + 1, math.MaxInt32, newDefaultRandGen()}}, }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinSubDateDurationIntSig { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETInt, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETInt), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinSubDateDurationRealSig { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETReal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETReal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, // builtinSubDateDurationDecimalSig { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("WEEK"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("QUARTER"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("SECOND_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("MINUTE_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("HOUR_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MICROSECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_SECOND"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_MINUTE"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("DAY_HOUR"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, { retEvalType: types.ETDuration, childrenTypes: []types.EvalType{types.ETDuration, types.ETDecimal, types.ETString}, geners: []dataGenerator{ newDefaultGener(0.2, types.ETDuration), newDefaultGener(0.2, types.ETDecimal), }, constants: []*Constant{nil, nil, {Value: types.NewStringDatum("YEAR_MONTH"), RetType: types.NewFieldType(mysql.TypeString)}}, chunkSize: 128, }, }, } func (s *testVectorizeSuite1) TestVectorizedBuiltinTimeEvalOneVecGenerated(c *C) { testVectorizedEvalOneVec(c, vecBuiltinTimeGeneratedCases) } func (s *testVectorizeSuite1) TestVectorizedBuiltinTimeFuncGenerated(c *C) { testVectorizedBuiltinFunc(c, vecBuiltinTimeGeneratedCases) } func BenchmarkVectorizedBuiltinTimeEvalOneVecGenerated(b *testing.B) { benchmarkVectorizedEvalOneVec(b, vecBuiltinTimeGeneratedCases) } func BenchmarkVectorizedBuiltinTimeFuncGenerated(b *testing.B) { benchmarkVectorizedBuiltinFunc(b, vecBuiltinTimeGeneratedCases) }<|fim▁end|>
chunkSize: 128, }, {
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='Unirest', version='1.1.7', author='Mashape', author_email='opensource@mashape.com', packages=['unirest'], url='https://github.com/Mashape/unirest-python', license='LICENSE', description='Simplified, lightweight HTTP client library', install_requires=[<|fim▁hole|> "poster >= 0.8.1" ] )<|fim▁end|>
<|file_name|>AuraSavedData.java<|end_file_name|><|fim▁begin|>package flabs.mods.magitech.aura; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.WorldSavedData; <|fim▁hole|> public static final String nbtName="MagiAura"; public AuraSavedData(String name) { super(name); } @Override public void readFromNBT(NBTTagCompound nbttagcompound) { System.out.println("Reading Aura Data"); } @Override public void writeToNBT(NBTTagCompound nbttagcompound) { System.out.println("Writing Aura Data"); } }<|fim▁end|>
public class AuraSavedData extends WorldSavedData{
<|file_name|>PercentageChanceGeneratorTest.java<|end_file_name|><|fim▁begin|>package uk.org.fyodor.generators; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; import org.junit.Test; import uk.org.fyodor.BaseTest; public class PercentageChanceGeneratorTest extends BaseTest { Multiset<Boolean> results = HashMultiset.create(); @Test public void percentageChances(){ for (int p = 1; p < 100; p++) { Generator<Boolean> percentageChance = RDG.percentageChanceOf(p); for (int i = 0; i < 10000; i++) {<|fim▁hole|> print("True: " + results.count(Boolean.TRUE)); print("False: " + results.count(Boolean.FALSE)); results.clear(); } } }<|fim▁end|>
results.add(percentageChance.next()); } print(p);
<|file_name|>adhoc.py<|end_file_name|><|fim▁begin|># Copyright: (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # Copyright: (c) 2018, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible import constants as C from ansible import context from ansible.cli import CLI from ansible.cli.arguments import optparse_helpers as opt_help from ansible.errors import AnsibleError, AnsibleOptionsError from ansible.executor.task_queue_manager import TaskQueueManager from ansible.module_utils._text import to_text from ansible.parsing.splitter import parse_kv from ansible.playbook import Playbook from ansible.playbook.play import Play from ansible.plugins.loader import get_all_plugin_loaders from ansible.utils.display import Display display = Display() class AdHocCLI(CLI): ''' is an extra-simple tool/framework/API for doing 'remote things'. this command allows you to define and run a single task 'playbook' against a set of hosts ''' def init_parser(self): ''' create an options parser for bin/ansible ''' super(AdHocCLI, self).init_parser(usage='%prog <host-pattern> [options]',<|fim▁hole|> " meta, etc)") opt_help.add_runas_options(self.parser) opt_help.add_inventory_options(self.parser) opt_help.add_async_options(self.parser) opt_help.add_output_options(self.parser) opt_help.add_connect_options(self.parser) opt_help.add_check_options(self.parser) opt_help.add_runtask_options(self.parser) opt_help.add_vault_options(self.parser) opt_help.add_fork_options(self.parser) opt_help.add_module_options(self.parser) opt_help.add_basedir_options(self.parser) # options unique to ansible ad-hoc self.parser.add_option('-a', '--args', dest='module_args', help="module arguments", default=C.DEFAULT_MODULE_ARGS) self.parser.add_option('-m', '--module-name', dest='module_name', help="module name to execute (default=%s)" % C.DEFAULT_MODULE_NAME, default=C.DEFAULT_MODULE_NAME) def post_process_args(self, options, args): '''Post process and validate options for bin/ansible ''' options, args = super(AdHocCLI, self).post_process_args(options, args) if len(args) < 1: raise AnsibleOptionsError("Missing target hosts") elif len(args) > 1: raise AnsibleOptionsError("Extraneous options or arguments") display.verbosity = options.verbosity self.validate_conflicts(options, runas_opts=True, vault_opts=True, fork_opts=True) options = self.normalize_become_options(options) return options, args def _play_ds(self, pattern, async_val, poll): check_raw = context.CLIARGS['module_name'] in ('command', 'win_command', 'shell', 'win_shell', 'script', 'raw') mytask = {'action': {'module': context.CLIARGS['module_name'], 'args': parse_kv(context.CLIARGS['module_args'], check_raw=check_raw)}} # avoid adding to tasks that don't support it, unless set, then give user an error if context.CLIARGS['module_name'] not in ('include_role', 'include_tasks') or any(frozenset((async_val, poll))): mytask['async_val'] = async_val mytask['poll'] = poll return dict( name="Ansible Ad-Hoc", hosts=pattern, gather_facts='no', tasks=[mytask]) def run(self): ''' create and execute the single task playbook ''' super(AdHocCLI, self).run() # only thing left should be host pattern pattern = to_text(context.CLIARGS['args'][0], errors='surrogate_or_strict') sshpass = None becomepass = None (sshpass, becomepass) = self.ask_passwords() passwords = {'conn_pass': sshpass, 'become_pass': becomepass} # dynamically load any plugins get_all_plugin_loaders() loader, inventory, variable_manager = self._play_prereqs() try: hosts = self.get_host_list(inventory, context.CLIARGS['subset'], pattern) except AnsibleError: if context.CLIARGS['subset']: raise else: hosts = [] display.warning("No hosts matched, nothing to do") if context.CLIARGS['listhosts']: display.display(' hosts (%d):' % len(hosts)) for host in hosts: display.display(' %s' % host) return 0 if context.CLIARGS['module_name'] in C.MODULE_REQUIRE_ARGS and not context.CLIARGS['module_args']: err = "No argument passed to %s module" % context.CLIARGS['module_name'] if pattern.endswith(".yml"): err = err + ' (did you mean to run ansible-playbook?)' raise AnsibleOptionsError(err) # Avoid modules that don't work with ad-hoc if context.CLIARGS['module_name'] in ('import_playbook',): raise AnsibleOptionsError("'%s' is not a valid action for ad-hoc commands" % context.CLIARGS['module_name']) play_ds = self._play_ds(pattern, context.CLIARGS['seconds'], context.CLIARGS['poll_interval']) play = Play().load(play_ds, variable_manager=variable_manager, loader=loader) # used in start callback playbook = Playbook(loader) playbook._entries.append(play) playbook._file_name = '__adhoc_playbook__' if self.callback: cb = self.callback elif context.CLIARGS['one_line']: cb = 'oneline' # Respect custom 'stdout_callback' only with enabled 'bin_ansible_callbacks' elif C.DEFAULT_LOAD_CALLBACK_PLUGINS and C.DEFAULT_STDOUT_CALLBACK != 'default': cb = C.DEFAULT_STDOUT_CALLBACK else: cb = 'minimal' run_tree = False if context.CLIARGS['tree']: C.DEFAULT_CALLBACK_WHITELIST.append('tree') C.TREE_DIR = context.CLIARGS['tree'] run_tree = True # now create a task queue manager to execute the play self._tqm = None try: self._tqm = TaskQueueManager( inventory=inventory, variable_manager=variable_manager, loader=loader, passwords=passwords, stdout_callback=cb, run_additional_callbacks=C.DEFAULT_LOAD_CALLBACK_PLUGINS, run_tree=run_tree, forks=context.CLIARGS['forks'], ) self._tqm.send_callback('v2_playbook_on_start', playbook) result = self._tqm.run(play) self._tqm.send_callback('v2_playbook_on_stats', self._tqm._stats) finally: if self._tqm: self._tqm.cleanup() if loader: loader.cleanup_all_tmp_files() return result<|fim▁end|>
desc="Define and run a single task 'playbook' against" " a set of hosts", epilog="Some modules do not make sense in Ad-Hoc (include,"
<|file_name|>request.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import oauth2 # XXX pumazi: factor this out from webob.multidict import MultiDict, NestedMultiDict from webob.request import Request as WebObRequest __all__ = ['Request'] class Request(WebObRequest): """The OAuth version of the WebOb Request. Provides an easier way to obtain OAuth request parameters (e.g. oauth_token) from the WSGI environment.""" def _checks_positive_for_oauth(self, params_var): """Simple check for the presence of OAuth parameters.""" checks = [ p.find('oauth_') >= 0 for p in params_var ] return True in checks @property <|fim▁hole|> auth_header = self.headers['authorization'] # Check that the authorization header is OAuth. if auth_header[:6] == 'OAuth ': auth_header = auth_header.lstrip('OAuth ') try: # Extract the parameters from the header. extracted = oauth2.Request._split_header(auth_header) except: raise Error('Unable to parse OAuth parameters from ' 'the Authorization header.') return extracted @property def str_oauth_POST(self): extracted = {} if self._checks_positive_for_oauth(self.str_POST): extracted = dict([ (k, v,) for k, v in self.str_POST.iteritems() if (k.find('oauth_') >= 0) ]) return extracted @property def str_oauth_GET(self): extracted = {} if self._checks_positive_for_oauth(self.str_GET): extracted = dict([ (k, v,) for k, v in self.str_GET.iteritems() if (k.find('oauth_') >= 0) ]) return extracted def params(self): params = WebObRequest.params.fget(self) return NestedMultiDict(params, self.str_oauth_header) params = property(params, doc=WebObRequest.params.__doc__) @property def oauth_params(self): """Simple way to get the OAuth parameters without sifting through the entire stack of parameters. We check the header first, because it is low hanging fruit. However, it would be more efficient to check for the POSTed parameters, because the specification defines the POST method as the recommended request type before using GET or the Authorization header.""" extracted = {} # OAuth in the Header extracted.update(self.str_oauth_header) # OAuth in a GET or POST method extracted.update(self.str_oauth_GET) extracted.update(self.str_oauth_POST) # Return the extracted oauth variables return MultiDict(extracted) @property def nonoauth_params(self): """Simple way to get the non-OAuth parameters from the request.""" oauth_param_keys = self.oauth_params.keys() return dict([(k, v) for k, v in self.params.iteritems() if k not in oauth_param_keys])<|fim▁end|>
def str_oauth_header(self): extracted = {} # Check for OAuth in the Header if 'authorization' in self.headers:
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------- # Copyright (c) Microsoft. All rights reserved. # # 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. #-------------------------------------------------------------------------- class HTTPError(Exception): ''' Represents an HTTP Exception when response status code >= 300. :ivar int status: the status code of the response :ivar str message: the message :ivar list headers: the returned headers, as a list of (name, value) pairs :ivar bytes body: the body of the response ''' def __init__(self, status, message, respheader, respbody): self.status = status self.respheader = respheader self.respbody = respbody Exception.__init__(self, message) class HTTPResponse(object): ''' Represents a response from an HTTP request. :ivar int status: the status code of the response :ivar str message: the message :ivar dict headers: the returned headers :ivar bytes body: the body of the response ''' def __init__(self, status, message, headers, body): self.status = status self.message = message self.headers = headers self.body = body class HTTPRequest(object): ''' Represents an HTTP Request. :ivar str host: the host name to connect to :ivar str method: the method to use to connect (string such as GET, POST, PUT, etc.) :ivar str path: the uri fragment :ivar dict query: query parameters :ivar dict headers: header values :ivar bytes body: the body of the request. ''' def __init__(self): self.host = ''<|fim▁hole|> self.method = '' self.path = '' self.query = {} # list of (name, value) self.headers = {} # list of (header name, header value) self.body = ''<|fim▁end|>
<|file_name|>test_Goulib_interval.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # coding: utf8 from nose.tools import assert_equal from nose import SkipTest #lines above are inserted automatically by pythoscope. Line below overrides them from Goulib.tests import * from Goulib.interval import * class TestInInterval: def test_in_interval(self): assert_equal(in_interval([1,2], 1),True) assert_equal(in_interval([2,1], 1),True) #interval might be unordered assert_equal(in_interval((2,1), 1),True) #or defined by a tuple assert_equal(in_interval([1,2], 2,closed=True),True) assert_equal(in_interval([1,2], 2,closed=False),False) class TestIntersect: def test_intersect(self): assert_equal(intersect([1,3],[2,4]),True) assert_equal(intersect([3,1],(4,2)),True) assert_equal(intersect((1,2),[2,4]),False) assert_equal(intersect((5,1),(2,3)),True) class TestIntersection: def test_intersection(self): assert_equal(intersection([1,3],(4,2)),(2,3)) assert_equal(intersection([1,5],(3,2)),(2,3)) assert_equal(intersection((1,2),[2,4]),(2,2)) assert_equal(intersection((1,2),[3,4]),None) class TestIntersectlen: def test_intersectlen(self): assert_equal(intersectlen([1,5],(3,2)),1) assert_equal(intersectlen((1,2),[2,4]),0) assert_equal(intersectlen((1,2),[3,4],None),None) class TestInterval: @classmethod def setup_class(self): self.none = Interval(None,None) #required for Box, equivalent t self.i12 = Interval(1,2) self.i13 = Interval(1,3) self.i23 = Interval(2,3) self.i24 = Interval(2,4) self.i25 = Interval(5,2) assert_equal(self.i25,Interval(2,5)) #check order self.i33 = Interval(3,3) #empty self.i34 = Interval(3,4) def test___init__(self): pass #tested above def test___repr__(self): assert_equal(repr(self.i12),'[1,2)') def test___str__(self): assert_equal(str(self.i12),'[1,2)') def test___hash__(self): """test that we can use an Interval as key in a dict and retrieve it with a different Interval with same values""" dict={} dict[self.i12]=self.i12 assert_equal(dict[Interval(2,1)],self.i12) def test___lt__(self): assert_equal(self.i12<self.i34,True) assert_equal(self.i12>self.i34,False) def test___contains__(self): assert_true(2 in self.i13) assert_false(3 in self.i13) def test_empty(self): assert_true(self.i33.empty()) assert_false(self.i13.empty()) def test_hull(self): assert_equal(self.i12.hull(self.i34),Interval(1,4)) def test_intersection(self): assert_equal(self.i12.intersection(self.i34),None) assert_equal(self.i13.intersection(self.i25),self.i23) assert_equal(self.i25.intersection(self.i13),self.i23) def test_overlap(self): assert_false(Interval(1,2).overlap(Interval(3,4))) assert_true(Interval(1,3).overlap(Interval(2,5))) def test_separation(self): assert_equal(self.i12.separation(self.i23),0) assert_equal(self.i12.separation(self.i34),3-2) assert_equal(self.i34.separation(self.i12),3-2) def test_subset(self): assert_true(Interval(1,3).subset(Interval(1,3))) assert_false(Interval(1,3).subset(Interval(1,2))) assert_false(Interval(2,3).subset(Interval(1,2))) def test_proper_subset(self): assert_false(Interval(1,3).proper_subset(Interval(1,3))) eps=1E-12 assert_true(Interval(1,3).proper_subset(Interval(1-eps,3+eps))) def test_singleton(self): assert_true(Interval(1,2).singleton()) assert_false(Interval(1,3).singleton()) def test___add__(self): assert_equal(Interval(1,3)+Interval(2,4),Interval(1,4)) i24=Interval(2,3)+Interval(3,4) assert_equal(i24,self.i24) assert_equal(Interval(4,5)+Interval(2,3),Intervals([Interval(4,5),Interval(2,3)])) a=Interval(5,6)+Interval(2,3) a+=Interval(3,4) b=Intervals([Interval(5,6),Interval(2,4)]) assert_equal(a,b) def test___eq__(self): pass #tested in other tests... def test___iadd__(self): pass #tested in other tests... def test_center(self): pass #tested in other tests... def test_size(self): pass #tested in other tests... def test___call__(self): # interval = Interval(start, end) # assert_equal(expected, interval.__call__()) raise SkipTest def test___nonzero__(self): # interval = Interval(start, end) # assert_equal(expected, interval.__nonzero__()) raise SkipTest class TestIntervals: @classmethod def setup_class(self): i12 = Interval(1,2) i13 = Interval(1,3) i24 = Interval(2,4) i56 = Interval(5,6) self.intervals=Intervals([i24,i13,i12,i56]) assert_equal(str(self.intervals),'[[1,4), [5,6)]') def test___init__(self): pass #tested above def test___call__(self): assert_equal(self.intervals(2),Interval(1,4)) assert_equal(self.intervals(4),None) assert_equal(self.intervals(5),Interval(5,6)) def test_insert(self): pass #tested above def test_extend(self): pass #tested above def test___add__(self): i=self.intervals+Interval(-1,-3) assert_equal(str(i),'[[-3,-1), [1,4), [5,6)]') def test___iadd__(self): i=Intervals(self.intervals) i+=Interval(-1,-3) assert_equal(str(i),'[[-3,-1), [1,4), [5,6)]') def test___repr__(self): # intervals = Intervals() # assert_equal(expected, intervals.__repr__()) raise SkipTest class TestBox: @classmethod def setup_class(self): self.empty=Box(2) self.unit=Box(Interval(0,1),Interval(0,1)) self.box=Box((-1,4),[3,-2]) self.copy=Box(self.box) assert_equal(self.box,self.copy) def test___init__(self): pass #tested in setup_class def test___repr__(self): assert_equal(repr(self.box),'[[-1,3), [-2,4)]') def test_min(self): assert_equal(self.unit.min, (0,0)) assert_equal(self.box.min, (-1,-2)) def test_max(self): assert_equal(self.unit.max, (1,1)) assert_equal(self.box.max, (3,4)) def test_size(self): assert_equal(self.box.size, (4,6)) def test_center(self): assert_equal(self.box.center, (1,1)) def test___add__(self): box=self.unit+(2,0) assert_equal(repr(box),'[[0,2), [0,1)]') box=box+Box((-2,-1),(.5,.5)) assert_equal(repr(box),'[[-2,2), [-1,1)]') def test___iadd__(self): box=Box(self.unit) box+=(2,0) assert_equal(repr(box),'[[0,2), [0,1)]') box+=Box((-2,-1),(.5,.5)) assert_equal(repr(box),'[[-2,2), [-1,1)]') def test_end(self): pass #tested in other tests... def test_start(self): pass #tested in other tests... def test___contains__(self): # box = Box(*args) # assert_equal(expected, box.__contains__(other)) raise SkipTest def test___nonzero__(self): # box = Box(*args) # assert_equal(expected, box.__nonzero__()) raise SkipTest def test_empty(self): # box = Box(*args) # assert_equal(expected, box.empty()) raise SkipTest def test_corner(self): # box = Box(*args) <|fim▁hole|> # assert_equal(expected, box.corner(n)) raise SkipTest def test___call__(self): # box = Box(*args) # assert_equal(expected, box.__call__()) raise SkipTest if __name__ == "__main__": runmodule()<|fim▁end|>
<|file_name|>Test_CCopasiObject.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual # Properties, Inc., University of Heidelberg, and University of # of Connecticut School of Medicine. # All rights reserved. # Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual # Properties, Inc., University of Heidelberg, and The University # of Manchester. # All rights reserved. # Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual # Properties, Inc., EML Research, gGmbH, University of Heidelberg, # and The University of Manchester. # All rights reserved. # Copyright (C) 2006 - 2007 by Pedro Mendes, Virginia Tech Intellectual # Properties, Inc. and EML Research, gGmbH. # All rights reserved. import COPASI import unittest from types import * class Test_CDataObject(unittest.TestCase): def setUp(self): self.datamodel=COPASI.CRootContainer.addDatamodel() self.model=self.datamodel.getModel() self.compartment=self.model.createCompartment("Comp1") self.object=self.model.createMetabolite("Metab1","Comp1") self.model.compileIfNecessary() def test_getObjectName(self): t=self.object.getObjectName() self.assert_(type(t)==StringType) def test_setObjectName(self): NAME="MyObject" self.object.setObjectName(NAME) self.assert_(self.object.getObjectName()==NAME) def test_getObjectDisplayName(self): t=self.object.getObjectDisplayName() self.assert_(type(t)==StringType) def test_getObjectType(self): t=self.object.getObjectType() self.assert_(type(t)==StringType) def test_getObjectParent(self): parent=self.object.getObjectParent() self.assert_(parent!=None) self.assert_(parent.__class__==COPASI.MetabVectorNS) self.assert_(parent.getKey()==self.compartment.getMetabolites().getKey()) def test_getCN(self): cn=self.object.getCN() self.assert_(cn.__class__==COPASI.CCommonName) def test_isContainer(self): result=self.object.isContainer() self.assert_(type(result)==BooleanType) def test_isVector(self): result=self.object.isVector() self.assert_(type(result)==BooleanType) def test_isMatrix(self): result=self.object.isMatrix() self.assert_(type(result)==BooleanType) def test_isNameVector(self): result=self.object.isNameVector() self.assert_(type(result)==BooleanType) def test_isReference(self): result=self.object.isReference() self.assert_(type(result)==BooleanType) def test_isValueBool(self): result=self.object.isValueBool() self.assert_(type(result)==BooleanType) def test_isValueInt(self): result=self.object.isValueInt() self.assert_(type(result)==BooleanType) def test_isValueDbl(self): result=self.object.isValueDbl() self.assert_(type(result)==BooleanType) def test_isNonUniqueName(self): result=self.object.isNonUniqueName() self.assert_(type(result)==BooleanType) def test_isStaticString(self): result=self.object.isStaticString() self.assert_(type(result)==BooleanType) def test_isValueString(self): result=self.object.isValueString() self.assert_(type(result)==BooleanType) def test_isSeparator(self): result=self.object.isSeparator() self.assert_(type(result)==BooleanType) def test_getKey(self): key=self.object.getKey() self.assert_(type(key)==StringType) def suite(): tests=[ 'test_getObjectName' ,'test_setObjectName' ,'test_getObjectDisplayName' ,'test_getObjectType' ,'test_getObjectParent' ,'test_getCN' ,'test_isContainer' ,'test_isVector' ,'test_isMatrix' ,'test_isNameVector' ,'test_isReference' ,'test_isValueBool' ,'test_isValueInt' ,'test_isValueDbl' ,'test_isNonUniqueName' ,'test_isStaticString' ,'test_isValueString' ,'test_isSeparator' ,'test_getKey'<|fim▁hole|> return unittest.TestSuite(map(Test_CDataObject,tests)) if(__name__ == '__main__'): unittest.TextTestRunner(verbosity=2).run(suite())<|fim▁end|>
]
<|file_name|>sepp2_test.py<|end_file_name|><|fim▁begin|>from .helper import * import open_cp.gui.predictors.sepp2 as sepp2 import open_cp.gui.predictors.predictor #import datetime @pytest.fixture def analysis_model2(analysis_model): analysis_model.time_range = (datetime.datetime(2017,5,21,12,30), datetime.datetime(2017,5,21,13,30), None, None) return analysis_model<|fim▁hole|> @mock.patch("open_cp.seppexp") def test_SEPP(seppmock, model, project_task, analysis_model2, grid_task): provider = sepp2.SEPP(model) assert provider.name == "Grid based SEPP" assert provider.settings_string is None standard_calls(provider, project_task, analysis_model2, grid_task) def test_serialise(model, project_task, analysis_model2, grid_task): serialise( sepp2.SEPP(model) ) def test_no_data(model, project_task, analysis_model, grid_task): analysis_model.time_range = (datetime.datetime(2017,5,20,12,30), datetime.datetime(2017,5,20,13,30), None, None) provider = sepp2.SEPP(model) with pytest.raises(open_cp.gui.predictors.predictor.PredictionError): standard_calls(provider, project_task, analysis_model, grid_task) @mock.patch("open_cp.seppexp") def test_training_usage(seppmock, model, project_task, analysis_model2, grid_task): provider = sepp2.SEPP(model) subtask = standard_calls(provider, project_task, analysis_model2, grid_task) seppmock.SEPPTrainer.assert_called_with(grid=grid_task.return_value) trainer_mock = seppmock.SEPPTrainer.return_value np.testing.assert_allclose(trainer_mock.data.xcoords, [0, 10]) np.testing.assert_allclose(trainer_mock.data.ycoords, [10, 20]) time_diffs = ( (trainer_mock.data.timestamps - [np.datetime64("2017-05-21T12:30"), np.datetime64("2017-05-21T13:00")]) / np.timedelta64(1,"ms") ) np.testing.assert_allclose(time_diffs, [0,0]) trainer_mock.train.assert_called_with(iterations=40, use_corrected=True) pred = trainer_mock.train.return_value np.testing.assert_allclose(pred.data.xcoords, [0, 10, 20]) np.testing.assert_allclose(pred.data.ycoords, [10, 20, 0]) train_date = datetime.datetime(2017,5,22,5,35) prediction = subtask(train_date) assert prediction == pred.predict.return_value pred.predict.assert_called_with(train_date)<|fim▁end|>
<|file_name|>dev-server.ts<|end_file_name|><|fim▁begin|>import express, { Router } from 'express'; import { Builder, logConfig, Options } from '@storybook/core-common'; import { getMiddleware } from './utils/middleware'; import { getServerAddresses } from './utils/server-address'; import { getServer } from './utils/server-init'; import { useStatics } from './utils/server-statics'; import * as managerBuilder from './manager/builder'; import { openInBrowser } from './utils/open-in-browser'; import { getPreviewBuilder } from './utils/get-preview-builder'; // @ts-ignore export const router: Router = new Router(); export async function storybookDevServer(options: Options) { const startTime = process.hrtime(); const app = express(); const server = await getServer(app, options); if (typeof options.extendServer === 'function') { options.extendServer(server); } app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); }); // User's own static files await useStatics(router, options); <|fim▁hole|> const { port, host } = options; const proto = options.https ? 'https' : 'http'; const { address, networkAddress } = getServerAddresses(port, host, proto); await new Promise<void>((resolve, reject) => { // FIXME: Following line doesn't match TypeScript signature at all 🤔 // @ts-ignore server.listen({ port, host }, (error: Error) => (error ? reject(error) : resolve())); }); const previewBuilder: Builder<unknown, unknown> = await getPreviewBuilder(options.configDir); if (options.debugWebpack) { logConfig('Preview webpack config', await previewBuilder.getConfig(options)); logConfig('Manager webpack config', await managerBuilder.getConfig(options)); } const preview = options.ignorePreview ? Promise.resolve() : previewBuilder.start({ startTime, options, router, }); const manager = managerBuilder.start({ startTime, options, router, }); const [previewResult, managerResult] = await Promise.all([ preview, manager // TODO #13083 Restore this when compiling the preview is fast enough // .then((result) => { // if (!options.ci && !options.smokeTest) openInBrowser(address); // return result; // }) .catch(previewBuilder.bail), ]); // TODO #13083 Remove this when compiling the preview is fast enough if (!options.ci && !options.smokeTest) openInBrowser(host ? networkAddress : address); return { previewResult, managerResult, address, networkAddress }; }<|fim▁end|>
getMiddleware(options.configDir)(router); app.use(router);
<|file_name|>WhileDirective.java<|end_file_name|><|fim▁begin|>package org.reasm.m68k.assembly.internal; import javax.annotation.Nonnull; import javax.annotation.concurrent.Immutable; import org.reasm.Value; import org.reasm.ValueToBooleanVisitor; /** * The <code>WHILE</code> directive. * * @author Francis Gagné */ @Immutable class WhileDirective extends Mnemonic { @Nonnull static final WhileDirective WHILE = new WhileDirective(); private WhileDirective() { } @Override void assemble(M68KAssemblyContext context) { context.sizeNotAllowed(); final Object blockState = context.getParentBlock(); if (!(blockState instanceof WhileBlockState)) { throw new AssertionError(); } final WhileBlockState whileBlockState = (WhileBlockState) blockState; // The WHILE directive is assembled on every iteration. // Parse the condition operand on the first iteration only. if (!whileBlockState.parsedCondition) { if (context.requireNumberOfOperands(1)) { whileBlockState.conditionExpression = parseExpressionOperand(context, 0); } whileBlockState.parsedCondition = true; }<|fim▁hole|> final Value condition; if (whileBlockState.conditionExpression != null) { condition = whileBlockState.conditionExpression.evaluate(context.getEvaluationContext()); } else { condition = null; } final Boolean result = Value.accept(condition, ValueToBooleanVisitor.INSTANCE); if (!(result != null && result.booleanValue())) { // Skip the block body and stop the iteration. whileBlockState.iterator.next(); whileBlockState.hasNextIteration = false; } } }<|fim▁end|>
<|file_name|>inner-static.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or<|fim▁hole|>// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:inner_static.rs extern crate inner_static; pub fn main() { let a = inner_static::A::<()> { v: () }; let b = inner_static::B::<()> { v: () }; let c = inner_static::test::A::<()> { v: () }; assert_eq!(a.bar(), 2); assert_eq!(b.bar(), 4); assert_eq!(c.bar(), 6); }<|fim▁end|>
<|file_name|>uicommon.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
def emptyLayout(layout): for i in reversed(range(layout.count())): layout.itemAt(i).widget().setParent(None)
<|file_name|>read.js<|end_file_name|><|fim▁begin|>/* @flow */ 'use strict'<|fim▁hole|> const projectMeta = require('../utils/project-meta.js') const values = require('../values.js') function readCors ( cwd /* : string */ ) /* : Promise<CorsConfiguration | false> */ { return projectMeta.read(cwd) .then((config) => { // Want to support two options here: // 1. Falsey to disable CORS if (!config.server || !config.server.cors) { return false } // 2. Truthy to use default CORS and merge in any custom stuff return Object.assign({ credentials: values.DEFAULT_CORS.CREDENTIALS, exposedHeaders: values.DEFAULT_CORS.EXPOSED_HEADERS, headers: values.DEFAULT_CORS.HEADERS, maxAge: values.DEFAULT_CORS.MAX_AGE, origins: values.DEFAULT_CORS.ORIGINS }, typeof config.server.cors === 'boolean' ? {} : config.server.cors) }) } module.exports = readCors<|fim▁end|>
/* :: import type {CorsConfiguration} from '../../types.js' */
<|file_name|>groups.js<|end_file_name|><|fim▁begin|>// // Webble World 3.0 (IntelligentPad system for the web) // // Copyright (c) 2010-2015 Micke Nicander Kuwahara, Giannis Georgalis, Yuzuru Tanaka // in Meme Media R&D Group of Hokkaido University, Japan. All rights reserved. // // 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. // // Additional restrictions may apply. See the LICENSE file for more information. // 'use strict'; /** * Group management controller that drives the view groups.html * * @author Giannis Georgalis <jgeorgal@meme.hokudai.ac.jp> */ ww3Controllers.controller('GroupsCtrl', ['$scope', '$http', 'gettext', 'authService', 'confirm', 'Users', 'UserAccounts', function ($scope, $http, gettext, authService, confirm, Users, UserAccounts) { //////////////////////////////////////////////////////////////////// // Utility functions // function gToF(g) { // Group to formatted visible value (f) if (g.readonly) { return '<i style="color: #b0b8c5;">' + g.name + '</i>'; } else return g.name;<|fim▁hole|> return [{ v: g.id, f: gToF(g) }, g.parent_id, g.description]; } function gsToData(gs) { var rows = [ ['Name', 'Parent Group', 'Tooltip'] ]; // cols gs.forEach(function(g) { rows.push(gToRow(g)); }); return rows; } //****************************************************************** function generateChartData(groupsArray, myGroupsArray) { if (myGroupsArray) { var myGroupsById = {}; for (var i = 0; i < myGroupsArray.length; ++i) myGroupsById[myGroupsArray[i].id] = myGroupsArray[i]; for (i = 0; i < groupsArray.length; ++i) { if (!myGroupsById.hasOwnProperty(groupsArray[i].id)) groupsArray[i].readonly = true; } } return gsToData(groupsArray); // Regenerate if necessary } //****************************************************************** function refreshAllGroups() { return $http.get('/api/groups').then(function(resp) { $scope.groups = resp.data; $scope.chartData = generateChartData($scope.groups, $scope.myGroups); }); } //////////////////////////////////////////////////////////////////// // Scope properties & initialization // /* $scope.users = Users.query(); $scope.userAccounts = UserAccounts.query(); */ $scope.tabs = {}; $scope.editable = $scope.user && $scope.user.role === 'adm'; $scope.groups = []; $scope.alerts = []; refreshAllGroups(); $scope.selectedGroup = null; $scope.selectedGroupEdit = false; if (!$scope.editable) { $http.get('/api/mygroups').then(function (resp) { $scope.myGroups = resp.data; if ($scope.myGroups.length > 0) { $scope.editable = true; if ($scope.groups) // Regenerate chart data if necessary $scope.chartData = generateChartData($scope.groups, $scope.myGroups); } }); } $scope.groupData = {}; // Available publication policies // $scope.availablePolicies = [ { enum: 'open', name: gettext("Open for publications"), help: gettext("Members can publish and update freely under this group") }, { enum: 'moderate_new', name: gettext("Moderate new publications"), help: gettext("Members can update freely but new publications require the group owner's approval") }, { enum: 'moderate_updates', name: gettext("Moderate all updates"), help: gettext("All new publications and updates (by members) under this group require the owner's approval") }, { enum: 'closed', name: gettext("Closed for publications"), help: gettext("All publications and updates under this group are suspended") } ]; $scope.availablePoliciesById = { open: $scope.availablePolicies[0], moderate_new: $scope.availablePolicies[1], moderate_updates: $scope.availablePolicies[2], closed: $scope.availablePolicies[3] }; //////////////////////////////////////////////////////////////////// // Public scope functions // $scope.closeAlert = function (index) { $scope.alerts.splice(index, 1); }; $scope.getUsers = function(q) { var url = $scope.user.role !== 'adm' ? '/api/users?limit=20&q=' : '/api/adm/users?limit=20&q='; return $http.get(url + encodeURIComponent(q)).then(function(resp){ return resp.data; }); }; //****************************************************************** $scope.createGroup = function() { var url = $scope.groupData.subgroup && $scope.selectedGroup && $scope.selectedGroup.id ? '/api/groups/' + $scope.selectedGroup.id : '/api/groups'; return $http.post(url, { group: $scope.groupData, owner: $scope.groupData.owner && $scope.groupData.owner.email }).then(function (resp) { var g = resp.data; $scope.groups.push(g); if ($scope.chartData) $scope.chartData.push(gToRow(g)); $scope.onGroupSelected(null); $scope.alerts.push({ type: 'success', msg: gettext("Created Group") + ": " + g.name }); }, function (err) { $scope.alerts.push({ type: 'danger', msg: err.data }); }); }; $scope.modifySelectedGroup = function() { return $http.put('/api/groups/' + $scope.selectedGroup.id, { group: $scope.groupData, owner: ($scope.groupData.owner && $scope.groupData.owner.email) || undefined }).then(function(resp) { var g = resp.data; for (var i = 0; i < $scope.groups.length; ++i) { if ($scope.groups[i].id == g.id) { $scope.groups[i] = g; break; } } $scope.chartData = gsToData($scope.groups); $scope.onGroupSelected(null); }, function(err) { $scope.alerts.push({ type: 'danger', msg: err.data }); }); }; $scope.createOrModifyGroup = function() { return $scope.selectedGroupEdit ? $scope.modifySelectedGroup() : $scope.createGroup(); }; $scope.deleteGroup = function() { if ($scope.selectedGroup && $scope.selectedGroup.id) { confirm.show(gettext("Delete Group:") + " " + $scope.selectedGroup.name, gettext("If you confirm, any subgroups will be transfered to the parent group and the group's reference will be revoked from all its published objects"), gettext("Delete Group"), gettext("Do Not Delete Group")).then(function () { $http.delete('/api/groups/' + $scope.selectedGroup.id).then(function() { refreshAllGroups().then(function() { // Group deletion may affect other groups also $scope.onGroupSelected(null); $scope.alerts.push({ type: 'success', msg: gettext("Deleted Group") + ": " + g.name }); }); }, function (err) { $scope.alerts.push({ type: 'danger', msg: err.data }); }); }); } }; $scope.retrievePublishedObjects = function() { $http.get('/api/groups/' + $scope.selectedGroup.id + '/objects').then(function(resp) { $scope.publishedObjects = resp.data; }); }; $scope.deauthorizePublishedObject = function(obj, index) { confirm.show(gettext("Deauthorize Object:") + " " + obj.repr, gettext("If you confirm, the selected object will no longer be member of the group."), gettext("Deauthorize"), gettext("Do Not Deauthorize")).then(function () { $http.put('/api/groups/' + $scope.selectedGroup.id + '/objects', { obj: obj.id, remove: true }).then(function() { $scope.publishedObjects.splice(index, 1); }, function (err) { $scope.alerts.push({ type: 'danger', msg: err.data }); }); }); }; //****************************************************************** $scope.onGroupSelected = function(selectedItem) { $scope.publishedObjects = null; // Clear the publihsed object list in any case if (selectedItem) { for (var i = 0; i < $scope.groups.length; ++i) { if ($scope.groups[i].id == selectedItem) { $scope.selectedGroup = $scope.groups[i]; if ($scope.selectedGroup.readonly) $scope.tabs.info = true; else if ($scope.selectedGroupEdit) $scope.groupData = angular.copy($scope.selectedGroup); break; } } } else { $scope.groupData = {}; $scope.selectedGroup = null; $scope.selectedGroupEdit = false; // Jump to info tab $scope.tabs.info = true; } }; $scope.toggleSelectedGroupEdit = function() { if (!$scope.selectedGroupEdit && $scope.selectedGroup && $scope.selectedGroup.id) { $scope.groupData = angular.copy($scope.selectedGroup); $scope.selectedGroupEdit = true; } else { $scope.groupData = {}; $scope.selectedGroupEdit = false; } }; $scope.addUserToGroup = function(user, group) { if (user && user.email && group && group.id) { //console.log("FAKE ADDING USER: ", user.name.full, "TO GROUP:", group.name); $http.put('/api/groups/' + group.id + '/users', { user: user.email || user.username }) .then(function (resp) { $scope.alerts.push({ type: 'success', msg: gettext("User added to group") + ": " + group.name }); }, function (err) { $scope.alerts.push({ type: 'danger', msg: err.data }); }); } }; //****************************************************************** }]);<|fim▁end|>
} function gToRow(g) {
<|file_name|>cl_DF_digits.cc<|end_file_name|><|fim▁begin|>// float_digits(). // General includes. #include "base/cl_sysdep.h" // Specification. #include "cln/dfloat.h"<|fim▁hole|>// Implementation. #include "float/dfloat/cl_DF.h" namespace cln { CL_INLINE uintC CL_INLINE_DECL(float_digits) (const cl_DF& x) { unused x; return DF_mant_len+1; // 53 } } // namespace cln<|fim▁end|>
<|file_name|>composed.js<|end_file_name|><|fim▁begin|>import { createStore } from 'redux' import { combineReducers } from 'redux';<|fim▁hole|> todos: todoReducer, app: appReducer }) export const store = createStore(todoApp); store.getState() // outputs -> // { // todos: { // todos: [] // }, // app: { // settingsVisible: false, // ... // } // }<|fim▁end|>
import { todoReducer } from '../todo-reducer'; import { appReducer } from '../app-reducer'; const todoApp = combineReducers({
<|file_name|>py_choose.hpp<|end_file_name|><|fim▁begin|>#ifndef __PY_CHOOSE__ #define __PY_CHOOSE__ //--------------------------------------------------------------------------- //<inline(py_choose)> //--------------------------------------------------------------------------- uint32 idaapi choose_sizer(void *self) { PYW_GIL_GET; newref_t pyres(PyObject_CallMethod((PyObject *)self, "sizer", "")); return PyInt_AsLong(pyres.o); } //--------------------------------------------------------------------------- char *idaapi choose_getl(void *self, uint32 n, char *buf) { PYW_GIL_GET; newref_t pyres( PyObject_CallMethod( (PyObject *)self, "getl", "l", n)); const char *res;<|fim▁hole|> qstrncpy(buf, res, MAXSTR); return buf; } //--------------------------------------------------------------------------- void idaapi choose_enter(void *self, uint32 n) { PYW_GIL_GET; newref_t res(PyObject_CallMethod((PyObject *)self, "enter", "l", n)); } //--------------------------------------------------------------------------- uint32 choose_choose( void *self, int flags, int x0,int y0, int x1,int y1, int width, int deflt, int icon) { PYW_GIL_CHECK_LOCKED_SCOPE(); newref_t pytitle(PyObject_GetAttrString((PyObject *)self, "title")); const char *title = pytitle != NULL ? PyString_AsString(pytitle.o) : "Choose"; int r = choose( flags, x0, y0, x1, y1, self, width, choose_sizer, choose_getl, title, icon, deflt, NULL, /* del */ NULL, /* inst */ NULL, /* update */ NULL, /* edit */ choose_enter, NULL, /* destroy */ NULL, /* popup_names */ NULL);/* get_icon */ return r; } //</inline(py_choose)> #endif // __PY_CHOOSE__<|fim▁end|>
if ( pyres == NULL || (res = PyString_AsString(pyres.o)) == NULL ) qstrncpy(buf, "<Empty>", MAXSTR); else
<|file_name|>bind_statement.rs<|end_file_name|><|fim▁begin|>use std::result::Result; use serde_json::*; use super::script::*; use super::bound_script::*; use super::bind_expression::*; use super::binding_environment::*; use super::script_interpreter::*; /// /// Creates an execution error relating to an script statement /// fn generate_statement_error(error: ScriptEvaluationError, script: &Script) -> Value { json![{ "error": error, "failed-statement": script }] } /// /// Binds a sequnce in a script /// fn bind_sequence(sequence: &Vec<Script>, binding_environment: &mut BindingEnvironment) -> Result<Vec<BoundScript>, Value> { let mut result = vec![]; for statement in sequence { result.push(bind_statement_without_allocation(statement, binding_environment)?); } Ok(result) } /// /// Binds a new variable name /// fn bind_variable_name(name: &ScriptToken, script: &Script, binding_environment: &mut BindingEnvironment) -> Result<u32, Value> { let binding = binding_environment.allocate_variable(&name.matched); match binding { Ok(value) => Ok(value), Err(BindingError::AlreadyInUse) => Err(generate_statement_error(ScriptEvaluationError::VariableNameAlreadyInUse, script)) } } /// /// Retrieves an existing variable name /// fn get_variable_name(name: &ScriptToken, script: &Script, binding_environment: &mut BindingEnvironment) -> Result<u32, Value> { let binding = binding_environment.lookup(&name.matched); match binding { BindingResult::Variable(value) => Ok(value), BindingResult::Tool(_) => Err(generate_statement_error(ScriptEvaluationError::WasExpectingAVariable, script)), BindingResult::Error(_) => Err(generate_statement_error(ScriptEvaluationError::VariableNameNotFound, script)) } } /// /// Binds a statement to an environment (does not allocate space for variables) /// fn bind_statement_without_allocation(script: &Script, binding_environment: &mut BindingEnvironment) -> Result<BoundScript, Value> { use self::BoundScript::*; match *script { Script::RunCommand(ref expr) => Ok(RunCommand(bind_expression(expr, binding_environment)?)), Script::Sequence(ref parts) => Ok(Sequence(bind_sequence(parts, binding_environment)?)), Script::Var(ref name, ref expr) => Ok(Var(bind_variable_name(name, script, binding_environment)?, bind_expression(expr, binding_environment)?, name.clone())), Script::Assign(ref name, ref expr) => Ok(Assign(get_variable_name(name, script, binding_environment)?, bind_expression(expr, binding_environment)?, name.clone())), _ => unimplemented!() } } /// /// Binds a statement to an environment /// pub fn bind_statement(script: &Script, binding_environment: &mut BindingEnvironment) -> Result<BoundScript, Value> { use self::BoundScript::*; // We store the initial number of variables so we can see if any allocation is required let initial_variable_count = binding_environment.get_number_of_variables(); // Then bind the statements with no further allocation let bound_script = bind_statement_without_allocation(script, binding_environment)?; // Transform to an allocation script if required let final_variable_count = binding_environment.get_number_of_variables(); if initial_variable_count < final_variable_count { Ok(AllocateVariables(final_variable_count, Box::new(bound_script))) } else { Ok(bound_script) } } #[cfg(test)] mod test { use gossyp_base::basic::*; use super::*;<|fim▁hole|> #[test] fn can_bind_simple_statement() { let string_statement = Script::RunCommand(Expression::string("\"Foo\"")); let empty_environment = EmptyEnvironment::new(); let mut env = BindingEnvironment::from_environment(&empty_environment); let bound = bind_statement(&string_statement, &mut *env); assert!(match bound { Ok(BoundScript::RunCommand(BoundExpression::Value(Value::String(s), _))) => s == "Foo", _ => false }); } #[test] fn can_bind_simple_sequence() { let sequence_statement = Script::Sequence(vec![Script::RunCommand(Expression::string("\"Foo\""))]); let empty_environment = EmptyEnvironment::new(); let mut env = BindingEnvironment::from_environment(&empty_environment); let bound = bind_statement(&sequence_statement, &mut *env); assert!(match bound { Ok(BoundScript::Sequence(_)) => true, _ => false }); } #[test] fn can_bind_var_expression() { let var_statement = Script::Var(ScriptToken::identifier("test"), Expression::number("42")); let empty_environment = EmptyEnvironment::new(); let mut env = BindingEnvironment::from_environment(&empty_environment); let bound = bind_statement(&var_statement, &mut *env); assert!(match bound { Ok(BoundScript::AllocateVariables(1, _)) => true, _ => false }); if let Ok(BoundScript::AllocateVariables(_, boundvar)) = bound { assert!(match *boundvar { BoundScript::Var(0, BoundExpression::Value(_, _), _) => true, _ => false }); } else { assert!(false); } } #[test] fn can_bind_assign_expression() { let assign_statement = Script::Assign(ScriptToken::identifier("test"), Expression::number("42")); let empty_environment = EmptyEnvironment::new(); let mut env = BindingEnvironment::from_environment(&empty_environment); assert!(env.allocate_variable("test") == Ok(0)); let bound = bind_statement(&assign_statement, &mut *env); assert!(bound.is_ok()); assert!(match bound { Ok(BoundScript::Assign(0, BoundExpression::Value(_, _), _)) => true, _ => false }); } }<|fim▁end|>
<|file_name|>upgrade_schema.py<|end_file_name|><|fim▁begin|># ============================================================================== # Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # 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. """Upgrade script to move from pre-release schema to new schema. Usage examples: bazel run tensorflow/lite/schema/upgrade_schema -- in.json out.json bazel run tensorflow/lite/schema/upgrade_schema -- in.bin out.bin bazel run tensorflow/lite/schema/upgrade_schema -- in.bin out.json bazel run tensorflow/lite/schema/upgrade_schema -- in.json out.bin bazel run tensorflow/lite/schema/upgrade_schema -- in.tflite out.tflite """ import argparse import contextlib import json import os import shutil import subprocess import sys import tempfile import tensorflow as tf from tensorflow.python.platform import resource_loader parser = argparse.ArgumentParser( description="Script to move TFLite models from pre-release schema to " "new schema.") parser.add_argument( "input", type=str, help="Input TensorFlow lite file in `.json`, `.bin` or `.tflite` format.") parser.add_argument( "output", type=str, help="Output json or bin TensorFlow lite model compliant with " "the new schema. Extension must be `.json`, `.bin` or `.tflite`.") # RAII Temporary Directory, because flatc doesn't allow direct use of tempfiles. @contextlib.contextmanager def TemporaryDirectoryResource(): temporary = tempfile.mkdtemp() try: yield temporary finally: shutil.rmtree(temporary) class Converter(object): """Converts TensorFlow flatbuffer models from old to new version of schema. This can convert between any version to the latest version. It uses an incremental upgrade strategy to go from version to version. Usage: converter = Converter() converter.Convert("a.tflite", "a.json") converter.Convert("b.json", "b.tflite") """ def __init__(self): # TODO(aselle): make this work in the open source version with better # path. paths_to_try = [ "../../../../flatbuffers/flatc", # not bazel "../../../../external/flatbuffers/flatc" # bazel ] for p in paths_to_try: self._flatc_path = resource_loader.get_path_to_datafile(p) if os.path.exists(self._flatc_path): break def FindSchema(base_name): return resource_loader.get_path_to_datafile("%s" % base_name) # Supported schemas for upgrade. self._schemas = [ (0, FindSchema("schema_v0.fbs"), True, self._Upgrade0To1), (1, FindSchema("schema_v1.fbs"), True, self._Upgrade1To2), (2, FindSchema("schema_v2.fbs"), True, self._Upgrade2To3), (3, FindSchema("schema_v3.fbs"), False, None) # Non-callable by design. ] # Ensure schemas are sorted, and extract latest version and upgrade # dispatch function table. self._schemas.sort() self._new_version, self._new_schema = self._schemas[-1][:2] self._upgrade_dispatch = { version: dispatch for version, unused1, unused2, dispatch in self._schemas} def _Read(self, input_file, schema, raw_binary=False): """Read a tflite model assuming the given flatbuffer schema. If `input_file` is in bin, then we must use flatc to convert the schema from binary to json. Args: input_file: a binary (flatbuffer) or json file to read from. Extension must be `.tflite`, `.bin`, or `.json` for FlatBuffer Binary or FlatBuffer JSON. schema: which schema to use for reading raw_binary: whether to assume raw_binary (versions previous to v3) that lacked file_identifier require this. Raises: RuntimeError: 1. When flatc cannot be invoked. 2. When json file does not exists. ValueError: When the extension is not json or bin. Returns: A dictionary representing the read tflite model. """ raw_binary = ["--raw-binary"] if raw_binary else [] with TemporaryDirectoryResource() as tempdir: basename = os.path.basename(input_file) basename_no_extension, extension = os.path.splitext(basename) if extension in [".bin", ".tflite"]: # Convert to json using flatc returncode = subprocess.call([ self._flatc_path, "-t", "--strict-json", "--defaults-json", ] + raw_binary + ["-o", tempdir, schema, "--", input_file]) if returncode != 0: raise RuntimeError("flatc failed to convert from binary to json.") json_file = os.path.join(tempdir, basename_no_extension + ".json") if not os.path.exists(json_file): raise RuntimeError("Could not find %r" % json_file) elif extension == ".json": json_file = input_file else: raise ValueError("Invalid extension on input file %r" % input_file) return json.load(open(json_file)) def _Write(self, data, output_file): """Output a json or bin version of the flatbuffer model. Args: data: Dict representing the TensorFlow Lite model to write. output_file: filename to write the converted flatbuffer to. (json, tflite, or bin extension is required). Raises: ValueError: When the extension is not json or bin RuntimeError: When flatc fails to convert json data to binary. """ _, extension = os.path.splitext(output_file) with TemporaryDirectoryResource() as tempdir: if extension == ".json": json.dump(data, open(output_file, "w"), sort_keys=True, indent=2) elif extension in [".tflite", ".bin"]: input_json = os.path.join(tempdir, "temp.json") with open(input_json, "w") as fp:<|fim▁hole|> returncode = subprocess.call([ self._flatc_path, "-b", "--defaults-json", "--strict-json", "-o", tempdir, self._new_schema, input_json ]) if returncode != 0: raise RuntimeError("flatc failed to convert upgraded json to binary.") shutil.copy(os.path.join(tempdir, "temp.tflite"), output_file) else: raise ValueError("Invalid extension on output file %r" % output_file) def _Upgrade0To1(self, data): """Upgrade data from Version 0 to Version 1. Changes: Added subgraphs (which contains a subset of formally global entries). Args: data: Dictionary representing the TensorFlow lite data to be upgraded. This will be modified in-place to be an upgraded version. """ subgraph = {} for key_to_promote in ["tensors", "operators", "inputs", "outputs"]: subgraph[key_to_promote] = data[key_to_promote] del data[key_to_promote] data["subgraphs"] = [subgraph] def _Upgrade1To2(self, data): """Upgrade data from Version 1 to Version 2. Changes: Rename operators to Conform to NN API. Args: data: Dictionary representing the TensorFlow lite data to be upgraded. This will be modified in-place to be an upgraded version. Raises: ValueError: Throws when model builtins are numeric rather than symbols. """ def RemapOperator(opcode_name): """Go from old schema op name to new schema op name. Args: opcode_name: String representing the ops (see :schema.fbs). Returns: Converted opcode_name from V1 to V2. """ old_name_to_new_name = { "CONVOLUTION": "CONV_2D", "DEPTHWISE_CONVOLUTION": "DEPTHWISE_CONV_2D", "AVERAGE_POOL": "AVERAGE_POOL_2D", "MAX_POOL": "MAX_POOL_2D", "L2_POOL": "L2_POOL_2D", "SIGMOID": "LOGISTIC", "L2NORM": "L2_NORMALIZATION", "LOCAL_RESPONSE_NORM": "LOCAL_RESPONSE_NORMALIZATION", "Basic_RNN": "RNN", } return (old_name_to_new_name[opcode_name] if opcode_name in old_name_to_new_name else opcode_name) def RemapOperatorType(operator_type): """Remap operator structs from old names to new names. Args: operator_type: String representing the builtin operator data type string. (see :schema.fbs). Raises: ValueError: When the model has consistency problems. Returns: Upgraded builtin operator data type as a string. """ old_to_new = { "PoolOptions": "Pool2DOptions", "DepthwiseConvolutionOptions": "DepthwiseConv2DOptions", "ConvolutionOptions": "Conv2DOptions", "LocalResponseNormOptions": "LocalResponseNormalizationOptions", "BasicRNNOptions": "RNNOptions", } return (old_to_new[operator_type] if operator_type in old_to_new else operator_type) for subgraph in data["subgraphs"]: for ops in subgraph["operators"]: ops["builtin_options_type"] = RemapOperatorType( ops["builtin_options_type"]) # Upgrade the operator codes for operator_code in data["operator_codes"]: # Check if builtin_code is the appropriate string type # use type("") instead of str or unicode. for py2and3 if not isinstance(operator_code["builtin_code"], type(u"")): raise ValueError("builtin_code %r is non-string. this usually means " "your model has consistency problems." % (operator_code["builtin_code"])) operator_code["builtin_code"] = (RemapOperator( operator_code["builtin_code"])) def _Upgrade2To3(self, data): """Upgrade data from Version 2 to Version 3. Changed actual read-only tensor data to be in a buffers table instead of inline with the tensor. Args: data: Dictionary representing the TensorFlow lite data to be upgraded. This will be modified in-place to be an upgraded version. """ buffers = [{"data": []}] # Start with 1 empty buffer for subgraph in data["subgraphs"]: if "tensors" not in subgraph: continue for tensor in subgraph["tensors"]: if "data_buffer" not in tensor: tensor["buffer"] = 0 else: if tensor["data_buffer"]: tensor[u"buffer"] = len(buffers) buffers.append({"data": tensor["data_buffer"]}) else: tensor["buffer"] = 0 del tensor["data_buffer"] data["buffers"] = buffers def _PerformUpgrade(self, data): """Manipulate the `data` (parsed JSON) based on changes in format. This incrementally will upgrade from version to version within data. Args: data: Dictionary representing the TensorFlow data. This will be upgraded in place. """ while data["version"] < self._new_version: self._upgrade_dispatch[data["version"]](data) data["version"] += 1 def Convert(self, input_file, output_file): """Perform schema conversion from input_file to output_file. Args: input_file: Filename of TensorFlow Lite data to convert from. Must be `.json` or `.bin` extension files for JSON or Binary forms of the TensorFlow FlatBuffer schema. output_file: Filename to write to. Extension also must be `.json` or `.bin`. Raises: RuntimeError: Generated when none of the upgrader supported schemas matche the `input_file` data. """ # Read data in each schema (since they are incompatible). Version is # always present. Use the read data that matches the version of the # schema. for version, schema, raw_binary, _ in self._schemas: try: data_candidate = self._Read(input_file, schema, raw_binary) except RuntimeError: continue # Skip and hope another schema works if "version" not in data_candidate: # Assume version 1 if not present. data_candidate["version"] = 1 elif data_candidate["version"] == 0: # Version 0 doesn't exist in wild. data_candidate["version"] = 1 if data_candidate["version"] == version: self._PerformUpgrade(data_candidate) self._Write(data_candidate, output_file) return raise RuntimeError("No schema that the converter understands worked with " "the data file you provided.") def main(argv): del argv Converter().Convert(FLAGS.input, FLAGS.output) if __name__ == "__main__": FLAGS, unparsed = parser.parse_known_args() tf.compat.v1.app.run(main=main, argv=[sys.argv[0]] + unparsed)<|fim▁end|>
json.dump(data, fp, sort_keys=True, indent=2)
<|file_name|>VarTestCase.java<|end_file_name|><|fim▁begin|>package prolog; import junit.framework.TestCase; import nars.tuprolog.Var; public class VarTestCase extends TestCase { public void testIsAtomic() { assertFalse(new Var("X").isAtomic()); } public void testIsAtom() { assertFalse(new Var("X").isAtom()); <|fim▁hole|> } public void testIsCompound() { assertFalse(new Var("X").isCompound()); } }<|fim▁end|>
<|file_name|>output_test.go<|end_file_name|><|fim▁begin|>package command import ( "io/ioutil" "os" "path/filepath" "strings" "testing" "github.com/hashicorp/terraform/terraform" "github.com/mitchellh/cli" ) func TestOutput(t *testing.T) { originalState := &terraform.State{ Modules: []*terraform.ModuleState{ &terraform.ModuleState{ Path: []string{"root"}, Outputs: map[string]string{ "foo": "bar", }, }, }, } statePath := testStateFile(t, originalState) ui := new(cli.MockUi) c := &OutputCommand{ Meta: Meta{ ContextOpts: testCtxConfig(testProvider()), Ui: ui, }, } args := []string{ "-state", statePath, "foo", } if code := c.Run(args); code != 0 { t.Fatalf("bad: \n%s", ui.ErrorWriter.String()) } actual := strings.TrimSpace(ui.OutputWriter.String()) if actual != "bar" { t.Fatalf("bad: %#v", actual) } } func TestOutput_badVar(t *testing.T) { originalState := &terraform.State{ Modules: []*terraform.ModuleState{ &terraform.ModuleState{ Path: []string{"root"}, Outputs: map[string]string{ "foo": "bar", }, }, }, } statePath := testStateFile(t, originalState) ui := new(cli.MockUi) c := &OutputCommand{ Meta: Meta{ ContextOpts: testCtxConfig(testProvider()), Ui: ui, }, } args := []string{ "-state", statePath, "bar", } if code := c.Run(args); code != 1 { t.Fatalf("bad: \n%s", ui.ErrorWriter.String()) } } func TestOutput_blank(t *testing.T) { originalState := &terraform.State{ Modules: []*terraform.ModuleState{ &terraform.ModuleState{ Path: []string{"root"}, Outputs: map[string]string{ "foo": "bar", }, },<|fim▁hole|> statePath := testStateFile(t, originalState) ui := new(cli.MockUi) c := &OutputCommand{ Meta: Meta{ ContextOpts: testCtxConfig(testProvider()), Ui: ui, }, } args := []string{ "-state", statePath, "", } if code := c.Run(args); code != 1 { t.Fatalf("bad: \n%s", ui.ErrorWriter.String()) } } func TestOutput_manyArgs(t *testing.T) { ui := new(cli.MockUi) c := &OutputCommand{ Meta: Meta{ ContextOpts: testCtxConfig(testProvider()), Ui: ui, }, } args := []string{ "bad", "bad", } if code := c.Run(args); code != 1 { t.Fatalf("bad: \n%s", ui.OutputWriter.String()) } } func TestOutput_noArgs(t *testing.T) { ui := new(cli.MockUi) c := &OutputCommand{ Meta: Meta{ ContextOpts: testCtxConfig(testProvider()), Ui: ui, }, } args := []string{} if code := c.Run(args); code != 1 { t.Fatalf("bad: \n%s", ui.OutputWriter.String()) } } func TestOutput_noVars(t *testing.T) { originalState := &terraform.State{ Modules: []*terraform.ModuleState{ &terraform.ModuleState{ Path: []string{"root"}, Outputs: map[string]string{}, }, }, } statePath := testStateFile(t, originalState) ui := new(cli.MockUi) c := &OutputCommand{ Meta: Meta{ ContextOpts: testCtxConfig(testProvider()), Ui: ui, }, } args := []string{ "-state", statePath, "bar", } if code := c.Run(args); code != 1 { t.Fatalf("bad: \n%s", ui.ErrorWriter.String()) } } func TestOutput_stateDefault(t *testing.T) { originalState := &terraform.State{ Modules: []*terraform.ModuleState{ &terraform.ModuleState{ Path: []string{"root"}, Outputs: map[string]string{ "foo": "bar", }, }, }, } // Write the state file in a temporary directory with the // default filename. td, err := ioutil.TempDir("", "tf") if err != nil { t.Fatalf("err: %s", err) } statePath := filepath.Join(td, DefaultStateFilename) f, err := os.Create(statePath) if err != nil { t.Fatalf("err: %s", err) } err = terraform.WriteState(originalState, f) f.Close() if err != nil { t.Fatalf("err: %s", err) } // Change to that directory cwd, err := os.Getwd() if err != nil { t.Fatalf("err: %s", err) } if err := os.Chdir(filepath.Dir(statePath)); err != nil { t.Fatalf("err: %s", err) } defer os.Chdir(cwd) ui := new(cli.MockUi) c := &OutputCommand{ Meta: Meta{ ContextOpts: testCtxConfig(testProvider()), Ui: ui, }, } args := []string{ "foo", } if code := c.Run(args); code != 0 { t.Fatalf("bad: \n%s", ui.ErrorWriter.String()) } actual := strings.TrimSpace(ui.OutputWriter.String()) if actual != "bar" { t.Fatalf("bad: %#v", actual) } }<|fim▁end|>
}, }
<|file_name|>booking.component.ts<|end_file_name|><|fim▁begin|>import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import { ToastsManager } from 'ng2-toastr/ng2-toastr'; import { CalendarEvent, CalendarMonthViewComponent, CalendarDayViewComponent, CalendarMonthViewDay, CalendarEventAction } from 'angular-calendar'; import { NgbModal, NgbDateStruct, NgbTimeStruct } from '@ng-bootstrap/ng-bootstrap'; import * as moment from 'moment'; import * as swal from 'sweetalert2'; import * as jQuery from 'jquery'; import { LocalStorageService } from 'ng2-webstorage'; // tslint:disable-next-line:max-line-length import { BookingModalComponent } from '../../../portal/components/booking-modal/booking-modal.component'; import { BookingService } from '../../../portal/services/booking'; import { RoomService } from '../../../portal/services/room'; interface BookingCalendarEvent extends CalendarEvent { booking: IBooking; } @Component({ // The selector is what angular internally uses // for `document.querySelectorAll(selector)` in our index.html // where, in this case, selector is the string 'booking' selector: 'booking', // <booking></booking> // We need to tell Angular's Dependency Injection which providers are in our app. providers: [ LocalStorageService, BookingService, RoomService ], // Our list of styles in our component. We may add more to compose many styles together styleUrls: ['./booking.style.scss'], // Every Angular template is first compiled by the browser before Angular runs it's compiler templateUrl: './booking.template.pug', encapsulation: ViewEncapsulation.None }) export class AdminBookingComponent implements OnInit { public selectedRoom: IRoom; public rooms: IRoom[]; public viewDate: Date = new Date(); public events: CalendarEvent[]; public dayEvents: CalendarEvent[]; public bookings: IBooking[]; public weekStartsOn: number = 1; public view: string = 'month'; public startHours: number = 8; public endHours: number = 20; public dayModifier: Function; public color: any = { primary: 'blue', secondary: '' }; public timeStruct: NgbTimeStruct; public user: IUser; public roomCols: number; public actions: CalendarEventAction[] = [{ label: `<i class="fa fa-trash"></i>`, onClick: ({ event }: { event: CalendarEvent }): void => { this.removeClick(event); } }]; constructor( private modalService: NgbModal, private roomService: RoomService, private bookingService: BookingService, private toastr: ToastsManager, private storage: LocalStorageService, private router: Router ) { console.log('hello `Booking` component'); this.user = this.storage.retrieve('currentuser'); this.selectedRoom = <IRoom> { id: '' }; this.loadRooms(); let today = new Date(); today.setHours(0, 0, 0, 0); /*this.dayModifier = (day: CalendarMonthViewDay) => { if (day.date < today) { day.cssClass = 'cal-disabled'; } };*/ } public ngOnInit(): void { this.loadBookings(); } public loadBookings(): void { this.bookingService.query({ year: this.viewDate.getFullYear(), month: this.viewDate.getMonth() }) .$observable .subscribe((bookings: IBooking[]) => { this.bookings = bookings.map((item: IBooking) => { item.start_time = moment(item.start_time).toDate(); item.end_time = moment(item.end_time).toDate(); item.days_of_week = item.days_of_week && item.days_of_week.length ? (<string> item.days_of_week).split(',') .map((day: string) => { return parseInt(day, 0); }) : []; return item; }); this.fillEvents(); }); } public daySelect(day: Date): void { this.viewDate = day; this.view = 'room'; }<|fim▁hole|> public timeSelect(event: any, booking?: IBooking): void { let date: Date = event.date; let todaysBookings = this.bookings.filter((b: IBooking) => { return moment(b.start_time).startOf('month').isSame(moment(date).startOf('month')); }); let minTime: moment.Moment = moment(date).hour(this.startHours).minute(0).second(0); let maxTime: moment.Moment = moment(date).hour(this.endHours).minute(0).second(0); todaysBookings.forEach((b: IBooking) => { if ( (moment(b.end_time).isBefore(moment(date)) || moment(b.end_time).isSame(moment(date))) && moment(b.end_time).isAfter(minTime) && (<IRoom> b.room).id === this.selectedRoom.id && (!booking || b.id !== booking.id) ) { minTime = moment(b.end_time); } if ( (moment(b.start_time).isAfter(moment(date)) || moment(b.start_time).isSame(moment(date))) && moment(b.start_time).isBefore(maxTime) && (<IRoom> b.room).id === this.selectedRoom.id && (!booking || b.id !== booking.id) ) { maxTime = moment(b.start_time); } }); this.open(booking, date, this.getTimeStruct(minTime), this.getTimeStruct(maxTime)); } public eventClicked(event: any): void { let booking: IBooking = event.event.booking; this.timeSelect({ date: booking.start_time }, booking); } public selectRoom(room: IRoom): void { this.selectedRoom = room; this.fillDayEvents(); this.view = 'day'; } public removeClick(event: any): void { (<any> swal)({ title: 'Отменить?', // tslint:disable-next-line:max-line-length text: `Вы уверены, что хотите отменить это событие? Вы не сможете восстановить его после удаления!`, type: 'warning', reverseButtons: true, focusCancel: true, showCancelButton: true, buttonsStyling: false, showCloseButton: true, confirmButtonClass: 'btn btn-danger margin-5 d5-init-ripples', confirmButtonText: 'Да, отменить событие!', cancelButtonClass: 'btn btn-default margin-5 d5-init-ripples', cancelButtonText: 'Нет!' }) .then(() => { if (event.booking.periodic) { (<any> swal)({ title: 'Удалить?', // tslint:disable-next-line:max-line-length text: `Вы хотите отменить одно событие или за весь период?`, type: 'warning', reverseButtons: true, focusCancel: true, showCancelButton: true, buttonsStyling: false, showCloseButton: true, confirmButtonClass: 'btn btn-danger margin-5 d5-init-ripples', confirmButtonText: 'Отменить все!', cancelButtonClass: 'btn btn-default margin-5 d5-init-ripples', cancelButtonText: 'Отменить одно!' }) .then(() => { this.removeBooking(event.booking, true); }, () => { this.removeBooking(event.booking, false); }) .catch((<any> swal).noop); } else { this.removeBooking(event.booking, false); } }) .catch((<any> swal).noop); } public disableScroll(): void { $.fn.fullpage.setMouseWheelScrolling(false); } public enableScroll(): void { $.fn.fullpage.setMouseWheelScrolling(true); } private removeBooking(booking: IBooking, removeAll: boolean): void { this.bookingService.delete({ id: booking.id, all: removeAll }) .$observable .subscribe(() => { this.toastr.success(`Вы успешно отменили события!`, ''); this.loadBookings(); }, (error: any) => { let message: string = 'Что-то пошло не так...'; if (error && error.message) { message = error.message; } this.toastr.error(message, 'Oops!'); }); } private loadRooms(): void { this.roomService.query() .$observable .subscribe((rooms: IRoom[]) => { this.rooms = rooms.filter((room: IRoom) => { return room.active === true; }).sort((a: IRoom, b: IRoom) => { return a.order > b.order ? 1 : a.order < b.order ? -1 : 0; }).map((room: IRoom) => { room.description = (room.description || '').replace(/\n/g, '<br />'); return room; }); this.roomCols = Math.ceil(12 / Math.ceil(this.rooms.length / 2)); this.roomCols = this.roomCols === 12 && this.rooms.length > 1 ? 6 : this.roomCols; }); } private open(booking?: IBooking, date?: Date, min?: NgbTimeStruct, max?: NgbTimeStruct) { const modalRef = this.modalService.open(BookingModalComponent); modalRef.componentInstance.booking = booking; modalRef.componentInstance.userId = this.user.id; modalRef.componentInstance.selected = date; modalRef.componentInstance.minTime = min; modalRef.componentInstance.maxTime = max; modalRef.componentInstance.room = this.selectedRoom; modalRef.result.then((bookings: IBooking[]) => { if (bookings && bookings.length) { this.bookings = this.bookings.concat(bookings); this.fillEvents(); } }, () => null); } private getTimeStruct(date: moment.Moment): NgbTimeStruct { return <NgbTimeStruct> { hour: date.hour(), minute: date.minute() }; } private fillEvents(): void { this.events = this.bookings.map((item: IBooking) => { let event: CalendarEvent = { start: item.start_time, end: item.end_time, title: item.user.lastname + ' ' + item.user.firstname + ' ' + (<IRoom> item.room).name + ' ' + moment(item.start_time).format('HH:mm') + ' - ' + moment(item.end_time).format('HH:mm') + ' ' + item.title, color: { primary: this.hexToRgb((<IRoom> item.room).color, 1), secondary: this.hexToRgb((<IRoom> item.room).color, 0.5) } }; return event; }); this.fillDayEvents(); } private fillDayEvents(): void { this.dayEvents = this.bookings .filter((item: IBooking) => { return (<IRoom> item.room).id === this.selectedRoom.id; }) .map((item: IBooking) => { let event: BookingCalendarEvent = { booking: item, start: item.start_time, end: item.end_time, title: (item.user.id === this.user.id ? 'Я' : item.user.lastname + ' ' + item.user.firstname + ' (' + item.user.phone + ')') + (item.title && item.title.length ? ' - ' + item.title : ''), color: { primary: this.hexToRgb((<IRoom> item.room).color, 1), secondary: this.hexToRgb((<IRoom> item.room).color, 0.5) }, actions: this.actions }; return event; }); } private hexToRgb(hex: string, opacity: number): string { let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? 'rgba(' + parseInt(result[1], 16) + ',' + parseInt(result[2], 16) + ',' + parseInt(result[3], 16) + ',' + opacity.toString() + ')' : null; } }<|fim▁end|>
<|file_name|>basic.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import mozhttpd import mozfile import os import tempfile import unittest class TestBasic(unittest.TestCase): """ Test basic Mozhttpd capabilites """ def test_basic(self): """ Test mozhttpd can serve files """ tempdir = tempfile.mkdtemp() # sizes is a dict of the form: name -> [size, binary_string, filepath] sizes = {'small': [128], 'large': [16384]} for k in sizes.keys(): # Generate random binary string sizes[k].append(os.urandom(sizes[k][0])) # Add path of file with binary string to list fpath = os.path.join(tempdir, k) sizes[k].append(fpath) # Write binary string to file with open(fpath, 'wb') as f: f.write(sizes[k][1]) server = mozhttpd.MozHttpd(docroot=tempdir) server.start() server_url = server.get_url() # Retrieve file and check contents matchup for k in sizes.keys(): retrieved_content = mozfile.load(server_url + k).read() self.assertEqual(retrieved_content, sizes[k][1]) # Cleanup tempdir and related files mozfile.rmtree(tempdir) if __name__ == '__main__':<|fim▁hole|><|fim▁end|>
unittest.main()
<|file_name|>unicorn.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np class Unicorn(object): def __init__(self): import unicornhathd as unicorn unicorn.rotation(180) unicorn.brightness(0.75) def write_pixels(self, data): import unicornhathd as unicorn for y, row in enumerate((data * 255).astype(np.uint8)): for x, color in enumerate(row): unicorn.set_pixel(x, y, *color)<|fim▁hole|> unicorn.show()<|fim▁end|>
<|file_name|>profiling_support.rs<|end_file_name|><|fim▁begin|>use measureme::{StringComponent, StringId}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::profiling::SelfProfiler; use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE}; use rustc_hir::definitions::DefPathData; use rustc_middle::ty::{TyCtxt, WithOptConstParam}; use rustc_query_system::query::{QueryCache, QueryCacheStore}; use std::fmt::Debug; use std::io::Write; struct QueryKeyStringCache { def_id_cache: FxHashMap<DefId, StringId>, } impl QueryKeyStringCache { fn new() -> QueryKeyStringCache { QueryKeyStringCache { def_id_cache: Default::default() } } } struct QueryKeyStringBuilder<'p, 'c, 'tcx> { profiler: &'p SelfProfiler, tcx: TyCtxt<'tcx>, string_cache: &'c mut QueryKeyStringCache, } impl<'p, 'c, 'tcx> QueryKeyStringBuilder<'p, 'c, 'tcx> { fn new( profiler: &'p SelfProfiler, tcx: TyCtxt<'tcx>, string_cache: &'c mut QueryKeyStringCache, ) -> QueryKeyStringBuilder<'p, 'c, 'tcx> { QueryKeyStringBuilder { profiler, tcx, string_cache } } // The current implementation is rather crude. In the future it might be a // good idea to base this on `ty::print` in order to get nicer and more // efficient query keys. fn def_id_to_string_id(&mut self, def_id: DefId) -> StringId { if let Some(&string_id) = self.string_cache.def_id_cache.get(&def_id) { return string_id; } let def_key = self.tcx.def_key(def_id); let (parent_string_id, start_index) = match def_key.parent { Some(parent_index) => {<|fim▁hole|> None => (StringId::INVALID, 2), }; let dis_buffer = &mut [0u8; 16]; let crate_name; let other_name; let name; let dis; let end_index; match def_key.disambiguated_data.data { DefPathData::CrateRoot => { crate_name = self.tcx.crate_name(def_id.krate).as_str(); name = &*crate_name; dis = ""; end_index = 3; } other => { other_name = other.to_string(); name = other_name.as_str(); if def_key.disambiguated_data.disambiguator == 0 { dis = ""; end_index = 3; } else { write!(&mut dis_buffer[..], "[{}]", def_key.disambiguated_data.disambiguator) .unwrap(); let end_of_dis = dis_buffer.iter().position(|&c| c == b']').unwrap(); dis = std::str::from_utf8(&dis_buffer[..end_of_dis + 1]).unwrap(); end_index = 4; } } } let components = [ StringComponent::Ref(parent_string_id), StringComponent::Value("::"), StringComponent::Value(name), StringComponent::Value(dis), ]; let string_id = self.profiler.alloc_string(&components[start_index..end_index]); self.string_cache.def_id_cache.insert(def_id, string_id); string_id } } trait IntoSelfProfilingString { fn to_self_profile_string(&self, builder: &mut QueryKeyStringBuilder<'_, '_, '_>) -> StringId; } // The default implementation of `IntoSelfProfilingString` just uses `Debug` // which is slow and causes lots of duplication of string data. // The specialized impls below take care of making the `DefId` case more // efficient. impl<T: Debug> IntoSelfProfilingString for T { default fn to_self_profile_string( &self, builder: &mut QueryKeyStringBuilder<'_, '_, '_>, ) -> StringId { let s = format!("{:?}", self); builder.profiler.alloc_string(&s[..]) } } impl<T: SpecIntoSelfProfilingString> IntoSelfProfilingString for T { fn to_self_profile_string(&self, builder: &mut QueryKeyStringBuilder<'_, '_, '_>) -> StringId { self.spec_to_self_profile_string(builder) } } #[rustc_specialization_trait] trait SpecIntoSelfProfilingString: Debug { fn spec_to_self_profile_string( &self, builder: &mut QueryKeyStringBuilder<'_, '_, '_>, ) -> StringId; } impl SpecIntoSelfProfilingString for DefId { fn spec_to_self_profile_string( &self, builder: &mut QueryKeyStringBuilder<'_, '_, '_>, ) -> StringId { builder.def_id_to_string_id(*self) } } impl SpecIntoSelfProfilingString for CrateNum { fn spec_to_self_profile_string( &self, builder: &mut QueryKeyStringBuilder<'_, '_, '_>, ) -> StringId { builder.def_id_to_string_id(DefId { krate: *self, index: CRATE_DEF_INDEX }) } } impl SpecIntoSelfProfilingString for DefIndex { fn spec_to_self_profile_string( &self, builder: &mut QueryKeyStringBuilder<'_, '_, '_>, ) -> StringId { builder.def_id_to_string_id(DefId { krate: LOCAL_CRATE, index: *self }) } } impl SpecIntoSelfProfilingString for LocalDefId { fn spec_to_self_profile_string( &self, builder: &mut QueryKeyStringBuilder<'_, '_, '_>, ) -> StringId { builder.def_id_to_string_id(DefId { krate: LOCAL_CRATE, index: self.local_def_index }) } } impl<T: SpecIntoSelfProfilingString> SpecIntoSelfProfilingString for WithOptConstParam<T> { fn spec_to_self_profile_string( &self, builder: &mut QueryKeyStringBuilder<'_, '_, '_>, ) -> StringId { // We print `WithOptConstParam` values as tuples to make them shorter // and more readable, without losing information: // // "WithOptConstParam { did: foo::bar, const_param_did: Some(foo::baz) }" // becomes "(foo::bar, foo::baz)" and // "WithOptConstParam { did: foo::bar, const_param_did: None }" // becomes "(foo::bar, _)". let did = StringComponent::Ref(self.did.to_self_profile_string(builder)); let const_param_did = if let Some(const_param_did) = self.const_param_did { let const_param_did = builder.def_id_to_string_id(const_param_did); StringComponent::Ref(const_param_did) } else { StringComponent::Value("_") }; let components = [ StringComponent::Value("("), did, StringComponent::Value(", "), const_param_did, StringComponent::Value(")"), ]; builder.profiler.alloc_string(&components[..]) } } impl<T0, T1> SpecIntoSelfProfilingString for (T0, T1) where T0: SpecIntoSelfProfilingString, T1: SpecIntoSelfProfilingString, { fn spec_to_self_profile_string( &self, builder: &mut QueryKeyStringBuilder<'_, '_, '_>, ) -> StringId { let val0 = self.0.to_self_profile_string(builder); let val1 = self.1.to_self_profile_string(builder); let components = &[ StringComponent::Value("("), StringComponent::Ref(val0), StringComponent::Value(","), StringComponent::Ref(val1), StringComponent::Value(")"), ]; builder.profiler.alloc_string(components) } } /// Allocate the self-profiling query strings for a single query cache. This /// method is called from `alloc_self_profile_query_strings` which knows all /// the queries via macro magic. fn alloc_self_profile_query_strings_for_query_cache<'tcx, C>( tcx: TyCtxt<'tcx>, query_name: &'static str, query_cache: &QueryCacheStore<C>, string_cache: &mut QueryKeyStringCache, ) where C: QueryCache, C::Key: Debug + Clone, { tcx.prof.with_profiler(|profiler| { let event_id_builder = profiler.event_id_builder(); // Walk the entire query cache and allocate the appropriate // string representations. Each cache entry is uniquely // identified by its dep_node_index. if profiler.query_key_recording_enabled() { let mut query_string_builder = QueryKeyStringBuilder::new(profiler, tcx, string_cache); let query_name = profiler.get_or_alloc_cached_string(query_name); // Since building the string representation of query keys might // need to invoke queries itself, we cannot keep the query caches // locked while doing so. Instead we copy out the // `(query_key, dep_node_index)` pairs and release the lock again. let mut query_keys_and_indices = Vec::new(); query_cache.iter_results(&mut |k, _, i| query_keys_and_indices.push((k.clone(), i))); // Now actually allocate the strings. If allocating the strings // generates new entries in the query cache, we'll miss them but // we don't actually care. for (query_key, dep_node_index) in query_keys_and_indices { // Translate the DepNodeIndex into a QueryInvocationId let query_invocation_id = dep_node_index.into(); // Create the string version of the query-key let query_key = query_key.to_self_profile_string(&mut query_string_builder); let event_id = event_id_builder.from_label_and_arg(query_name, query_key); // Doing this in bulk might be a good idea: profiler.map_query_invocation_id_to_string( query_invocation_id, event_id.to_string_id(), ); } } else { // In this branch we don't allocate query keys let query_name = profiler.get_or_alloc_cached_string(query_name); let event_id = event_id_builder.from_label(query_name).to_string_id(); let mut query_invocation_ids = Vec::new(); query_cache.iter_results(&mut |_, _, i| { query_invocation_ids.push(i.into()); }); profiler.bulk_map_query_invocation_id_to_single_string( query_invocation_ids.into_iter(), event_id, ); } }); } /// All self-profiling events generated by the query engine use /// virtual `StringId`s for their `event_id`. This method makes all /// those virtual `StringId`s point to actual strings. /// /// If we are recording only summary data, the ids will point to /// just the query names. If we are recording query keys too, we /// allocate the corresponding strings here. pub fn alloc_self_profile_query_strings(tcx: TyCtxt<'tcx>) { if !tcx.prof.enabled() { return; } let mut string_cache = QueryKeyStringCache::new(); macro_rules! alloc_once { (<$tcx:tt> $($(#[$attr:meta])* [$($modifiers:tt)*] fn $name:ident($K:ty) -> $V:ty,)* ) => { $({ alloc_self_profile_query_strings_for_query_cache( tcx, stringify!($name), &tcx.query_caches.$name, &mut string_cache, ); })* } } rustc_query_append! { [alloc_once!][<'tcx>] } }<|fim▁end|>
let parent_def_id = DefId { index: parent_index, krate: def_id.krate }; (self.def_id_to_string_id(parent_def_id), 0) }
<|file_name|>taxonomy.py<|end_file_name|><|fim▁begin|>""" Provides classes that represent complete taxonomies, built using components from the taxacomponents module. """ from taxacomponents import Citation, RankTable, Taxon from taxonvisitor import TaxonVisitor from taxonvisitors_concrete import PrintTaxonVisitor, CSVTaxonVisitor from nameresolve import CoLNamesResolver class TaxonomyError(Exception): """ A basic exception class for reporting errors encountered while working with taxonomies. """ def __init__(self, msg): msg = 'Taxonomy error:\n ' + msg Exception.__init__(self, msg) class TaxonomyBase: # Define the "nil" UUID constant as returned by the uuid-osp Postgres module # function uuid_nil(). #NIL_UUID = '00000000-0000-0000-0000-000000000000' NIL_UUID = 0 def __init__(self, taxonomy_id, name='', ismaster=False, citation=None, roottaxon=None): self.taxonomy_id = taxonomy_id self.name = name self.ismaster = ismaster self.citation = citation self.roottaxon = roottaxon <|fim▁hole|> """ Attempts to load the taxonomy from a taxonomy database, including the full tree of taxa. If taxanum > 0, then only taxanum taxa will be loaded. If maxdepth > -1, the taxa tree will only be traversed to a depth of maxdepth. """ query = """SELECT name, citation_id, ismaster, root_tc_id FROM taxonomies WHERE taxonomy_id=?""" pgcur.execute(query, (self.taxonomy_id,)) res = pgcur.fetchone() if res == None: raise TaxonomyError('Taxonomy ID ' + str(self.taxonomy_id) + ' was not found in the database.') self.name = res[0] self.ismaster = res[2] roottc_id = res[3] # Create the Citation object. self.citation = Citation() self.citation.loadFromDB(pgcur, res[1]) # Get the rank ID and taxonomy ID of the root taxon concept. query = """SELECT tc.rank_id, tc.taxonomy_id FROM taxon_concepts tc, ranks r WHERE tc.tc_id=? AND tc.rank_id=r.rank_id""" pgcur.execute(query, (roottc_id,)) res = pgcur.fetchone() rankid = res[0] root_taxonomy_id = res[1] # Initialize the rank lookup table. rankt = RankTable() rankt.loadFromDB(pgcur) # Load the taxa tree. self.roottaxon = Taxon(self.taxonomy_id, rankid, rankt, roottaxo_id = root_taxonomy_id, isroot=True) self.roottaxon.loadFromDB(pgcur, roottc_id, taxanum, maxdepth) def persist(self): """ Persist the Taxonomy to the database. This method should be implemented by concrete subclasses. """ pass def __str__(self): tstr = 'name: ' + self.name + '\nID: ' + str(self.taxonomy_id) + '\nmaster: ' if self.ismaster: tstr += 'yes' else: tstr += 'no' return tstr def printTaxonomyInfo(self): """ Prints the metadata that describes this taxonomy. """ print '** Taxonomy information **' print str(self) print str(self.citation) def printCSVTaxaTree(self, numtaxa=-1, maxdepth=-1): """ Prints the tree of taxa for this taxonomy in "flat" format as CSV outut. If numtaxa > 0, only the first numtaxa taxa will be printed. If maxdepth > -1, the taxa tree will only be traversed to a depth of maxdepth. """ if numtaxa > 0: print '(Only printing first', numtaxa, 'taxa.)' if maxdepth > -1: print '(Only traversing taxa tree to a depth of ' + str(maxdepth) + '.)' csvvisitor = CSVTaxonVisitor(numtaxa, maxdepth) csvvisitor.visit(self.roottaxon) def printTaxaTree(self, numtaxa=-1, maxdepth=-1): """ Prints the tree of taxa for this taxonomy. If numtaxa > 0, only the first numtaxa taxa will be printed. If maxdepth > -1, the taxa tree will only be traversed to a depth of maxdepth. """ print '** Taxa tree **' if numtaxa > 0: print '(Only printing first', numtaxa, 'taxa.)' if maxdepth > -1: print '(Only traversing taxa tree to a depth of ' + str(maxdepth) + '.)' ptvisitor = PrintTaxonVisitor(numtaxa, maxdepth) ptvisitor.visit(self.roottaxon) def printAll(self, numtaxa=-1, maxdepth=-1): """ Prints a text representation of this taxonomy, including the tree of taxa. If numtaxa > 0, only the first numtaxa taxa will be printed. If maxdepth > -1, the taxa tree will only be traversed to a depth of maxdepth. """ self.printTaxonomyInfo() print self.printTaxaTree(numtaxa, maxdepth) class Taxonomy(TaxonomyBase): """ A class that represents a single taxonomy in the MOL taxonomy database. Provides methods to load a taxonomy from the database and persist a taxonomy to the database. Can also link a taxonomy to the backbone taxonomy. """ def __init__(self, taxonomy_id, name='', ismaster=False, citation=None, roottaxon=None): TaxonomyBase.__init__(self, taxonomy_id, name, ismaster, citation, roottaxon) # A reference for the backbone taxonomy, which encompasses all other taxonomies. # This reference is used if this taxonomy is linked to the backbone taxonomy. self.bb_taxonomy = None def linkToBackbone(self, pgcur, adjustdepth=True): """ Tries to connect this taxonomy to the backbone taxonomy, creating new nodes in the backbone taxonomy, if needed, to link the two together. If adjustdepth is True, the depth property of all nodes in the taxonomy are set to match the correct depth relative to the root of the backbone taxonomy. Returns True if the linking operation succeeded, False otherwise. """ bb_taxonomy = BackboneTaxonomy(pgcur) if bb_taxonomy.linkTaxonomy(self): self.bb_taxonomy = bb_taxonomy if adjustdepth: self.bb_taxonomy.setNodeDepths() return True else: self.bb_taxonomy = None return False def getBackboneTaxonomy(self): """ Returns a reference to the backbone taxonomy object that links this taxonomy to the MOL backbone taxonomy. """ return self.bb_taxonomy def persist(self, pgcur, printprogress=False): """ Writes the taxonomy information to the database, if it does not already exist. This includes calling the persist() methods on the Citation and Taxon tree associated with this Taxonomy object. """ # First, check if this taxonomy already exists in the database. query = """SELECT taxonomy_id FROM taxonomies WHERE taxonomy_id=? AND ismaster=?""" pgcur.execute(query, (self.taxonomy_id, self.ismaster)) res = pgcur.fetchone() if res == None: # Write the citation information to the database, if needed. citation_id = self.citation.persist(pgcur) # Create the initial database entry for the taxonomy metadata so that the # foreign key constraint for the child taxon concepts can be satisfied. query = """INSERT INTO taxonomies (taxonomy_id, name, citation_id, ismaster, root_tc_id) VALUES (?, ?, ?, ?, ?)""" pgcur.execute(query, (self.taxonomy_id, self.name, citation_id, self.ismaster, None)) # Make sure all taxon concepts, including those from the backbone taxonomy, # are persisted to the database. Use the "nil" UUID as the parent_id for # the root of the taxonomy if there is not an existing root entry. if self.bb_taxonomy != None: self.bb_taxonomy.roottaxon.persist(pgcur, self.NIL_UUID, printprogress, self.roottaxon.depth) else: self.roottaxon.persist(pgcur, self.NIL_UUID, printprogress, self.roottaxon.depth) # Get the ID of the root taxon. root_tcid = self.roottaxon.existsInDB(pgcur) # Update the taxonomy metadata entry with the root taxon concept ID. query = """UPDATE taxonomies SET root_tc_id=? WHERE taxonomy_id=?""" pgcur.execute(query, (root_tcid, self.taxonomy_id)) pgcur.connection.commit() elif printprogress: print ('The metadata for taxonomy "' + self.name + '" (ID ' + str(self.taxonomy_id) + ') already exist in the database; no changes were made.') def printAll(self, numtaxa=-1, maxdepth=-1): """ Prints a text representation of this taxonomy, including the tree of taxa. If numtaxa > 0, only the first numtaxa taxa will be printed. If maxdepth > -1, the taxa tree will only be traversed to a depth of maxdepth. Unlike the method in the base class, this method accounts for the possibility of this taxonomy being linked to the backbone taxonomy. """ self.printTaxonomyInfo() print if self.bb_taxonomy != None: self.bb_taxonomy.printTaxaTree(numtaxa, maxdepth) else: self.printTaxaTree(numtaxa, maxdepth) class DepthAdjustVisitor(TaxonVisitor): """ Sets the "depth" values for all Taxon objects in a taxa tree, using an initial starting depth value. """ def __init__(self, startdepth): """ Assigns startdepth as the "depth" value for the top-level Taxon object. All other "depth" values are calculated relative to startdepth. """ TaxonVisitor.__init__(self) self.startdepth = startdepth def processTaxon(self, taxon, depth): taxon.depth = self.startdepth + depth class BackboneTaxonomy(TaxonomyBase): """ A special case of Taxonomy that represents the MOL backbone taxonomy. Provides methods to link other taxonomies to the backbone taxonomy. Does not provide a persist() method because the backbone taxonomy metadata are set when the database tables are created. """ def __init__(self, pgcur): """ Initialize the backbone Taxonomy object and automatically load it from the database, but load only the root node by default. """ self.pgcur = pgcur # The ID of the backbone taxonomy is always 1. TaxonomyBase.__init__(self, 1) self.loadFromDB(pgcur) def loadFromDB(self, pgcur, taxanum=-1, maxdepth=0): """ Exactly the same as loadFromDB() from the superclass, except loads only the root taxonomy node (i.e., Eukaryota) by default. """ TaxonomyBase.loadFromDB(self, pgcur, taxanum, maxdepth) def linkTaxonomy(self, taxonomy): """ Given a Taxonomy object, this method searches for the root taxon concept in the database, verifies whether it is already connected to the MOL backbone taxonomy, and if not, attempts to create the Taxon objects needed to link it to the backbone taxonomy. To do this, the method loads all ancestors of the root of the provided taxonomy, and checks if the top-most ancestor is the root of the backbone taxonomy. If it not, then Catalog of Life is used to try to infer the missing taxon nodes that connect the target taxonomy to the backbone taxonomy. If the linking is succesful, the method returns True; otherwise, False is returned. """ # Load any parent links to the target taxonomy from the database. topnode = self.getLinksFromDB(taxonomy) # See if we made it back to the root of the backbone taxonomy. if topnode.equals(self.roottaxon): # We did, so simply link the child of the returned node to our root taxon. self.roottaxon.addChild(topnode.children[0]) success = True else: # Otherwise, try to use Catalog of Life to fill in any missing links. success = self._buildCoLLinks(topnode) return success def _buildCoLLinks(self, taxon): """ Uses Catalog of Life to fill in missing taxa needed to link the target taxon to the MOL backbone taxonomy. If linking was successful, the target taxon will be connected to the backbone root taxon by one or more linking taxa. Returns True on success; False otherwise. """ # Use the Catalog of Life names resolver to try to get higher taxonomy information # for the taxon. resolver = CoLNamesResolver() searchres = resolver.searchCoLForTaxon(taxon, taxon.name.namestr, True) if searchres == None: return False res, sname, srank, authorinfo = searchres # Process each parent taxon in the CoL classification, creating a chain of Taxon # objects to capture the higher taxonomy. Because the name resolver search method # verifies that the kingdom is correct, we already know that we are connecting the # taxonomy to the correct kingdom. taxaxml = res.find('./classification') # It is important that we use the rank system from the taxonomy (not the backbone) # to ensure that rank name lookups retrieve the correct ID. tranksys = taxon.ranksys ranktable = taxon.rankt curnode = self.roottaxon for taxonxml in taxaxml: namestr = taxonxml.find('name').text rankstr = taxonxml.find('rank').text child = curnode.createChild(ranktable.getID(rankstr, tranksys), namestr) #print child curnode = child # Link the root of the target taxonomy to the backbone taxonomy. curnode.addChild(taxon) return True def getLinksFromDB(self, taxonomy): """ Starting from the root node of the provided taxonomy, follows parent links upward, building a chain of taxon objects until the top-most parent is reached. Returns the top-most node that could be reached by following the links upward. """ # See if the root taxon_concept already has a parent. curnode = taxonomy.roottaxon parent_id = taxonomy.roottaxon.getParentIDFromDB(self.pgcur) # Follow parent links upwards until we reach the root or any other node # that has no parent or does not yet exist in the database. while parent_id != None and parent_id != self.NIL_UUID: # Create the parent node and load it from the database. parent = Taxon(curnode.taxonomy_id, curnode.rank_id, curnode.rankt) parent.loadFromDB(self.pgcur, parent_id, maxdepth=0) parent.addChild(curnode) curnode = parent parent_id = curnode.getParentIDFromDB(self.pgcur) return curnode def setNodeDepths(self): """ After linking a new taxonomy to the backbone taxonomy, the values of the depth properties on the Taxon objects in the target taxonomy are likely to be incorrect. This method will visit all nodes and set the correct value of the depth property for each node. """ depthvisitor = DepthAdjustVisitor(0) depthvisitor.visit(self.roottaxon)<|fim▁end|>
def loadFromDB(self, pgcur, taxanum=-1, maxdepth=-1):
<|file_name|>database.rs<|end_file_name|><|fim▁begin|>// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use crate::err::Result; use rusqlite::{params, Connection, OptionalExtension, Row, Statement, NO_PARAMS}; use std::collections::HashMap; use std::path::Path; fn trace(s: &str) { println!("sql: {}", s) } pub(super) fn open_or_create<P: AsRef<Path>>(path: P) -> Result<Connection> { let mut db = Connection::open(path)?; if std::env::var("TRACESQL").is_ok() { db.trace(Some(trace)); } db.pragma_update(None, "page_size", &4096)?; db.pragma_update(None, "legacy_file_format", &false)?; db.pragma_update_and_check(None, "journal_mode", &"wal", |_| Ok(()))?; initial_db_setup(&mut db)?; Ok(db) } fn initial_db_setup(db: &mut Connection) -> Result<()> { // tables already exist? if db .prepare("select null from sqlite_master where type = 'table' and name = 'media'")? .exists(NO_PARAMS)? { return Ok(()); } db.execute("begin", NO_PARAMS)?; db.execute_batch(include_str!("schema.sql"))?; db.execute_batch("commit; vacuum; analyze;")?; Ok(()) } #[derive(Debug, PartialEq)] pub struct MediaEntry { pub fname: String, /// If None, file has been deleted pub sha1: Option<[u8; 20]>, // Modification time; 0 if deleted pub mtime: i64, /// True if changed since last sync pub sync_required: bool, } #[derive(Debug, PartialEq)] pub struct MediaDatabaseMetadata { pub folder_mtime: i64, pub last_sync_usn: i32, }<|fim▁hole|>/// Helper to prepare a statement, or return a previously prepared one. macro_rules! cached_sql { ( $label:expr, $db:expr, $sql:expr ) => {{ if $label.is_none() { $label = Some($db.prepare($sql)?); } $label.as_mut().unwrap() }}; } pub struct MediaDatabaseContext<'a> { db: &'a Connection, get_entry_stmt: Option<Statement<'a>>, update_entry_stmt: Option<Statement<'a>>, remove_entry_stmt: Option<Statement<'a>>, } impl MediaDatabaseContext<'_> { pub(super) fn new(db: &Connection) -> MediaDatabaseContext { MediaDatabaseContext { db, get_entry_stmt: None, update_entry_stmt: None, remove_entry_stmt: None, } } /// Execute the provided closure in a transaction, rolling back if /// an error is returned. pub(super) fn transact<F, R>(&mut self, func: F) -> Result<R> where F: FnOnce(&mut MediaDatabaseContext) -> Result<R>, { self.begin()?; let mut res = func(self); if res.is_ok() { if let Err(e) = self.commit() { res = Err(e); } } if res.is_err() { self.rollback()?; } res } fn begin(&mut self) -> Result<()> { self.db.execute_batch("begin immediate").map_err(Into::into) } fn commit(&mut self) -> Result<()> { self.db.execute_batch("commit").map_err(Into::into) } fn rollback(&mut self) -> Result<()> { self.db.execute_batch("rollback").map_err(Into::into) } pub(super) fn get_entry(&mut self, fname: &str) -> Result<Option<MediaEntry>> { let stmt = cached_sql!( self.get_entry_stmt, self.db, " select fname, csum, mtime, dirty from media where fname=?" ); stmt.query_row(params![fname], row_to_entry) .optional() .map_err(Into::into) } pub(super) fn set_entry(&mut self, entry: &MediaEntry) -> Result<()> { let stmt = cached_sql!( self.update_entry_stmt, self.db, " insert or replace into media (fname, csum, mtime, dirty) values (?, ?, ?, ?)" ); let sha1_str = entry.sha1.map(hex::encode); stmt.execute(params![ entry.fname, sha1_str, entry.mtime, entry.sync_required ])?; Ok(()) } pub(super) fn remove_entry(&mut self, fname: &str) -> Result<()> { let stmt = cached_sql!( self.remove_entry_stmt, self.db, " delete from media where fname=?" ); stmt.execute(params![fname])?; Ok(()) } pub(super) fn get_meta(&mut self) -> Result<MediaDatabaseMetadata> { let mut stmt = self.db.prepare("select dirMod, lastUsn from meta")?; stmt.query_row(NO_PARAMS, |row| { Ok(MediaDatabaseMetadata { folder_mtime: row.get(0)?, last_sync_usn: row.get(1)?, }) }) .map_err(Into::into) } pub(super) fn set_meta(&mut self, meta: &MediaDatabaseMetadata) -> Result<()> { let mut stmt = self.db.prepare("update meta set dirMod = ?, lastUsn = ?")?; stmt.execute(params![meta.folder_mtime, meta.last_sync_usn])?; Ok(()) } pub(super) fn count(&mut self) -> Result<u32> { self.db .query_row( "select count(*) from media where csum is not null", NO_PARAMS, |row| Ok(row.get(0)?), ) .map_err(Into::into) } pub(super) fn get_pending_uploads(&mut self, max_entries: u32) -> Result<Vec<MediaEntry>> { let mut stmt = self .db .prepare("select fname from media where dirty=1 limit ?")?; let results: Result<Vec<_>> = stmt .query_and_then(params![max_entries], |row| { let fname = row.get_raw(0).as_str()?; Ok(self.get_entry(fname)?.unwrap()) })? .collect(); results } pub(super) fn all_mtimes(&mut self) -> Result<HashMap<String, i64>> { let mut stmt = self .db .prepare("select fname, mtime from media where csum is not null")?; let map: std::result::Result<HashMap<String, i64>, rusqlite::Error> = stmt .query_map(NO_PARAMS, |row| Ok((row.get(0)?, row.get(1)?)))? .collect(); Ok(map?) } pub(super) fn force_resync(&mut self) -> Result<()> { self.db .execute_batch("delete from media; update meta set lastUsn = 0, dirMod = 0") .map_err(Into::into) } } fn row_to_entry(row: &Row) -> rusqlite::Result<MediaEntry> { // map the string checksum into bytes let sha1_str: Option<String> = row.get(1)?; let sha1_array = if let Some(s) = sha1_str { let mut arr = [0; 20]; match hex::decode_to_slice(s, arr.as_mut()) { Ok(_) => Some(arr), _ => None, } } else { None }; // and return the entry Ok(MediaEntry { fname: row.get(0)?, sha1: sha1_array, mtime: row.get(2)?, sync_required: row.get(3)?, }) } #[cfg(test)] mod test { use crate::err::Result; use crate::media::database::MediaEntry; use crate::media::files::sha1_of_data; use crate::media::MediaManager; use tempfile::NamedTempFile; #[test] fn database() -> Result<()> { let db_file = NamedTempFile::new()?; let db_file_path = db_file.path().to_str().unwrap(); let mut mgr = MediaManager::new("/dummy", db_file_path)?; let mut ctx = mgr.dbctx(); ctx.transact(|ctx| { // no entry exists yet assert_eq!(ctx.get_entry("test.mp3")?, None); // add one let mut entry = MediaEntry { fname: "test.mp3".into(), sha1: None, mtime: 0, sync_required: false, }; ctx.set_entry(&entry)?; assert_eq!(ctx.get_entry("test.mp3")?.unwrap(), entry); // update it entry.sha1 = Some(sha1_of_data(b"hello")); entry.mtime = 123; entry.sync_required = true; ctx.set_entry(&entry)?; assert_eq!(ctx.get_entry("test.mp3")?.unwrap(), entry); assert_eq!(ctx.get_pending_uploads(25)?, vec![entry]); let mut meta = ctx.get_meta()?; assert_eq!(meta.folder_mtime, 0); assert_eq!(meta.last_sync_usn, 0); meta.folder_mtime = 123; meta.last_sync_usn = 321; ctx.set_meta(&meta)?; meta = ctx.get_meta()?; assert_eq!(meta.folder_mtime, 123); assert_eq!(meta.last_sync_usn, 321); Ok(()) })?; // reopen database and ensure data was committed drop(ctx); drop(mgr); mgr = MediaManager::new("/dummy", db_file_path)?; let mut ctx = mgr.dbctx(); let meta = ctx.get_meta()?; assert_eq!(meta.folder_mtime, 123); Ok(()) } }<|fim▁end|>
<|file_name|>relevanceFusion.py<|end_file_name|><|fim▁begin|>import os import sys import numpy as np from basic.common import checkToSkip def process(options): overwrite = options.overwrite inputeFile = options.inputeFile weightFile = options.weightFile resultFile = options.resultFile weightFile = os.path.join('result', weightFile) weight = open(weightFile).readline().strip().split() weight = np.array(weight, dtype=np.float) resultFile = os.path.join('result', resultFile) if checkToSkip(resultFile, overwrite): sys.exit(0) fout = open(resultFile, 'w') done = 0 for line in open(os.path.join('result', inputeFile)): elems = line.strip().split() vecs = map(float, elems[3:]) vecs = np.array(vecs, dtype=np.float) assert(len(weight) == len(vecs)) <|fim▁hole|> done += 1 if done % 10000 == 0: print done, 'Done' fout.close() print "final score result after relevance fusion have written in %s" % resultFile def main(argv=None): if argv is None: argv = sys.argv[1:] from optparse import OptionParser parser = OptionParser(usage="""usage: %prog [options] """) parser.add_option("--overwrite", default=0, type="int", help="overwrite existing file (default: 0)") parser.add_option("--inputeFile", default='qid.img.lable.feature.txt', type="string", help="file stored all score from different methods") parser.add_option("--weightFile", default='optimized_wights.txt', type="string", help="optimized wight will be written in the file") parser.add_option("--resultFile", default='fianl.result.txt', type="string", help="final score after relevance fusion") (options, args) = parser.parse_args(argv) return process(options) if __name__ == "__main__": sys.exit(main())<|fim▁end|>
fout.write(" ".join(elems[:2]) + " " + str(np.dot(weight, vecs)) + '\n')
<|file_name|>index.js<|end_file_name|><|fim▁begin|>import database from "../api/database"; import * as types from "../actions/ActionTypes" const receiveAspects = aspects => ({ type: types.GET_COMMON_ASPECTS, aspects });<|fim▁hole|> database.getCommonAspects(aspects => { dispatch(receiveAspects(aspects)) }) }; export const loadAll = () => ({ type: types.LOAD_ALL_ASPECTS });<|fim▁end|>
export const getCommonAspects = () => dispatch => {
<|file_name|>main.js<|end_file_name|><|fim▁begin|>'use strict'; var assert = require('assert'); var fs = require('fs'); var path = require('path'); describe('responsive-compass-sprite', function() { describe('icon-sprite', function() { function compare(expected, tmp, done) { var baseExpected = __dirname + '/expected/icon-sprite', baseTmp = __dirname + '/tmp/icon-sprite'; if(typeof tmp === 'function') { done = tmp; tmp = expected; } assert.equal(fs.readFileSync(baseExpected + '/' + expected, 'utf-8'), fs.readFileSync(baseTmp + '/' + tmp, 'utf-8')); done();<|fim▁hole|> compare('simple.css', done); }); it('renderAll test', function(done) { compare('renderAllSprites.css', done); }); }); });<|fim▁end|>
}; it('simple test', function(done) {
<|file_name|>0016_grades_initialdata.py<|end_file_name|><|fim▁begin|># Generated by Django 2.2.12 on 2020-05-09 06:28 from django.db import migrations # Can't use fixtures because load_fixtures method is janky with django-tenant-schemas def load_initial_data(apps, schema_editor): Grade = apps.get_model('courses', 'Grade') # add some initial data if none has been created yet if not Grade.objects.exists(): Grade.objects.create( name="8", value=8 ) Grade.objects.create( name="9",<|fim▁hole|> value=10 ) Grade.objects.create( name="11", value=11 ) Grade.objects.create( name="12", value=12 ) class Migration(migrations.Migration): dependencies = [ ('courses', '0015_auto_20200508_1957'), ] operations = [ migrations.RunPython(load_initial_data), ]<|fim▁end|>
value=9 ) Grade.objects.create( name="10",
<|file_name|>sample_template.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # ----------------------------------------------------------------------------- from os.path import basename, exists from json import loads, dumps from tempfile import NamedTemporaryFile from tornado.web import authenticated, HTTPError from qiita_core.qiita_settings import r_client from qiita_pet.handlers.base_handlers import BaseHandler from qiita_db.util import get_files_from_uploads_folders from qiita_db.study import Study from qiita_db.metadata_template.sample_template import SampleTemplate from qiita_db.metadata_template.util import looks_like_qiime_mapping_file from qiita_db.software import Software, Parameters from qiita_db.processing_job import ProcessingJob from qiita_db.exceptions import QiitaDBUnknownIDError from qiita_pet.handlers.api_proxy import ( data_types_get_req, sample_template_samples_get_req, prep_template_samples_get_req, study_prep_get_req, sample_template_meta_cats_get_req, sample_template_category_get_req, get_sample_template_processing_status, check_fp) SAMPLE_TEMPLATE_KEY_FORMAT = 'sample_template_%s' def sample_template_checks(study_id, user, check_exists=False): """Performs different checks and raises errors if any of the checks fail Parameters ---------- study_id : int The study id user : qiita_db.user.User The user trying to access the study check_exists : bool, optional If true, check if the sample template exists Raises ------ HTTPError 404 if the study does not exist 403 if the user does not have access to the study 404 if check_exists == True and the sample template doesn't exist """ try: study = Study(int(study_id)) except QiitaDBUnknownIDError: raise HTTPError(404, reason='Study does not exist') if not study.has_access(user): raise HTTPError(403, reason='User does not have access to study') # Check if the sample template exists if check_exists and not SampleTemplate.exists(study_id): raise HTTPError(404, reason="Study %s doesn't have sample information" % study_id) def sample_template_handler_post_request(study_id, user, filepath, data_type=None, direct_upload=False): """Creates a new sample template Parameters ---------- study_id: int The study to add the sample information user: qiita_db.user import User The user performing the request filepath: str The path to the sample template file data_type: str, optional If filepath is a QIIME mapping file, the data type of the prep information file direct_upload: boolean, optional If filepath is a direct upload; if False we need to process the filepath as part of the study upload folder Returns ------- dict of {'job': str} job: the id of the job adding the sample information to the study Raises ------ HTTPError 404 if the filepath doesn't exist """ # Check if the current user has access to the study sample_template_checks(study_id, user) # Check if the file exists if not direct_upload: fp_rsp = check_fp(study_id, filepath) if fp_rsp['status'] != 'success': raise HTTPError(404, reason='Filepath not found') filepath = fp_rsp['file'] is_mapping_file = looks_like_qiime_mapping_file(filepath) if is_mapping_file and not data_type: raise HTTPError(400, reason='Please, choose a data type if uploading ' 'a QIIME mapping file') qiita_plugin = Software.from_name_and_version('Qiita', 'alpha') cmd = qiita_plugin.get_command('create_sample_template') params = Parameters.load( cmd, values_dict={'fp': filepath, 'study_id': study_id, 'is_mapping_file': is_mapping_file, 'data_type': data_type}) job = ProcessingJob.create(user, params, True) r_client.set(SAMPLE_TEMPLATE_KEY_FORMAT % study_id, dumps({'job_id': job.id})) job.submit() return {'job': job.id} def sample_template_handler_patch_request(user, req_op, req_path, req_value=None, req_from=None, direct_upload=False): """Patches the sample template Parameters ---------- user: qiita_db.user.User The user performing the request req_op : str The operation to perform on the sample template req_path : str The path to the attribute to patch req_value : str, optional The new value req_from : str, optional The original path of the element direct_upload : boolean, optional If the file being uploaded comes from a direct upload (True) Returns ------- Raises ------ HTTPError 400 If the path parameter doens't follow the expected format 400 If the given operation is not supported """ req_path = [v for v in req_path.split('/') if v] # At this point we know the path should be at least length 2 if len(req_path) < 2: raise HTTPError(400, reason='Incorrect path parameter') study_id = int(req_path[0]) # Check if the current user has access to the study and if the sample # template exists sample_template_checks(study_id, user, check_exists=True) if req_op == 'remove': # Path format # column: study_id/columns/column_name # sample: study_id/samples/sample_id if len(req_path) != 3: raise HTTPError(400, reason='Incorrect path parameter') attribute = req_path[1] attr_id = req_path[2] qiita_plugin = Software.from_name_and_version('Qiita', 'alpha') cmd = qiita_plugin.get_command('delete_sample_or_column') params = Parameters.load( cmd, values_dict={'obj_class': 'SampleTemplate', 'obj_id': study_id, 'sample_or_col': attribute, 'name': attr_id}) job = ProcessingJob.create(user, params, True) # Store the job id attaching it to the sample template id r_client.set(SAMPLE_TEMPLATE_KEY_FORMAT % study_id, dumps({'job_id': job.id})) job.submit() return {'job': job.id} elif req_op == 'replace': # WARNING: Although the patch operation is a replace, is not a full # true replace. A replace is in theory equivalent to a remove + add. # In this case, the replace operation doesn't necessarily removes # anything (e.g. when only new columns/samples are being added to the) # sample information. # Path format: study_id/data # Forcing to specify data for extensibility. In the future we may want # to use this function to replace other elements of the sample # information if len(req_path) != 2: raise HTTPError(400, reason='Incorrect path parameter') attribute = req_path[1] if attribute == 'data': # Update the sample information if req_value is None: raise HTTPError(400, reason="Value is required when updating " "sample information") if direct_upload: # We can assume that the file exist as it was generated by # the system filepath = req_value if not exists(filepath): reason = ('Upload file not found (%s), please report to ' 'qiita.help@gmail.com' % filepath) raise HTTPError(404, reason=reason) else: # Check if the file exists fp_rsp = check_fp(study_id, req_value) if fp_rsp['status'] != 'success': raise HTTPError(404, reason='Filepath not found') filepath = fp_rsp['file'] qiita_plugin = Software.from_name_and_version('Qiita', 'alpha') cmd = qiita_plugin.get_command('update_sample_template') params = Parameters.load( cmd, values_dict={'study': study_id, 'template_fp': filepath}) job = ProcessingJob.create(user, params, True) # Store the job id attaching it to the sample template id r_client.set(SAMPLE_TEMPLATE_KEY_FORMAT % study_id, dumps({'job_id': job.id})) job.submit() return {'job': job.id} else: raise HTTPError(404, reason='Attribute %s not found' % attribute) else: raise HTTPError(400, reason='Operation %s not supported. Current ' 'supported operations: remove, replace' % req_op) def sample_template_handler_delete_request(study_id, user): """Deletes the sample template Parameters ---------- study_id: int The study to delete the sample information user: qiita_db.user The user performing the request Returns ------- dict of {'job': str} job: the id of the job deleting the sample information to the study Raises ------ HTTPError 404 If the sample template doesn't exist """ # Check if the current user has access to the study and if the sample # template exists sample_template_checks(study_id, user, check_exists=True) qiita_plugin = Software.from_name_and_version('Qiita', 'alpha') cmd = qiita_plugin.get_command('delete_sample_template') params = Parameters.load(cmd, values_dict={'study': int(study_id)}) job = ProcessingJob.create(user, params, True) # Store the job if deleteing the sample template r_client.set(SAMPLE_TEMPLATE_KEY_FORMAT % study_id, dumps({'job_id': job.id})) job.submit() return {'job': job.id} class SampleTemplateHandler(BaseHandler): @authenticated def get(self): study_id = self.get_argument('study_id') # Check if the current user has access to the study sample_template_checks(study_id, self.current_user) self.render('study_ajax/sample_summary.html', study_id=study_id) @authenticated def post(self): study_id = int(self.get_argument('study_id')) filepath = self.get_argument('filepath') data_type = self.get_argument('data_type') direct_upload = self.get_argument('direct_upload', False) if direct_upload and direct_upload == 'true': direct_upload = True with NamedTemporaryFile(suffix='.txt', delete=False) as fp: fp.write(self.request.files['theFile'][0]['body']) filepath = fp.name self.write(sample_template_handler_post_request( study_id, self.current_user, filepath, data_type=data_type, direct_upload=direct_upload)) @authenticated def patch(self): req_op = self.get_argument('op') req_path = self.get_argument('path') req_value = self.get_argument('value', None) req_from = self.get_argument('from', None) direct_upload = self.get_argument('direct_upload', False) if direct_upload and direct_upload == 'true': direct_upload = True with NamedTemporaryFile(suffix='.txt', delete=False) as fp: fp.write(self.request.files['value'][0]['body']) req_value = fp.name self.write(sample_template_handler_patch_request( self.current_user, req_op, req_path, req_value, req_from, direct_upload)) @authenticated def delete(self): study_id = int(self.get_argument('study_id')) self.write(sample_template_handler_delete_request( study_id, self.current_user)) def sample_template_overview_handler_get_request(study_id, user): # Check if the current user has access to the sample template sample_template_checks(study_id, user) # Check if the sample template exists exists = SampleTemplate.exists(study_id) # The following information should always be provided: # The files that have been uploaded to the system and can be a # sample template file files = [f for _, f, _ in get_files_from_uploads_folders(study_id) if f.endswith(('txt', 'tsv', 'xlsx'))] # If there is a job associated with the sample information, the job id job = None job_info = r_client.get(SAMPLE_TEMPLATE_KEY_FORMAT % study_id) if job_info: job = loads(job_info)['job_id'] # Specific information if it exists or not: data_types = [] st_fp_id = None old_files = [] num_samples = 0 num_cols = 0 columns = [] specimen_id_column = None sample_restrictions = '' if exists: # If it exists we need to provide: # The id of the sample template file so the user can download it and # the list of old filepaths st = SampleTemplate(study_id) all_st_files = st.get_filepaths() # The current sample template file is the first one in the list # (pop(0)) and we are interested only in the id ([0]) st_fp_id = all_st_files.pop(0)[0] # For the old filepaths we are only interested in their basename old_files = [basename(fp) for _, fp in all_st_files] # The number of samples - this is a space efficient way of counting # the number of samples. Doing len(list(st.keys())) creates a list # that we are not using num_samples = sum(1 for _ in st.keys()) columns = st.categories() # The number of columns num_cols = len(columns) specimen_id_column = Study(study_id).specimen_id_column _, sample_restrictions = st.validate_restrictions() else: # It doesn't exist, we also need to provide the data_types in case # the user uploads a QIIME mapping file data_types = sorted(data_types_get_req()['data_types']) return {'exists': exists, 'uploaded_files': files, 'data_types': data_types, 'user_can_edit': Study(study_id).can_edit(user), 'job': job, 'download_id': st_fp_id, 'old_files': old_files, 'num_samples': num_samples, 'num_columns': num_cols, 'columns': columns, 'sample_restrictions': sample_restrictions, 'specimen_id_column': specimen_id_column} <|fim▁hole|>class SampleTemplateOverviewHandler(BaseHandler): @authenticated def get(self): study_id = int(self.get_argument('study_id')) self.write( sample_template_overview_handler_get_request( study_id, self.current_user)) def sample_template_columns_get_req(study_id, column, user): """Returns the columns of the sample template Parameters ---------- study_id: int The study to retrieve the sample information summary column: str The column of interest, if None send all columns user: qiita_db.user The user performing the request Returns ------- list of str The result of the search Raises ------ HTTPError 404 If the sample template doesn't exist """ # Check if the current user has access to the study and if the sample # template exists sample_template_checks(study_id, user, check_exists=True) if column is None: reply = SampleTemplate(study_id).categories() else: reply = list(SampleTemplate(study_id).get_category(column).values()) return reply class SampleTemplateColumnsHandler(BaseHandler): @authenticated def get(self): """Send formatted summary page of sample template""" sid = int(self.get_argument('study_id')) column = self.get_argument('column', None) reply = sample_template_columns_get_req(sid, column, self.current_user) # we reply with {'values': reply} because tornado expectes a dict self.write({'values': reply}) def _build_sample_summary(study_id, user_id): """Builds the row object for SlickGrid Parameters ---------- study_id : int Study to get samples from user_id : str User requesting the information Returns ------- columns : dicts keys represent fields and values names for the columns in SlickGrid rows : list of dicts [ {field_1: 'value', ...}, ...] """ # Load all samples available into dictionary and set rows = {s: {'sample': s} for s in sample_template_samples_get_req( study_id, user_id)['samples']} samples = rows.keys() # Add one column per prep template highlighting what samples exist preps = study_prep_get_req(study_id, user_id)["info"] columns = {} for preptype in preps: for prep in preps[preptype]: field = "prep%d" % prep["id"] name = "%s (%d)" % (prep["name"], prep["id"]) columns[field] = name prep_samples = prep_template_samples_get_req( prep['id'], user_id)['samples'] for s in samples: rows[s][field] = 'X' if s in prep_samples else '' return columns, rows class SampleAJAX(BaseHandler): @authenticated def get(self): """Show the sample summary page""" study_id = int(self.get_argument('study_id')) email = self.current_user.id res = sample_template_meta_cats_get_req(study_id, email) if res['status'] == 'error': if 'does not exist' in res['message']: raise HTTPError(404, reason=res['message']) elif 'User does not have access to study' in res['message']: raise HTTPError(403, reason=res['message']) else: raise HTTPError(500, reason=res['message']) categories = res['categories'] columns, rows = _build_sample_summary(study_id, email) _, alert_type, alert_msg = get_sample_template_processing_status( study_id) self.render('study_ajax/sample_prep_summary.html', rows=rows, columns=columns, categories=categories, study_id=study_id, alert_type=alert_type, alert_message=alert_msg, user_can_edit=Study(study_id).can_edit(self.current_user)) @authenticated def post(self): study_id = int(self.get_argument('study_id')) meta_col = self.get_argument('meta_col') values = sample_template_category_get_req(meta_col, study_id, self.current_user.id) if values['status'] != 'success': self.write(values) else: self.write({'status': 'success', 'message': '', 'values': values['values'] })<|fim▁end|>
<|file_name|>jheaderarea.cpp<|end_file_name|><|fim▁begin|>#include "precomp.h" #include "jheaderarea.h" #include "private/jheaderarea_p.h" // - JSortFilterProxyModelData - class JSortFilterProxyModelData { public: QMap<int/*column*/, QRegExp> mapRegExp; }; // - class JSortFilterProxyModel - JSortFilterProxyModel::JSortFilterProxyModel(QObject *parent) : QSortFilterProxyModel(parent) { d = new JSortFilterProxyModelData(); } JSortFilterProxyModel::~JSortFilterProxyModel() { delete d; } <|fim▁hole|> d->mapRegExp[column] = regExp; invalidateFilter(); } void JSortFilterProxyModel::removeFilter(int column) { if (d->mapRegExp.contains(column)) { d->mapRegExp.remove(column); invalidateFilter(); } } bool JSortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { QAbstractItemModel *model = sourceModel(); if (!model) { return true; } bool bResult = true; QMapIterator<int, QRegExp> iter(d->mapRegExp); while (iter.hasNext()) { iter.next(); QModelIndex index = model->index(source_row, iter.key(), source_parent); if (!index.isValid()) { return true; } bResult = bResult && model->data(index).toString().contains(iter.value()); } return bResult; } // - class JHeaderArea - JHeaderArea::JHeaderArea(QWidget *parent) : QFrame(parent) , d_ptr(new JHeaderAreaPrivate(this)) { Q_D(JHeaderArea); d->init(); } JHeaderArea::~JHeaderArea() { d_ptr->deleteLater(); } bool JHeaderArea::autoUpdateTitle() const { Q_D(const JHeaderArea); return d->autoUpdateTitle; } bool JHeaderArea::titleVisible() const { Q_D(const JHeaderArea); return d->titleArea->isVisible(); } QString JHeaderArea::title() const { Q_D(const JHeaderArea); return d->titleArea->text(); } int JHeaderArea::titleHeight() const { Q_D(const JHeaderArea); return d->titleArea->height(); } QFont JHeaderArea::titleFont() const { Q_D(const JHeaderArea); return d->titleArea->font(); } Qt::Alignment JHeaderArea::titleAlignment() const { Q_D(const JHeaderArea); return d->titleArea->alignment(); } bool JHeaderArea::filterVisible() const { Q_D(const JHeaderArea); return d->filterVisible(); } int JHeaderArea::filterHeight() const { Q_D(const JHeaderArea); return d->filterArea->height(); } void JHeaderArea::setTitleStyle(const QString &styleSheet) { Q_D(JHeaderArea); d->titleArea->setStyleSheet(styleSheet); } void JHeaderArea::setFilterStyle(const QString &styleSheet) { Q_D(JHeaderArea); d->filterArea->setStyleSheet(styleSheet); } bool JHeaderArea::filterItemVisible(int column) const { Q_D(const JHeaderArea); return d->filterItemVisible(column); } QStringList JHeaderArea::filterItem(int column) const { Q_D(const JHeaderArea); return d->filterItem(column); } bool JHeaderArea::filterItemEditable(int column) const { Q_D(const JHeaderArea); return d->filterItemEditable(column); } void JHeaderArea::setFilterItemEditable(bool editable, int column) { Q_D(JHeaderArea); d->setFilterItemEditable(editable, column); } bool JHeaderArea::setFilterItem(int column, const QString &text) { Q_D(JHeaderArea); if (!d->sourceModel) { return false; } if (column < 0 || column >= d->sourceModel->columnCount()) { return false; } d->setFilterItem(column, text); return true; } bool JHeaderArea::setFilterItem(int column, const QStringList &texts) { Q_D(JHeaderArea); if (!d->sourceModel) { return false; } if (column < 0 || column >= d->sourceModel->columnCount()) { return false; } d->setFilterItem(column, texts); return true; } void JHeaderArea::setFilterItem(const QList<int> &columns) { Q_D(JHeaderArea); if (!d->sourceModel) { return; } QListIterator<int> iter(columns); while (iter.hasNext()) { int column = iter.next(); if (column < 0 || column >= d->sourceModel->columnCount()) { continue; } d->setFilterItem(column, ""); } } void JHeaderArea::setFilterItem(const QList<QPair<int, QString> > &columns) { Q_D(JHeaderArea); if (!d->sourceModel) { return; } QListIterator<QPair<int, QString> > iter(columns); while (iter.hasNext()) { const QPair<int, QString> &column = iter.next(); int col = column.first; if (col < 0 || col >= d->sourceModel->columnCount()) { continue; } d->setFilterItem(col, column.second); } } void JHeaderArea::setFilterItem(const QList<QPair<int, QStringList> > &columns) { Q_D(JHeaderArea); if (!d->sourceModel) { return; } QListIterator<QPair<int, QStringList> > iter(columns); while (iter.hasNext()) { const QPair<int, QStringList> &column = iter.next(); int col = column.first; if (col < 0 || col >= d->sourceModel->columnCount()) { continue; } d->setFilterItem(col, column.second); } } void JHeaderArea::setFilterItemAsComboBox(const QList<int> columns) { Q_D(JHeaderArea); if (!d->sourceModel) { return; } QListIterator<int> iter(columns); while (iter.hasNext()) { int column = iter.next(); if (column < 0 || column >= d->sourceModel->columnCount()) { continue; } d->setFilterItem(column); } } void JHeaderArea::setAllFilterItemWithLineEdit() { Q_D(JHeaderArea); d->replaceFilterItemWithLineEdit(); } void JHeaderArea::setAllFilterItemWithComboBox() { Q_D(JHeaderArea); d->replaceFilterItemWithComboBox(); } void JHeaderArea::removeFilterItem(int column) { Q_D(JHeaderArea); if (!d->sourceModel) { return; } if (column < 0 || column >= d->sourceModel->columnCount()) { return; } d->removeFilterItem(column); } void JHeaderArea::clearFilterItem() { Q_D(JHeaderArea); d->clearFilterItem(); } JSortFilterProxyModel *JHeaderArea::filterModel() { Q_D(JHeaderArea); if (d->sourceModel) { return d->cusSortModel; } else { return &d->sortModel; } } void JHeaderArea::setFilterProxyModel(JSortFilterProxyModel *model) { Q_D(JHeaderArea); d->cusSortModel = model; d->updateFilterModel(filterVisible()); } bool JHeaderArea::attach(QAbstractItemView *view) { Q_D(JHeaderArea); if (d->attach(view)) { Q_EMIT attached(); return true; } else { return false; } } void JHeaderArea::detach() { Q_D(JHeaderArea); d->detach(); Q_EMIT detached(); } void JHeaderArea::setAutoUpdateTitle(bool enable) { Q_D(JHeaderArea); d->setAutpUpdateTitle(enable); } void JHeaderArea::setTitleVisible(bool visible) { Q_D(JHeaderArea); d->titleArea->setVisible(visible); Q_EMIT titleVisibleChanged(visible); } void JHeaderArea::setTitle(const QString &text) { Q_D(JHeaderArea); if (d->titleArea->text() != text) { d->titleArea->setText(text); Q_EMIT titleChanged(text); } } void JHeaderArea::setTitleHeight(int height) { Q_D(JHeaderArea); if (d->titleArea->height() != height) { d->titleArea->setFixedHeight(height); Q_EMIT titleHeightChanged(height); } } void JHeaderArea::setTitleFont(const QFont &font) { Q_D(JHeaderArea); d->titleArea->setFont(font); } void JHeaderArea::setTitleAlignment(Qt::Alignment alignment) { Q_D(JHeaderArea); d->titleArea->setAlignment(alignment); } void JHeaderArea::setFilterVisible(bool visible) { Q_D(JHeaderArea); d->setFilterVisible(visible); Q_EMIT filterVisibleChanged(visible); } void JHeaderArea::setFilterHeight(int height) { Q_D(JHeaderArea); d->filterArea->setFixedHeight(height); d->updateArea(); Q_EMIT filterHeightChanged(height); } void JHeaderArea::setSwitchEnabled(bool enable) { Q_D(JHeaderArea); d->setSwitchEnable(enable); }<|fim▁end|>
void JSortFilterProxyModel::setFilterRegExp(int column, const QRegExp &regExp) {
<|file_name|>label_steps.py<|end_file_name|><|fim▁begin|><|fim▁hole|>@when(u'I get the text from the label') def step_impl(context): context.expected_text = context.page.label_id() @when(u'I search for the label by "{how}"') def step_impl(context, how): method = 'label_{0}'.format(how) context.expected_text = getattr(context.page, method)()<|fim▁end|>
<|file_name|>build.go<|end_file_name|><|fim▁begin|>package main /* * Copyright 2016 ThoughtWorks, Inc. * * 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. */ import ( "fmt" "os" "os/exec" "io" "bytes" "io/ioutil" "strings" "flag" "runtime" "crypto/sha256" "encoding/hex" ) var goAgentFilename = "gocd-golang-agent" var targetOS = map[string][]string{ "darwin" : {"amd64"}, "linux" : {"386", "amd64", "arm", "arm64"}, "windows" : {"386", "amd64"}, // "solaris" : {"amd64"}, // Solaris does not have syscall.Statfs_t and syscall.Statfs to find disk usage. } var goAgent = "github.com/gocd-contrib/gocd-golang-agent" var targetOSmap = map[string]string{ "darwin" : "MacOS", "linux" : "Linux", "windows" : "Windows", "solaris" : "Solaris", "netbsd" : "NetBSD", "freebsd" : "FreeBSD", } var ext_libraries []string = []string{ "golang.org/x/net/websocket", "golang.org/x/text", "golang.org/x/crypto/ssh", "github.com/satori/go.uuid", "github.com/xli/assert", "github.com/bmatcuk/doublestar"} var testReport = "testreport.xml" func shouldSkipDependent(exlib string) bool { exlibGoEnv := "GO_REVISION_SRC_" + strings.ToUpper(strings.Join(strings.Split(strings.Join(strings.Split(exlib,"."),"_"),"/"),"_")) if len(os.Getenv(exlibGoEnv)) > 0 { return true } return false } func getDependencies(excludeLib string) { fmt.Println("==================================") fmt.Println("Download Dependencies") go_args := []string{} args := []string{"get","-u"} for _, exlib := range ext_libraries { if strings.Contains(excludeLib,exlib) { fmt.Printf("Exclude from go get. Please manually run : go get %s\n", exlib) }else { if !shouldSkipDependent(exlib) { go_args = append(args, exlib) _, err := exec.Command("go", go_args...).Output() if err != nil { fmt.Println(err) } fmt.Printf("Get : %s\n", exlib) } else { fmt.Printf("Skip %s since it is part of GoCD Material\n", exlib) } } } } func getGitHash(pwd string) string { runCmd := exec.Command("git", "rev-parse", "HEAD") runCmd.Dir = pwd + "/src/" + goAgent out, err := runCmd.Output() if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(2) } return strings.TrimSpace(string(out)) } func buildBinary(pwd string, binAllbinary bool){ fmt.Println("==================================") fmt.Println("Building Binary") os.RemoveAll("output") os.Mkdir("output",0755) os.Setenv("CGO_ENABLED","0") if binAllbinary { for buildOS, buildArchs := range targetOS { for _, buildArch := range buildArchs { os.Setenv("GOOS", buildOS) os.Setenv("GOARCH", buildArch) compileApp(pwd, buildOS, buildArch) } } }else{ compileApp(pwd, runtime.GOOS, runtime.GOARCH) } } func compileApp(pwd string, targetOS string, targetArch string){ var outputName string fmt.Println("---> " + targetOSmap[targetOS] + " - " + targetArch) ldFlags := "-w -X main.Githash=" + getGitHash(pwd) buildVersion := os.Getenv("BUILD_VERSION") outputName = "output/" + goAgentFilename + "_" + targetOS + "_" + targetArch if len(buildVersion) > 0 { ldFlags = ldFlags + " -X main.Version=" + buildVersion outputName = outputName + "_" + buildVersion } if targetOS == "windows"{ outputName = outputName + ".exe" } out, err := exec.Command("go", "build", "-a", "-tags", "netgo", "-ldflags", ldFlags, "-o", outputName, goAgent).Output() if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(2) } if len(string(out)) > 0 { fmt.Println(out) } hasher := sha256.New() outfileHash, outfileHashErr := ioutil.ReadFile(outputName) if outfileHashErr != nil { fmt.Println("Cannot read file ", outputName) os.Exit(2) } hasher.Write(outfileHash) outputNameSHA256, outputNameSHA256Err := os.Create(outputName + ".SHA256") if outputNameSHA256Err != nil { fmt.Println("Cannot create ", outputName, " SHA256 checksum file") os.Exit(2) } defer outputNameSHA256.Close() _, writeSHA256Err := outputNameSHA256.WriteString(hex.EncodeToString(hasher.Sum(nil))) if writeSHA256Err != nil { fmt.Println("Cannot write ", outputName, " SHA256 checksum to file") os.Exit(2) } } func runTest(pwd string){ fmt.Println("==================================") fmt.Println("Running Test") args := []string{"get","-u","github.com/jstemmer/go-junit-report"} reportCmd := pwd + "/bin/go-junit-report" reportCmd_args := []string{" > ", testReport} _, err := exec.Command("go", args...).Output() if err != nil{ fmt.Println(err) } _, err = os.Stat(testReport) if err == nil { os.Remove(testReport) } args = []string{"test", "-test.v", goAgent + "..." } gotest := exec.Command("go", args...) goreport := exec.Command(reportCmd,reportCmd_args...) reader, writer := io.Pipe() gotest.Stdout = writer goreport.Stdin = reader var buf bytes.Buffer goreport.Stdout = &buf gotest.Start() goreport.Start() gotest.Wait() writer.Close() goreport.Wait() err = ioutil.WriteFile(testReport,buf.Bytes(),0644) if err != nil{ panic(err) } } func uploadToBintray(pwd string, binAllbinary bool) { var ( bintrayURL string = "https://api.bintray.com/content/gocd-contrib/gocd_golang_goagent" bintrayPackage = "goagent" ) buildVersion := os.Getenv("BUILD_VERSION") bintrayUser := os.Getenv("BINTRAY_USER") bintrayToken := os.Getenv("BINTRAY_TOKEN") if len(buildVersion) <= 0 { fmt.Println("Unknown BUILD_VERSION") os.Exit(2) } if len(bintrayUser) <= 0 { fmt.Println("Unknown Bintray User") os.Exit(2) } if len(bintrayToken) <= 0 { fmt.Println("Unknown Bintray Token") os.Exit(2) } // temporary use curl to upload the file , will change it to use native http/net library fmt.Println("==================================") fmt.Println("Upload Binary to Bintray") for buildOS, buildArchs := range targetOS { for _, buildArch := range buildArchs { fmt.Println("---> " + targetOSmap[buildOS] + " - " + buildArch) outFilename := goAgentFilename + "_" + buildOS + "_" + buildArch + "_" + buildVersion if buildOS == "windows"{ outFilename = outFilename + ".exe" } if _, err := os.Stat("output/" + outFilename); err == nil { if _, err := os.Stat("output/" + outFilename + ".SHA256"); err == nil { outFilenameURL := bintrayURL + "/" + bintrayPackage + "/" + buildVersion + "/" + outFilename + ";bt_package=" + bintrayPackage + ";bt_version=" + buildVersion fmt.Println("\t", outFilename) _, uploadErr := exec.Command("curl", "-T", "output/" + outFilename, "-u" + bintrayUser + ":" + bintrayToken , outFilenameURL).Output() if uploadErr != nil { fmt.Println("Error upload file : ", outFilename, " to bintray.") os.Exit(2) } outFilenameURL = bintrayURL + "/" + bintrayPackage + "/" + buildVersion + "/" + outFilename + ".SHA256" + ";bt_package=" + bintrayPackage + ";bt_version=" + buildVersion fmt.Println("\t", outFilename + ".SHA256") _, uploadErr = exec.Command("curl", "-T", "output/" + outFilename + ".SHA256", "-u" + bintrayUser + ":" + bintrayToken, outFilenameURL).Output() if uploadErr != nil { fmt.Println("Error upload file : ", outFilename, " SHA256 checksum to bintray.") os.Exit(2) } }else{ fmt.Println("File : " , outFilename, " SHA256 checksum does not exist") os.Exit(2) } }else{ fmt.Println("File : ", outFilename , " does not exist.") os.Exit(2) } } } } func main() { var ( excludeLib string runAllTest bool buildLocalBinary bool buildAll bool uploadBinary bool<|fim▁hole|> flag.BoolVar(&runAllTest,"runtest", true, "Run all Tests") flag.BoolVar(&buildLocalBinary,"buildbinary", true, "Build local GoAgent binary" ) flag.BoolVar(&buildAll,"buildall", false, "Build GoAgent binary for all platforms" ) flag.BoolVar(&uploadBinary,"upload", false, "Upload GoAgent binary to bintray") flag.Parse() pwd, err := os.Getwd() if err == nil { os.Setenv("GOPATH",pwd) os.Setenv("GOBIN", pwd + "/bin") } getDependencies(excludeLib) if runAllTest { runTest(pwd) } if buildAll { buildBinary(pwd,true) }else{ if buildLocalBinary { buildBinary(pwd, false) } } if uploadBinary { uploadToBintray(pwd,true) } }<|fim▁end|>
) flag.StringVar(&excludeLib, "excludelib", "", "exclude dependencies in comma separated format, eg github.com/gocd-contrib/fake_agent,github.com/gocd-contrib/fake_server")
<|file_name|>size_of.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use script::dom::characterdata::CharacterData; use script::dom::element::Element; use script::dom::eventtarget::EventTarget; use script::dom::htmldivelement::HTMLDivElement; use script::dom::htmlelement::HTMLElement;<|fim▁hole|>use script::dom::node::Node; use script::dom::text::Text; use std::mem::size_of; // Macro so that we can stringify type names // I'd really prefer the tests themselves to be run at plugin time, // however rustc::middle doesn't have access to the full type data macro_rules! sizeof_checker ( ($testname: ident, $t:ty, $known_size:expr) => ( #[test] fn $testname() { let new = size_of::<$t>(); let old = $known_size; if new < old { panic!("Your changes have decreased the stack size of commonly used DOM struct {} from {} to {}. \ Good work! Please update the size in script/tests.rs", stringify!($t), old, new) } else if new > old { panic!("Your changes have increased the stack size of commonly used DOM struct {} from {} to {}. \ These structs are present in large quantities in the DOM, and increasing the size \ may dramatically affect our memory footprint. Please consider choosing a design which \ avoids this increase. If you feel that the increase is necessary, \ update to the new size in script/tests.rs.", stringify!($t), old, new) } }); ); // Update the sizes here sizeof_checker!(size_event_target, EventTarget, 40); sizeof_checker!(size_node, Node, 160); sizeof_checker!(size_element, Element, 312); sizeof_checker!(size_htmlelement, HTMLElement, 328); sizeof_checker!(size_div, HTMLDivElement, 328); sizeof_checker!(size_span, HTMLSpanElement, 328); sizeof_checker!(size_text, Text, 192); sizeof_checker!(size_characterdata, CharacterData, 192);<|fim▁end|>
use script::dom::htmlspanelement::HTMLSpanElement;
<|file_name|>download_samples.py<|end_file_name|><|fim▁begin|>""" RenderPipeline <|fim▁hole|>of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ """ Script to download the Render Pipeline samples """ import os import sys sys.path.insert(0, "../") sys.path.insert(0, "../rpcore/util") from submodule_downloader import download_submodule if __name__ == "__main__": # Make sure we are in the right directory main_dir = os.path.dirname(os.path.realpath(__file__)) os.chdir(main_dir) # Now extract the samples download_submodule("tobspr", "RenderPipeline-Samples", ".", ["README.md", "LICENSE"])<|fim▁end|>
Copyright (c) 2014-2016 tobspr <tobias.springer1@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy
<|file_name|>noise.py<|end_file_name|><|fim▁begin|>import numpy import random import math from exit_weight import * from privexUtils import resolution<|fim▁hole|> sigma_i = p_exit*sigma/math.sqrt(sum_of_sq) random_sample = random.gauss(0,sigma_i) return random_sample # return 0<|fim▁end|>
#def Noise(sensitivity, epsilon, delta, fingerprint, sigma): def Noise(sigma, fingerprint, sum_of_sq, p_exit):
<|file_name|>l2fib_vppcalls.go<|end_file_name|><|fim▁begin|>// Copyright (c) 2017 Cisco and/or its affiliates. // // 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. package vppcalls import ( "errors" "net" l2ba "github.com/ligato/vpp-agent/plugins/vpp/binapi/l2" l2nb "github.com/ligato/vpp-agent/plugins/vppv2/model/l2" ) // AddL2FIB creates L2 FIB table entry. func (h *FIBVppHandler) AddL2FIB(fib *l2nb.FIBEntry) error { return h.l2fibAddDel(fib, true) } // DeleteL2FIB removes existing L2 FIB table entry. func (h *FIBVppHandler) DeleteL2FIB(fib *l2nb.FIBEntry) error { return h.l2fibAddDel(fib, false) } func (h *FIBVppHandler) l2fibAddDel(fib *l2nb.FIBEntry, isAdd bool) (err error) { // get bridge domain metadata bdMeta, found := h.bdIndexes.LookupByName(fib.BridgeDomain) if !found { return errors.New("failed to get bridge domain metadata") } // get outgoing interface index swIfIndex := ^uint32(0) // ~0 is used by DROP entries if fib.Action == l2nb.FIBEntry_FORWARD { ifaceMeta, found := h.ifIndexes.LookupByName(fib.OutgoingInterface) if !found { return errors.New("failed to get interface metadata") } swIfIndex = ifaceMeta.GetIndex()<|fim▁hole|> // parse MAC address var mac []byte if fib.PhysAddress != "" { mac, err = net.ParseMAC(fib.PhysAddress) if err != nil { return err } } // add L2 FIB req := &l2ba.L2fibAddDel{ IsAdd: boolToUint(isAdd), Mac: mac, BdID: bdMeta.GetIndex(), SwIfIndex: swIfIndex, BviMac: boolToUint(fib.BridgedVirtualInterface), StaticMac: boolToUint(fib.StaticConfig), FilterMac: boolToUint(fib.Action == l2nb.FIBEntry_DROP), } reply := &l2ba.L2fibAddDelReply{} if err := h.callsChannel.SendRequest(req).ReceiveReply(reply); err != nil { return err } return nil }<|fim▁end|>
}
<|file_name|>launcher.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2010-2011 # Drakmail < drakmail@gmail.com > # NomerUNO < uno.kms@gmail.com > # Platon Peacel☮ve <platonny@ngs.ru> # Elec.Lomy.RU <Elec.Lomy.RU@gmail.com> # ADcomp <david.madbox@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os from Queue import Queue from subprocess import Popen from debug import logINFO devnull = open(os.path.devnull, 'w') q = None def start():<|fim▁hole|> def stop(): while not q.empty(): q.get() q.task_done() q.join() def check_programs(): programs = [] while not q.empty(): program = q.get() if program.poll() == None: programs.append(program) q.task_done() for program in programs: q.put(program) return True def launch_command(cmd): try: p = Popen(cmd, stdout = devnull, stderr = devnull ) q.put(p) except OSError, e: logINFO("unable to execute a command: %s : %s" % (repr(cmd), repr(e) ))<|fim▁end|>
global q q = Queue()
<|file_name|>SessionFactoryImplementor.java<|end_file_name|><|fim▁begin|>//$Id: SessionFactoryImplementor.java 8754 2005-12-05 23:36:59Z steveebersole $ package org.hibernate.engine; import java.util.Map; import java.util.Set; import java.sql.Connection; import javax.transaction.TransactionManager; import org.hibernate.HibernateException; import org.hibernate.Interceptor; import org.hibernate.MappingException; import org.hibernate.SessionFactory; import org.hibernate.ConnectionReleaseMode; import org.hibernate.engine.query.QueryPlanCache; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.cache.Cache; import org.hibernate.cache.QueryCache; import org.hibernate.cache.UpdateTimestampsCache; import org.hibernate.cfg.Settings; import org.hibernate.connection.ConnectionProvider; import org.hibernate.dialect.Dialect; import org.hibernate.exception.SQLExceptionConverter; import org.hibernate.id.IdentifierGenerator; import org.hibernate.stat.StatisticsImplementor; import org.hibernate.type.Type; /** * Defines the internal contract between the <tt>SessionFactory</tt> and other parts of * Hibernate such as implementors of <tt>Type</tt>. * * @see org.hibernate.SessionFactory * @see org.hibernate.impl.SessionFactoryImpl * @author Gavin King */ public interface SessionFactoryImplementor extends Mapping, SessionFactory { /** * Get the persister for the named entity */ public EntityPersister getEntityPersister(String entityName) throws MappingException; /** * Get the persister object for a collection role */ public CollectionPersister getCollectionPersister(String role) throws MappingException; /** * Get the SQL <tt>Dialect</tt> */ public Dialect getDialect(); public Interceptor getInterceptor(); public QueryPlanCache getQueryPlanCache(); /** * Get the return types of a query */ public Type[] getReturnTypes(String queryString) throws HibernateException; /** * Get the return aliases of a query */ public String[] getReturnAliases(String queryString) throws HibernateException; /** * Get the connection provider */ public ConnectionProvider getConnectionProvider(); /** * Get the names of all persistent classes that implement/extend the given interface/class */ public String[] getImplementors(String className) throws MappingException; /** * Get a class name, using query language imports */ public String getImportedClassName(String name); /** * Get the JTA transaction manager */ public TransactionManager getTransactionManager(); /** * Get the default query cache */ public QueryCache getQueryCache(); /** * Get a particular named query cache, or the default cache * @param regionName the name of the cache region, or null for the default query cache * @return the existing cache, or a newly created cache if none by that region name */ public QueryCache getQueryCache(String regionName) throws HibernateException; /** * Get the cache of table update timestamps */ public UpdateTimestampsCache getUpdateTimestampsCache(); /** * Statistics SPI */ public StatisticsImplementor getStatisticsImplementor(); public NamedQueryDefinition getNamedQuery(String queryName);<|fim▁hole|> /** * Get the identifier generator for the hierarchy */ public IdentifierGenerator getIdentifierGenerator(String rootEntityName); /** * Get a named second-level cache region */ public Cache getSecondLevelCacheRegion(String regionName); public Map getAllSecondLevelCacheRegions(); /** * Retrieves the SQLExceptionConverter in effect for this SessionFactory. * * @return The SQLExceptionConverter for this SessionFactory. */ public SQLExceptionConverter getSQLExceptionConverter(); public Settings getSettings(); /** * Get a nontransactional "current" session for Hibernate EntityManager */ public org.hibernate.classic.Session openTemporarySession() throws HibernateException; /** * Open a session conforming to the given parameters. Used mainly by * {@link org.hibernate.context.JTASessionContext} for current session processing. * * @param connection The external jdbc connection to use, if one (i.e., optional). * @param flushBeforeCompletionEnabled Should the session be auto-flushed * prior to transaction completion? * @param autoCloseSessionEnabled Should the session be auto-closed after * transaction completion? * @param connectionReleaseMode The release mode for managed jdbc connections. * @return An appropriate session. * @throws HibernateException */ public org.hibernate.classic.Session openSession( final Connection connection, final boolean flushBeforeCompletionEnabled, final boolean autoCloseSessionEnabled, final ConnectionReleaseMode connectionReleaseMode) throws HibernateException; /** * Retrieves a set of all the collection roles in which the given entity * is a participant, as either an index or an element. * * @param entityName The entity name for which to get the collection roles. * @return set of all the collection roles in which the given entityName participates. */ public Set getCollectionRolesByEntityParticipant(String entityName); }<|fim▁end|>
public NamedSQLQueryDefinition getNamedSQLQuery(String queryName); public ResultSetMappingDefinition getResultSetMapping(String name);
<|file_name|>rule.js<|end_file_name|><|fim▁begin|>const _ = require('lodash') const Joi = require('joi') module.exports = { name: 'href', params: { href: Joi.array().items( Joi.string(), Joi.func().ref() ).min(1) }, setup (params) { params.href = [''].concat(params.href) this._flags.href = params.href }, validate (params, value, state, options) { let parts = value.split('/').slice(1) if (!parts.every((p) => _.size(p) > 0)) { return this.createError('link.href', { v: value }, state, options) } else { return value } }<|fim▁hole|><|fim▁end|>
}
<|file_name|>iterators.ts<|end_file_name|><|fim▁begin|>export class IterationResult<T> { public done: boolean; public value: T | undefined | null; constructor(done: boolean, value: T | undefined) { this.done = done; this.value = value;<|fim▁hole|>} export enum IterationHint { NONE = 0, SKIP_DESCENDANTS = 1 << 0, } export const DONE_TOKEN = new IterationResult(true, undefined); export function ready<T>(value: T) { return new IterationResult(false, value); } export interface IIterator<T> { next(hint: IterationHint): IterationResult<T>; }<|fim▁end|>
}
<|file_name|>Create_Modify_Interface.py<|end_file_name|><|fim▁begin|>## This file is part of Invenio. ## Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """ This is the Create_Modify_Interface function (along with its helpers). It is used by WebSubmit for the "Modify Bibliographic Information" action. """ __revision__ = "$Id$" import os import re import time import pprint import cgi from invenio.dbquery import run_sql from invenio.websubmit_config import InvenioWebSubmitFunctionError from invenio.websubmit_functions.Retrieve_Data import Get_Field from invenio.errorlib import register_exception from invenio.htmlutils import escape_javascript_string from invenio.messages import gettext_set_language, wash_language def Create_Modify_Interface_getfieldval_fromfile(cur_dir, fld=""): """Read a field's value from its corresponding text file in 'cur_dir' (if it exists) into memory. Delete the text file after having read-in its value. This function is called on the reload of the modify-record page. This way, the field in question can be populated with the value last entered by the user (before reload), instead of always being populated with the value still found in the DB. """ fld_val = "" if len(fld) > 0 and os.access("%s/%s" % (cur_dir, fld), os.R_OK|os.W_OK): fp = open( "%s/%s" % (cur_dir, fld), "r" ) fld_val = fp.read() fp.close() try: os.unlink("%s/%s"%(cur_dir, fld)) except OSError: # Cannot unlink file - ignore, let WebSubmit main handle this pass fld_val = fld_val.strip() return fld_val def Create_Modify_Interface_getfieldval_fromDBrec(fieldcode, recid): """Read a field's value from the record stored in the DB. This function is called when the Create_Modify_Interface function is called for the first time when modifying a given record, and field values must be retrieved from the database. """ fld_val = "" if fieldcode != "": for next_field_code in [x.strip() for x in fieldcode.split(",")]: fld_val += "%s\n" % Get_Field(next_field_code, recid) fld_val = fld_val.rstrip('\n') return fld_val def Create_Modify_Interface_transform_date(fld_val): """Accept a field's value as a string. If the value is a date in one of the following formats: DD Mon YYYY (e.g. 23 Apr 2005) YYYY-MM-DD (e.g. 2005-04-23) ...transform this date value into "DD/MM/YYYY" (e.g. 23/04/2005). """ if re.search("^[0-9]{2} [a-z]{3} [0-9]{4}$", fld_val, re.IGNORECASE) is not None: try: fld_val = time.strftime("%d/%m/%Y", time.strptime(fld_val, "%d %b %Y")) except (ValueError, TypeError): # bad date format: pass elif re.search("^[0-9]{4}-[0-9]{2}-[0-9]{2}$", fld_val, re.IGNORECASE) is not None: try: fld_val = time.strftime("%d/%m/%Y", time.strptime(fld_val, "%Y-%m-%d")) except (ValueError,TypeError): # bad date format: pass return fld_val def Create_Modify_Interface(parameters, curdir, form, user_info=None): """ Create an interface for the modification of a document, based on the fields that the user has chosen to modify. This avoids having<|fim▁hole|> the elements already defined for the initial submission i.e. SBI action (The only page that needs to be built for the modification is the page letting the user specify a document to modify). This function should be added at step 1 of your modification workflow, after the functions that retrieves report number and record id (Get_Report_Number, Get_Recid). Functions at step 2 are the one executed upon successful submission of the form. Create_Modify_Interface expects the following parameters: * "fieldnameMBI" - the name of a text file in the submission working directory that contains a list of the names of the WebSubmit fields to include in the Modification interface. These field names are separated by"\n" or "+". * "prefix" - some content displayed before the main modification interface. Can contain HTML (i.e. needs to be pre-escaped). The prefix can make use of Python string replacement for common values (such as 'rn'). Percent signs (%) must consequently be escaped (with %%). * "suffix" - some content displayed after the main modification interface. Can contain HTML (i.e. needs to be pre-escaped). The suffix can make use of Python string replacement for common values (such as 'rn'). Percent signs (%) must consequently be escaped (with %%). * "button_label" - the label for the "END" button. * "button_prefix" - some content displayed before the button to submit the form. Can contain HTML (i.e. needs to be pre-escaped). The prefix can make use of Python string replacement for common values (such as 'rn'). Percent signs (%) must consequently be escaped (with %%). * "dates_conversion" - by default, values interpreted as dates are converted to their 'DD/MM/YYYY' format, whenever possible. Set another value for a different behaviour (eg. 'none' for no conversion) Given the list of WebSubmit fields to be included in the modification interface, the values for each field are retrieved for the given record (by way of each WebSubmit field being configured with a MARC Code in the WebSubmit database). An HTML FORM is then created. This form allows a user to modify certain field values for a record. The file referenced by 'fieldnameMBI' is usually generated from a multiple select form field): users can then select one or several fields to modify Note that the function will display WebSubmit Response elements, but will not be able to set an initial value: this must be done by the Response element iteself. Additionally the function creates an internal field named 'Create_Modify_Interface_DONE' on the interface, that can be retrieved in curdir after the form has been submitted. This flag is an indicator for the function that displayed values should not be retrieved from the database, but from the submitted values (in case the page is reloaded). You can also rely on this value when building your WebSubmit Response element in order to retrieve value either from the record, or from the submission directory. """ ln = wash_language(form['ln']) _ = gettext_set_language(ln) global sysno,rn t = "" # variables declaration fieldname = parameters['fieldnameMBI'] prefix = '' suffix = '' end_button_label = 'END' end_button_prefix = '' date_conversion_setting = '' if parameters.has_key('prefix'): prefix = parameters['prefix'] if parameters.has_key('suffix'): suffix = parameters['suffix'] if parameters.has_key('button_label') and parameters['button_label']: end_button_label = parameters['button_label'] if parameters.has_key('button_prefix'): end_button_prefix = parameters['button_prefix'] if parameters.has_key('dates_conversion'): date_conversion_setting = parameters['dates_conversion'] # Path of file containing fields to modify the_globals = { 'doctype' : doctype, 'action' : action, 'act' : action, ## for backward compatibility 'step' : step, 'access' : access, 'ln' : ln, 'curdir' : curdir, 'uid' : user_info['uid'], 'uid_email' : user_info['email'], 'rn' : rn, 'last_step' : last_step, 'action_score' : action_score, '__websubmit_in_jail__' : True, 'form': form, 'sysno': sysno, 'user_info' : user_info, '__builtins__' : globals()['__builtins__'], 'Request_Print': Request_Print } if os.path.exists("%s/%s" % (curdir, fieldname)): fp = open( "%s/%s" % (curdir, fieldname), "r" ) fieldstext = fp.read() fp.close() fieldstext = re.sub("\+","\n", fieldstext) fields = fieldstext.split("\n") else: res = run_sql("SELECT fidesc FROM sbmFIELDDESC WHERE name=%s", (fieldname,)) if len(res) == 1: fields = res[0][0].replace(" ", "") fields = re.findall("<optionvalue=.*>", fields) regexp = re.compile("""<optionvalue=(?P<quote>['|"]?)(?P<value>.*?)(?P=quote)""") fields = [regexp.search(x) for x in fields] fields = [x.group("value") for x in fields if x is not None] fields = [x for x in fields if x not in ("Select", "select")] else: raise InvenioWebSubmitFunctionError("cannot find fields to modify") #output some text if not prefix: t += "<center bgcolor=\"white\">The document <b>%s</b> has been found in the database.</center><br />Please modify the following fields:<br />Then press the '%s' button at the bottom of the page<br />\n" % \ (rn, cgi.escape(_(end_button_label))) else: t += prefix % the_globals for field in fields: subfield = "" value = "" marccode = "" text = "" # retrieve and display the modification text t = t + "<FONT color=\"darkblue\">\n" res = run_sql("SELECT modifytext FROM sbmFIELDDESC WHERE name=%s", (field,)) if len(res)>0: t = t + "<small>%s</small> </FONT>\n" % res[0][0] # retrieve the marc code associated with the field res = run_sql("SELECT marccode FROM sbmFIELDDESC WHERE name=%s", (field,)) if len(res) > 0: marccode = res[0][0] # then retrieve the previous value of the field if os.path.exists("%s/%s" % (curdir, "Create_Modify_Interface_DONE")): # Page has been reloaded - get field value from text file on server, not from DB record value = Create_Modify_Interface_getfieldval_fromfile(curdir, field) else: # First call to page - get field value from DB record value = Create_Modify_Interface_getfieldval_fromDBrec(marccode, sysno) if date_conversion_setting != 'none': # If field is a date value, transform date into format DD/MM/YYYY: value = Create_Modify_Interface_transform_date(value) res = run_sql("SELECT * FROM sbmFIELDDESC WHERE name=%s", (field,)) # kwalitee: disable=sql if len(res) > 0: element_type = res[0][3] numcols = res[0][6] numrows = res[0][5] size = res[0][4] maxlength = res[0][7] val = res[0][8] fidesc = res[0][9] if element_type == "T": text = "<textarea name=\"%s\" rows=%s cols=%s wrap>%s</textarea>" % (field, numrows, numcols, cgi.escape(value)) elif element_type == "F": text = "<input type=\"file\" name=\"%s\" size=%s maxlength=\"%s\">" % (field, size, maxlength) elif element_type == "I": text = "<input name=\"%s\" size=%s value=\"%s\"> " % (field, size, val and escape_javascript_string(val, escape_quote_for_html=True) or '') text = text + '''<script type="text/javascript">/*<![CDATA[*/ document.forms[0].%s.value="%s"; /*]]>*/</script>''' % (field, escape_javascript_string(value, escape_for_html=False)) elif element_type == "H": text = "<input type=\"hidden\" name=\"%s\" value=\"%s\">" % (field, val and escape_javascript_string(val, escape_quote_for_html=True) or '') text = text + '''<script type="text/javascript">/*<![CDATA[*/ document.forms[0].%s.value="%s"; /*]]>*/</script>''' % (field, escape_javascript_string(value, escape_for_html=False)) elif element_type == "S": values = re.split("[\n\r]+", value) text = fidesc if re.search("%s\[\]" % field, fidesc): multipletext = "[]" else: multipletext = "" if len(values) > 0 and not(len(values) == 1 and values[0] == ""): text += '<script type="text/javascript">/*<![CDATA[*/\n' text += "var i = 0;\n" text += "el = document.forms[0].elements['%s%s'];\n" % (field, multipletext) text += "max = el.length;\n" for val in values: text += "var found = 0;\n" text += "var i=0;\n" text += "while (i != max) {\n" text += " if (el.options[i].value == \"%s\" || el.options[i].text == \"%s\") {\n" % \ (escape_javascript_string(val, escape_for_html=False), escape_javascript_string(val, escape_for_html=False)) text += " el.options[i].selected = true;\n" text += " found = 1;\n" text += " }\n" text += " i=i+1;\n" text += "}\n" #text += "if (found == 0) {\n" #text += " el[el.length] = new Option(\"%s\", \"%s\", 1,1);\n" #text += "}\n" text += "/*]]>*/</script>\n" elif element_type == "D": text = fidesc elif element_type == "R": try: co = compile(fidesc.replace("\r\n", "\n"), "<string>", "exec") ## Note this exec is safe WRT global variable because the ## Create_Modify_Interface has already been parsed by ## execfile within a protected environment. the_globals['text'] = '' exec co in the_globals text = the_globals['text'] except: msg = "Error in evaluating response element %s with globals %s" % (pprint.pformat(field), pprint.pformat(globals())) register_exception(req=None, alert_admin=True, prefix=msg) raise InvenioWebSubmitFunctionError(msg) else: text = "%s: unknown field type" % field t = t + "<small>%s</small>" % text # output our flag field t += '<input type="hidden" name="Create_Modify_Interface_DONE" value="DONE\n" />' t += '<br />' if end_button_prefix: t += end_button_prefix % the_globals # output some more text t += "<br /><CENTER><small><INPUT type=\"button\" width=400 height=50 name=\"End\" value=\"%(end_button_label)s\" onClick=\"document.forms[0].step.value = 2;user_must_confirm_before_leaving_page = false;document.forms[0].submit();\"></small></CENTER></H4>" % {'end_button_label': escape_javascript_string(_(end_button_label), escape_quote_for_html=True)} if suffix: t += suffix % the_globals return t<|fim▁end|>
to redefine a submission page for the modifications, but rely on
<|file_name|>VictimCollector.java<|end_file_name|><|fim▁begin|>/* * Copyright 2000-2009 JetBrains s.r.o. * * 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. */ package com.intellij.refactoring.typeCook.deductive.util; import com.intellij.psi.*; import com.intellij.refactoring.typeCook.Settings; import com.intellij.refactoring.typeCook.Util; import java.util.HashSet; /** * @author db */ public class VictimCollector extends Visitor { final HashSet<PsiElement> myVictims = new HashSet<PsiElement>(); final PsiElement[] myElements; final Settings mySettings; public VictimCollector(final PsiElement[] elements, final Settings settings) { myElements = elements; mySettings = settings; } private void testNAdd(final PsiElement element, final PsiType t) { if (Util.isRaw(t, mySettings)) { if (element instanceof PsiNewExpression && t.getCanonicalText().equals("java.lang.Object")){ return; } myVictims.add(element); } } @Override public void visitLocalVariable(final PsiLocalVariable variable) { testNAdd(variable, variable.getType()); super.visitLocalVariable(variable); } @Override public void visitForeachStatement(final PsiForeachStatement statement) { super.visitForeachStatement(statement); final PsiParameter parameter = statement.getIterationParameter(); testNAdd(parameter, parameter.getType()); } @Override public void visitField(final PsiField field) { testNAdd(field, field.getType()); super.visitField(field); } @Override public void visitMethod(final PsiMethod method) { final PsiParameter[] parms = method.getParameterList().getParameters(); for (PsiParameter parm : parms) { testNAdd(parm, parm.getType()); } if (Util.isRaw(method.getReturnType(), mySettings)) { myVictims.add(method); } final PsiCodeBlock body = method.getBody(); <|fim▁hole|> } @Override public void visitNewExpression(final PsiNewExpression expression) { if (expression.getClassReference() != null) { testNAdd(expression, expression.getType()); } super.visitNewExpression(expression); } @Override public void visitTypeCastExpression (final PsiTypeCastExpression cast){ final PsiTypeElement typeElement = cast.getCastType(); if (typeElement != null) { testNAdd(cast, typeElement.getType()); } super.visitTypeCastExpression(cast); } @Override public void visitReferenceExpression(final PsiReferenceExpression expression) { } @Override public void visitFile(PsiFile file) { if (file instanceof PsiJavaFile) { super.visitFile(file); } } public HashSet<PsiElement> getVictims() { for (PsiElement element : myElements) { element.accept(this); } return myVictims; } }<|fim▁end|>
if (body != null) { body.accept(this); }
<|file_name|>shared_vec_slice.rs<|end_file_name|><|fim▁begin|>use std::sync::Arc; <|fim▁hole|> pub data: Arc<Vec<u8>>, pub start: usize, pub len: usize, } impl SharedVecSlice { pub fn empty() -> SharedVecSlice { SharedVecSlice::new(Arc::new(Vec::new())) } pub fn new(data: Arc<Vec<u8>>) -> SharedVecSlice { let data_len = data.len(); SharedVecSlice { data: data, start: 0, len: data_len, } } pub fn as_slice(&self) -> &[u8] { &self.data[self.start..self.start + self.len] } pub fn slice(&self, from_offset: usize, to_offset: usize) -> SharedVecSlice { SharedVecSlice { data: self.data.clone(), start: self.start + from_offset, len: to_offset - from_offset, } } }<|fim▁end|>
#[derive(Clone)] pub struct SharedVecSlice {
<|file_name|>bigip_gtm_server.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2017, F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'certified'} DOCUMENTATION = r''' --- module: bigip_gtm_server short_description: Manages F5 BIG-IP GTM servers description: - Manage BIG-IP server configuration. This module is able to manipulate the server definitions in a BIG-IP. version_added: 2.5 options: name: description: - The name of the server. required: True state: description: - The server state. If C(absent), an attempt to delete the server will be made. This will only succeed if this server is not in use by a virtual server. C(present) creates the server and enables it. If C(enabled), enable the server if it exists. If C(disabled), create the server if needed, and set state to C(disabled). default: present choices: - present - absent - enabled - disabled datacenter: description: - Data center the server belongs to. When creating a new GTM server, this value is required. devices: description: - Lists the self IP addresses and translations for each device. When creating a new GTM server, this value is required. This list is a complex list that specifies a number of keys. - The C(name) key specifies a name for the device. The device name must be unique per server. This key is required. - The C(address) key contains an IP address, or list of IP addresses, for the destination server. This key is required. - The C(translation) key contains an IP address to translate the C(address) value above to. This key is optional. - Specifying duplicate C(name) fields is a supported means of providing device addresses. In this scenario, the addresses will be assigned to the C(name)'s list of addresses. server_type: description: - Specifies the server type. The server type determines the metrics that the system can collect from the server. When creating a new GTM server, the default value C(bigip) is used. choices: - alteon-ace-director - cisco-css - cisco-server-load-balancer - generic-host - radware-wsd - windows-nt-4.0 - bigip - cisco-local-director-v2 - extreme - generic-load-balancer - sun-solaris - cacheflow - cisco-local-director-v3 - foundry-server-iron - netapp - windows-2000-server aliases: - product link_discovery: description: - Specifies whether the system auto-discovers the links for this server. When creating a new GTM server, if this parameter is not specified, the default value C(disabled) is used. - If you set this parameter to C(enabled) or C(enabled-no-delete), you must also ensure that the C(virtual_server_discovery) parameter is also set to C(enabled) or C(enabled-no-delete). choices: - enabled - disabled - enabled-no-delete virtual_server_discovery: description: - Specifies whether the system auto-discovers the virtual servers for this server. When creating a new GTM server, if this parameter is not specified, the default value C(disabled) is used. choices: - enabled - disabled - enabled-no-delete partition: description: - Device partition to manage resources on. default: Common version_added: 2.5 iquery_options: description: - Specifies whether the Global Traffic Manager uses this BIG-IP system to conduct a variety of probes before delegating traffic to it. suboptions: allow_path: description: - Specifies that the system verifies the logical network route between a data center server and a local DNS server. type: bool allow_service_check: description: - Specifies that the system verifies that an application on a server is running, by remotely running the application using an external service checker program. type: bool allow_snmp: description: - Specifies that the system checks the performance of a server running an SNMP agent. type: bool version_added: 2.7 monitors: description: - Specifies the health monitors that the system currently uses to monitor this resource. - When C(availability_requirements.type) is C(require), you may only have a single monitor in the C(monitors) list. version_added: 2.8 availability_requirements: description: - Specifies, if you activate more than one health monitor, the number of health monitors that must receive successful responses in order for the link to be considered available. suboptions: type: description: - Monitor rule type when C(monitors) is specified. - When creating a new pool, if this value is not specified, the default of 'all' will be used. choices: ['all', 'at_least', 'require'] at_least: description: - Specifies the minimum number of active health monitors that must be successful before the link is considered up. - This parameter is only relevant when a C(type) of C(at_least) is used. - This parameter will be ignored if a type of either C(all) or C(require) is used. number_of_probes: description: - Specifies the minimum number of probes that must succeed for this server to be declared up. - When creating a new virtual server, if this parameter is specified, then the C(number_of_probers) parameter must also be specified. - The value of this parameter should always be B(lower) than, or B(equal to), the value of C(number_of_probers). - This parameter is only relevant when a C(type) of C(require) is used. - This parameter will be ignored if a type of either C(all) or C(at_least) is used. number_of_probers: description: - Specifies the number of probers that should be used when running probes. - When creating a new virtual server, if this parameter is specified, then the C(number_of_probes) parameter must also be specified. - The value of this parameter should always be B(higher) than, or B(equal to), the value of C(number_of_probers). - This parameter is only relevant when a C(type) of C(require) is used. - This parameter will be ignored if a type of either C(all) or C(at_least) is used. version_added: 2.8 prober_preference: description: - Specifies the type of prober to use to monitor this server's resources. - This option is ignored in C(TMOS) version C(12.x). - From C(TMOS) version C(13.x) and up, when prober_preference is set to C(pool) a C(prober_pool) parameter must be specified. choices: - inside-datacenter - outside-datacenter - inherit - pool version_added: 2.8 prober_fallback: description: - Specifies the type of prober to use to monitor this server's resources when the preferred prober is not available. - This option is ignored in C(TMOS) version C(12.x). - From C(TMOS) version C(13.x) and up, when prober_preference is set to C(pool) a C(prober_pool) parameter must be specified. - The choices are mutually exclusive with prober_preference parameter, with the exception of C(any-available) or C(none) option. choices: - any - inside-datacenter - outside-datacenter - inherit - pool - none version_added: 2.8 prober_pool: description: - Specifies the name of the prober pool to use to monitor this server's resources. - From C(TMOS) version C(13.x) and up, this parameter is mandatory when C(prober_preference) is set to C(pool). - Format of the name can be either be prepended by partition (C(/Common/foo)), or specified just as an object name (C(foo)). - In C(TMOS) version C(12.x) prober_pool can be set to empty string to revert to default setting of inherit. version_added: 2.8 limits: description: - Specifies resource thresholds or limit requirements at the pool member level. - When you enable one or more limit settings, the system then uses that data to take members in and out of service. - You can define limits for any or all of the limit settings. However, when a member does not meet the resource threshold limit requirement, the system marks the member as unavailable and directs load-balancing traffic to another resource. version_added: 2.8 suboptions: bits_enabled: description: - Whether the bits limit it enabled or not. - This parameter allows you to switch on or off the effect of the limit. type: bool packets_enabled: description: - Whether the packets limit it enabled or not. - This parameter allows you to switch on or off the effect of the limit. type: bool connections_enabled: description: - Whether the current connections limit it enabled or not. - This parameter allows you to switch on or off the effect of the limit. type: bool cpu_enabled: description: - Whether the CPU limit it enabled or not. - This parameter allows you to switch on or off the effect of the limit. type: bool memory_enabled: description: - Whether the memory limit it enabled or not. - This parameter allows you to switch on or off the effect of the limit. type: bool bits_limit: description: - Specifies the maximum allowable data throughput rate, in bits per second, for the member. - If the network traffic volume exceeds this limit, the system marks the member as unavailable. packets_limit: description: - Specifies the maximum allowable data transfer rate, in packets per second, for the member. - If the network traffic volume exceeds this limit, the system marks the member as unavailable. connections_limit: description: - Specifies the maximum number of concurrent connections, combined, for all of the member. - If the connections exceed this limit, the system marks the server as unavailable. cpu_limit: description: - Specifies the percent of CPU usage. - If percent of CPU usage goes above the limit, the system marks the server as unavailable. memory_limit: description: - Specifies the available memory required by the virtual servers on the server. - If available memory falls below this limit, the system marks the server as unavailable. extends_documentation_fragment: f5 author: - Robert Teller (@r-teller) - Tim Rupp (@caphrim007) - Wojciech Wypior (@wojtek0806) ''' EXAMPLES = r''' - name: Create server "GTM_Server" bigip_gtm_server: name: GTM_Server datacenter: /Common/New York server_type: bigip link_discovery: disabled virtual_server_discovery: disabled devices: - name: server_1 address: 1.1.1.1 - name: server_2 address: 2.2.2.1 translation: 192.168.2.1 - name: server_2 address: 2.2.2.2 - name: server_3 addresses: - address: 3.3.3.1 - address: 3.3.3.2 - name: server_4 addresses: - address: 4.4.4.1 translation: 192.168.14.1 - address: 4.4.4.2 provider: user: admin password: secret server: lb.mydomain.com delegate_to: localhost - name: Create server "GTM_Server" with expanded keys bigip_gtm_server: server: lb.mydomain.com user: admin password: secret name: GTM_Server datacenter: /Common/New York server_type: bigip link_discovery: disabled virtual_server_discovery: disabled devices: - name: server_1 address: 1.1.1.1 - name: server_2 address: 2.2.2.1 translation: 192.168.2.1 - name: server_2 address: 2.2.2.2 - name: server_3 addresses: - address: 3.3.3.1 - address: 3.3.3.2 - name: server_4 addresses: - address: 4.4.4.1 translation: 192.168.14.1 - address: 4.4.4.2 provider: user: admin password: secret server: lb.mydomain.com delegate_to: localhost ''' RETURN = r''' bits_enabled: description: Whether the bits limit is enabled. returned: changed type: bool sample: yes bits_limit: description: The new bits_enabled limit. returned: changed type: int sample: 100 connections_enabled: description: Whether the connections limit is enabled. returned: changed type: bool sample: yes connections_limit: description: The new connections_limit limit. returned: changed type: int sample: 100 monitors: description: The new list of monitors for the resource. returned: changed type: list sample: ['/Common/monitor1', '/Common/monitor2'] link_discovery: description: The new C(link_discovery) configured on the remote device. returned: changed type: str sample: enabled virtual_server_discovery: description: The new C(virtual_server_discovery) name for the trap destination. returned: changed type: str sample: disabled server_type: description: The new type of the server. returned: changed type: str sample: bigip datacenter: description: The new C(datacenter) which the server is part of. returned: changed type: str sample: datacenter01 packets_enabled: description: Whether the packets limit is enabled. returned: changed type: bool sample: yes packets_limit: description: The new packets_limit limit. returned: changed type: int sample: 100 ''' import re from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import env_fallback from distutils.version import LooseVersion try: from library.module_utils.network.f5.bigip import F5RestClient from library.module_utils.network.f5.common import F5ModuleError from library.module_utils.network.f5.common import AnsibleF5Parameters from library.module_utils.network.f5.common import cleanup_tokens from library.module_utils.network.f5.common import fq_name from library.module_utils.network.f5.common import f5_argument_spec from library.module_utils.network.f5.common import transform_name from library.module_utils.network.f5.common import exit_json from library.module_utils.network.f5.common import fail_json from library.module_utils.network.f5.common import is_empty_list from library.module_utils.network.f5.icontrol import tmos_version from library.module_utils.network.f5.icontrol import module_provisioned except ImportError: from ansible.module_utils.network.f5.bigip import F5RestClient from ansible.module_utils.network.f5.common import F5ModuleError from ansible.module_utils.network.f5.common import AnsibleF5Parameters from ansible.module_utils.network.f5.common import cleanup_tokens from ansible.module_utils.network.f5.common import fq_name from ansible.module_utils.network.f5.common import f5_argument_spec from ansible.module_utils.network.f5.common import transform_name from ansible.module_utils.network.f5.common import exit_json from ansible.module_utils.network.f5.common import fail_json from ansible.module_utils.network.f5.common import is_empty_list from ansible.module_utils.network.f5.icontrol import tmos_version from ansible.module_utils.network.f5.icontrol import module_provisioned try: from collections import OrderedDict except ImportError: try: from ordereddict import OrderedDict except ImportError: pass class Parameters(AnsibleF5Parameters): api_map = { 'product': 'server_type', 'virtualServerDiscovery': 'virtual_server_discovery', 'linkDiscovery': 'link_discovery', 'addresses': 'devices', 'iqAllowPath': 'iquery_allow_path', 'iqAllowServiceCheck': 'iquery_allow_service_check', 'iqAllowSnmp': 'iquery_allow_snmp', 'monitor': 'monitors', 'proberPreference': 'prober_preference', 'proberPool': 'prober_pool', 'proberFallback': 'prober_fallback', 'limitMaxBps': 'bits_limit', 'limitMaxBpsStatus': 'bits_enabled', 'limitMaxConnections': 'connections_limit', 'limitMaxConnectionsStatus': 'connections_enabled', 'limitMaxPps': 'packets_limit', 'limitMaxPpsStatus': 'packets_enabled', 'limitCpuUsage': 'cpu_limit', 'limitCpuUsageStatus': 'cpu_enabled', 'limitMemAvail': 'memory_limit', 'limitMemAvailStatus': 'memory_enabled', } api_attributes = [ 'linkDiscovery', 'virtualServerDiscovery', 'product', 'addresses', 'datacenter', 'enabled', 'disabled', 'iqAllowPath', 'iqAllowServiceCheck', 'iqAllowSnmp', 'monitor', 'proberPreference', 'proberPool', 'proberFallback', 'limitMaxBps', 'limitMaxBpsStatus', 'limitMaxConnections', 'limitMaxConnectionsStatus', 'limitMaxPps', 'limitMaxPpsStatus', 'limitCpuUsage', 'limitCpuUsageStatus', 'limitMemAvail', 'limitMemAvailStatus', ] updatables = [ 'link_discovery', 'virtual_server_discovery', 'server_type_and_devices', 'datacenter', 'state', 'iquery_allow_path', 'iquery_allow_service_check', 'iquery_allow_snmp', 'monitors', 'prober_preference', 'prober_pool', 'prober_fallback', 'bits_enabled', 'bits_limit', 'connections_enabled', 'connections_limit', 'packets_enabled', 'packets_limit', 'cpu_enabled', 'cpu_limit', 'memory_enabled', 'memory_limit', ] returnables = [ 'link_discovery', 'virtual_server_discovery', 'server_type', 'datacenter', 'enabled', 'iquery_allow_path', 'iquery_allow_service_check', 'iquery_allow_snmp', 'devices', 'monitors', 'availability_requirements', 'prober_preference', 'prober_pool', 'prober_fallback', 'bits_enabled', 'bits_limit', 'connections_enabled', 'connections_limit', 'packets_enabled', 'packets_limit', 'cpu_enabled', 'cpu_limit', 'memory_enabled', 'memory_limit', ] class ApiParameters(Parameters): @property def devices(self): if self._values['devices'] is None: return None return self._values['devices'] @property def server_type(self): if self._values['server_type'] is None: return None elif self._values['server_type'] in ['single-bigip', 'redundant-bigip']: return 'bigip' else: return self._values['server_type'] @property def raw_server_type(self): if self._values['server_type'] is None: return None return self._values['server_type'] @property def enabled(self): if self._values['enabled'] is None: return None return True @property def disabled(self): if self._values['disabled'] is None: return None return True @property def iquery_allow_path(self): if self._values['iquery_allow_path'] is None: return None elif self._values['iquery_allow_path'] == 'yes': return True return False @property def iquery_allow_service_check(self): if self._values['iquery_allow_service_check'] is None: return None elif self._values['iquery_allow_service_check'] == 'yes': return True return False @property def iquery_allow_snmp(self): if self._values['iquery_allow_snmp'] is None: return None elif self._values['iquery_allow_snmp'] == 'yes': return True return False @property def availability_requirement_type(self): if self._values['monitors'] is None: return None if 'min ' in self._values['monitors']: return 'at_least' elif 'require ' in self._values['monitors']: return 'require' else: return 'all' @property def monitors_list(self): if self._values['monitors'] is None: return [] try: result = re.findall(r'/\w+/[^\s}]+', self._values['monitors']) result.sort() return result except Exception: return self._values['monitors'] @property def monitors(self): if self._values['monitors'] is None: return None if self._values['monitors'] == '/Common/bigip': return '/Common/bigip' monitors = [fq_name(self.partition, x) for x in self.monitors_list] if self.availability_requirement_type == 'at_least': monitors = ' '.join(monitors) result = 'min {0} of {{ {1} }}'.format(self.at_least, monitors) elif self.availability_requirement_type == 'require': monitors = ' '.join(monitors) result = 'require {0} from {1} {{ {2} }}'.format(self.number_of_probes, self.number_of_probers, monitors) else: result = ' and '.join(monitors).strip() return result @property def number_of_probes(self): """Returns the probes value from the monitor string. The monitor string for a Require monitor looks like this. require 1 from 2 { /Common/tcp } This method parses out the first of the numeric values. This values represents the "probes" value that can be updated in the module. Returns: int: The probes value if found. None otherwise. """ if self._values['monitors'] is None: return None pattern = r'require\s+(?P<probes>\d+)\s+from' matches = re.search(pattern, self._values['monitors']) if matches is None: return None return matches.group('probes') @property def number_of_probers(self): """Returns the probers value from the monitor string. The monitor string for a Require monitor looks like this. require 1 from 2 { /Common/tcp } This method parses out the first of the numeric values. This values represents the "probers" value that can be updated in the module. Returns: int: The probers value if found. None otherwise. """ if self._values['monitors'] is None: return None pattern = r'require\s+\d+\s+from\s+(?P<probers>\d+)\s+' matches = re.search(pattern, self._values['monitors']) if matches is None: return None return matches.group('probers') @property def at_least(self): """Returns the 'at least' value from the monitor string. The monitor string for a Require monitor looks like this. min 1 of { /Common/gateway_icmp } This method parses out the first of the numeric values. This values represents the "at_least" value that can be updated in the module. Returns: int: The at_least value if found. None otherwise. """ if self._values['monitors'] is None: return None pattern = r'min\s+(?P<least>\d+)\s+of\s+' matches = re.search(pattern, self._values['monitors']) if matches is None: return None return matches.group('least') class ModuleParameters(Parameters): def _get_limit_value(self, type): if self._values['limits'] is None: return None if self._values['limits'][type] is None: return None return int(self._values['limits'][type]) def _get_limit_status(self, type): if self._values['limits'] is None: return None if self._values['limits'][type] is None: return None if self._values['limits'][type]: return 'enabled' return 'disabled' @property def devices(self): if self._values['devices'] is None: return None result = [] for device in self._values['devices']: if not any(x for x in ['address', 'addresses'] if x in device): raise F5ModuleError( "The specified device list must contain an 'address' or 'addresses' key" ) if 'address' in device: translation = self._determine_translation(device) name = device['address'] device_name = device['name'] result.append({ 'name': name, 'deviceName': device_name, 'translation': translation }) elif 'addresses' in device: for address in device['addresses']: translation = self._determine_translation(address) name = address['address'] device_name = device['name'] result.append({ 'name': name, 'deviceName': device_name, 'translation': translation }) return result @property def enabled(self): if self._values['state'] in ['present', 'enabled']: return True return False @property def datacenter(self): if self._values['datacenter'] is None: return None return fq_name(self.partition, self._values['datacenter']) def _determine_translation(self, device): if 'translation' not in device: return 'none' return device['translation'] @property def state(self): if self._values['state'] == 'enabled': return 'present' return self._values['state'] @property def iquery_allow_path(self): if self._values['iquery_options'] is None: return None elif self._values['iquery_options']['allow_path'] is None: return None return self._values['iquery_options']['allow_path'] @property def iquery_allow_service_check(self): if self._values['iquery_options'] is None: return None elif self._values['iquery_options']['allow_service_check'] is None: return None return self._values['iquery_options']['allow_service_check'] @property def iquery_allow_snmp(self): if self._values['iquery_options'] is None: return None elif self._values['iquery_options']['allow_snmp'] is None: return None return self._values['iquery_options']['allow_snmp'] @property def monitors_list(self): if self._values['monitors'] is None: return [] try: result = re.findall(r'/\w+/[^\s}]+', self._values['monitors']) result.sort() return result except Exception: return self._values['monitors'] @property def monitors(self): if self._values['monitors'] is None: return None if is_empty_list(self._values['monitors']): return '/Common/bigip' monitors = [fq_name(self.partition, x) for x in self.monitors_list] if self.availability_requirement_type == 'at_least': if self.at_least > len(self.monitors_list): raise F5ModuleError( "The 'at_least' value must not exceed the number of 'monitors'." ) monitors = ' '.join(monitors) result = 'min {0} of {{ {1} }}'.format(self.at_least, monitors) elif self.availability_requirement_type == 'require': monitors = ' '.join(monitors) if self.number_of_probes > self.number_of_probers: raise F5ModuleError( "The 'number_of_probes' must not exceed the 'number_of_probers'." ) result = 'require {0} from {1} {{ {2} }}'.format(self.number_of_probes, self.number_of_probers, monitors) else: result = ' and '.join(monitors).strip() return result def _get_availability_value(self, type): if self._values['availability_requirements'] is None: return None if self._values['availability_requirements'][type] is None: return None return int(self._values['availability_requirements'][type]) @property def availability_requirement_type(self): if self._values['availability_requirements'] is None: return None return self._values['availability_requirements']['type'] @property def number_of_probes(self): return self._get_availability_value('number_of_probes') @property def number_of_probers(self): return self._get_availability_value('number_of_probers') @property def at_least(self): return self._get_availability_value('at_least') @property def prober_pool(self): if self._values['prober_pool'] is None: return None if self._values['prober_pool'] == '': return self._values['prober_pool'] result = fq_name(self.partition, self._values['prober_pool']) return result @property def prober_fallback(self): if self._values['prober_fallback'] == 'any': return 'any-available' return self._values['prober_fallback'] @property def bits_limit(self): return self._get_limit_value('bits_limit') @property def packets_limit(self): return self._get_limit_value('packets_limit') @property def connections_limit(self): return self._get_limit_value('connections_limit') @property def cpu_limit(self): return self._get_limit_value('cpu_limit') @property def memory_limit(self): return self._get_limit_value('memory_limit') @property def bits_enabled(self): return self._get_limit_status('bits_enabled') @property def packets_enabled(self): return self._get_limit_status('packets_enabled') @property def connections_enabled(self): return self._get_limit_status('connections_enabled') @property def cpu_enabled(self): return self._get_limit_status('cpu_enabled') @property def memory_enabled(self): return self._get_limit_status('memory_enabled') class Changes(Parameters): def to_return(self): result = {} for returnable in self.returnables: result[returnable] = getattr(self, returnable) result = self._filter_params(result) return result class UsableChanges(Changes): @property def monitors(self): monitor_string = self._values['monitors'] if monitor_string is None: return None if '{' in monitor_string and '}': tmp = monitor_string.strip('}').split('{') monitor = ''.join(tmp).rstrip() return monitor return monitor_string @property def iquery_allow_path(self): if self._values['iquery_allow_path'] is None: return None elif self._values['iquery_allow_path']: return 'yes' return 'no' @property def iquery_allow_service_check(self): if self._values['iquery_allow_service_check'] is None: return None elif self._values['iquery_allow_service_check']: return 'yes' return 'no' @property def iquery_allow_snmp(self): if self._values['iquery_allow_snmp'] is None: return None elif self._values['iquery_allow_snmp']: return 'yes' return 'no' class ReportableChanges(Changes): @property def server_type(self): if self._values['server_type'] in ['single-bigip', 'redundant-bigip']: return 'bigip' return self._values['server_type'] @property def monitors(self): if self._values['monitors'] is None: return [] try: result = re.findall(r'/\w+/[^\s}]+', self._values['monitors']) result.sort() return result except Exception: return self._values['monitors'] @property def availability_requirement_type(self): if self._values['monitors'] is None: return None if 'min ' in self._values['monitors']: return 'at_least' elif 'require ' in self._values['monitors']: return 'require' else: return 'all' @property def number_of_probes(self):<|fim▁hole|> require 1 from 2 { /Common/tcp } This method parses out the first of the numeric values. This values represents the "probes" value that can be updated in the module. Returns: int: The probes value if found. None otherwise. """ if self._values['monitors'] is None: return None pattern = r'require\s+(?P<probes>\d+)\s+from' matches = re.search(pattern, self._values['monitors']) if matches is None: return None return int(matches.group('probes')) @property def number_of_probers(self): """Returns the probers value from the monitor string. The monitor string for a Require monitor looks like this. require 1 from 2 { /Common/tcp } This method parses out the first of the numeric values. This values represents the "probers" value that can be updated in the module. Returns: int: The probers value if found. None otherwise. """ if self._values['monitors'] is None: return None pattern = r'require\s+\d+\s+from\s+(?P<probers>\d+)\s+' matches = re.search(pattern, self._values['monitors']) if matches is None: return None return int(matches.group('probers')) @property def at_least(self): """Returns the 'at least' value from the monitor string. The monitor string for a Require monitor looks like this. min 1 of { /Common/gateway_icmp } This method parses out the first of the numeric values. This values represents the "at_least" value that can be updated in the module. Returns: int: The at_least value if found. None otherwise. """ if self._values['monitors'] is None: return None pattern = r'min\s+(?P<least>\d+)\s+of\s+' matches = re.search(pattern, self._values['monitors']) if matches is None: return None return int(matches.group('least')) @property def availability_requirements(self): if self._values['monitors'] is None: return None result = dict() result['type'] = self.availability_requirement_type result['at_least'] = self.at_least result['number_of_probers'] = self.number_of_probers result['number_of_probes'] = self.number_of_probes return result @property def prober_fallback(self): if self._values['prober_fallback'] == 'any-available': return 'any' return self._values['prober_fallback'] class Difference(object): def __init__(self, want, have=None): self.want = want self.have = have def compare(self, param): try: result = getattr(self, param) return result except AttributeError: return self.__default(param) def __default(self, param): want = getattr(self.want, param) try: have = getattr(self.have, param) if want != have: return want except AttributeError: return want def _discovery_constraints(self): if self.want.virtual_server_discovery is None: virtual_server_discovery = self.have.virtual_server_discovery else: virtual_server_discovery = self.want.virtual_server_discovery if self.want.link_discovery is None: link_discovery = self.have.link_discovery else: link_discovery = self.want.link_discovery if link_discovery in ['enabled', 'enabled-no-delete'] and virtual_server_discovery == 'disabled': raise F5ModuleError( "Virtual server discovery must be enabled if link discovery is enabled" ) def _devices_changed(self): if self.want.devices is None and self.want.server_type is None: return None if self.want.devices is None: devices = self.have.devices else: devices = self.want.devices if self.have.devices is None: have_devices = [] else: have_devices = self.have.devices if len(devices) == 0: raise F5ModuleError( "A GTM server must have at least one device associated with it." ) want = [OrderedDict(sorted(d.items())) for d in devices] have = [OrderedDict(sorted(d.items())) for d in have_devices] if want != have: return True return False def _server_type_changed(self): if self.want.server_type is None: self.want.update({'server_type': self.have.server_type}) if self.want.server_type != self.have.server_type: return True return False @property def link_discovery(self): self._discovery_constraints() if self.want.link_discovery != self.have.link_discovery: return self.want.link_discovery @property def virtual_server_discovery(self): self._discovery_constraints() if self.want.virtual_server_discovery != self.have.virtual_server_discovery: return self.want.virtual_server_discovery def _handle_current_server_type_and_devices(self, devices_change, server_change): result = {} if devices_change: result['devices'] = self.want.devices if server_change: result['server_type'] = self.want.server_type return result def _handle_legacy_server_type_and_devices(self, devices_change, server_change): result = {} if server_change and devices_change: result['devices'] = self.want.devices if len(self.want.devices) > 1 and self.want.server_type == 'bigip': if self.have.raw_server_type != 'redundant-bigip': result['server_type'] = 'redundant-bigip' elif self.want.server_type == 'bigip': if self.have.raw_server_type != 'single-bigip': result['server_type'] = 'single-bigip' else: result['server_type'] = self.want.server_type elif devices_change: result['devices'] = self.want.devices if len(self.want.devices) > 1 and self.have.server_type == 'bigip': if self.have.raw_server_type != 'redundant-bigip': result['server_type'] = 'redundant-bigip' elif self.have.server_type == 'bigip': if self.have.raw_server_type != 'single-bigip': result['server_type'] = 'single-bigip' else: result['server_type'] = self.want.server_type elif server_change: if len(self.have.devices) > 1 and self.want.server_type == 'bigip': if self.have.raw_server_type != 'redundant-bigip': result['server_type'] = 'redundant-bigip' elif self.want.server_type == 'bigip': if self.have.raw_server_type != 'single-bigip': result['server_type'] = 'single-bigip' else: result['server_type'] = self.want.server_type return result @property def server_type_and_devices(self): """Compares difference between server type and devices list These two parameters are linked with each other and, therefore, must be compared together to ensure that the correct setting is sent to BIG-IP :return: """ devices_change = self._devices_changed() server_change = self._server_type_changed() if not devices_change and not server_change: return None tmos = tmos_version(self.client) if LooseVersion(tmos) >= LooseVersion('13.0.0'): result = self._handle_current_server_type_and_devices( devices_change, server_change ) return result else: result = self._handle_legacy_server_type_and_devices( devices_change, server_change ) return result @property def state(self): if self.want.state == 'disabled' and self.have.enabled: return dict(disabled=True) elif self.want.state in ['present', 'enabled'] and self.have.disabled: return dict(enabled=True) @property def monitors(self): if self.want.monitors is None: return None if self.want.monitors == '/Common/bigip' and self.have.monitors == '/Common/bigip': return None if self.want.monitors == '/Common/bigip' and self.have.monitors is None: return None if self.want.monitors == '/Common/bigip' and len(self.have.monitors) > 0: return '/Common/bigip' if self.have.monitors is None: return self.want.monitors if self.have.monitors != self.want.monitors: return self.want.monitors @property def prober_pool(self): if self.want.prober_pool is None: return None if self.have.prober_pool is None: if self.want.prober_pool == '': return None if self.want.prober_pool != self.have.prober_pool: return self.want.prober_pool @property def prober_preference(self): if self.want.prober_preference is None: return None if self.want.prober_preference == self.have.prober_preference: return None if self.want.prober_preference == 'pool' and self.want.prober_pool is None: raise F5ModuleError( "A prober_pool needs to be set if prober_preference is set to 'pool'" ) if self.want.prober_preference != 'pool' and self.have.prober_preference == 'pool': if self.want.prober_fallback != 'pool' and self.want.prober_pool != '': raise F5ModuleError( "To change prober_preference from {0} to {1}, set prober_pool to an empty string".format( self.have.prober_preference, self.want.prober_preference ) ) if self.want.prober_preference == self.want.prober_fallback: raise F5ModuleError( "Prober_preference and prober_fallback must not be equal." ) if self.want.prober_preference == self.have.prober_fallback: raise F5ModuleError( "Cannot set prober_preference to {0} if prober_fallback on device is set to {1}.".format( self.want.prober_preference, self.have.prober_fallback ) ) if self.want.prober_preference != self.have.prober_preference: return self.want.prober_preference @property def prober_fallback(self): if self.want.prober_fallback is None: return None if self.want.prober_fallback == self.have.prober_fallback: return None if self.want.prober_fallback == 'pool' and self.want.prober_pool is None: raise F5ModuleError( "A prober_pool needs to be set if prober_fallback is set to 'pool'" ) if self.want.prober_fallback != 'pool' and self.have.prober_fallback == 'pool': if self.want.prober_preference != 'pool' and self.want.prober_pool != '': raise F5ModuleError( "To change prober_fallback from {0} to {1}, set prober_pool to an empty string".format( self.have.prober_fallback, self.want.prober_fallback ) ) if self.want.prober_preference == self.want.prober_fallback: raise F5ModuleError( "Prober_preference and prober_fallback must not be equal." ) if self.want.prober_fallback == self.have.prober_preference: raise F5ModuleError( "Cannot set prober_fallback to {0} if prober_preference on device is set to {1}.".format( self.want.prober_fallback, self.have.prober_preference ) ) if self.want.prober_fallback != self.have.prober_fallback: return self.want.prober_fallback class ModuleManager(object): def __init__(self, *args, **kwargs): self.module = kwargs.get('module', None) self.client = kwargs.get('client', None) self.kwargs = kwargs def exec_module(self): if not module_provisioned(self.client, 'gtm'): raise F5ModuleError( "GTM must be provisioned to use this module." ) if self.version_is_less_than('13.0.0'): manager = self.get_manager('v1') else: manager = self.get_manager('v2') return manager.exec_module() def get_manager(self, type): if type == 'v1': return V1Manager(**self.kwargs) elif type == 'v2': return V2Manager(**self.kwargs) def version_is_less_than(self, version): tmos = tmos_version(self.client) if LooseVersion(tmos) < LooseVersion(version): return True else: return False class BaseManager(object): def __init__(self, *args, **kwargs): self.module = kwargs.get('module', None) self.client = kwargs.get('client', None) self.want = ModuleParameters(params=self.module.params) self.want.update(dict(client=self.client)) self.have = ApiParameters() self.changes = UsableChanges() def _set_changed_options(self): changed = {} for key in Parameters.returnables: if getattr(self.want, key) is not None: changed[key] = getattr(self.want, key) if changed: self.changes = UsableChanges(params=changed) def _update_changed_options(self): diff = Difference(self.want, self.have) diff.client = self.client updatables = Parameters.updatables changed = dict() for k in updatables: change = diff.compare(k) if change is None: continue else: if isinstance(change, dict): changed.update(change) else: changed[k] = change if changed: self.changes = UsableChanges(params=changed) return True return False def exec_module(self): changed = False result = dict() state = self.want.state if state in ['present', 'enabled', 'disabled']: changed = self.present() elif state == "absent": changed = self.absent() reportable = ReportableChanges(params=self.changes.to_return()) changes = reportable.to_return() result.update(**changes) result.update(dict(changed=changed)) self._announce_deprecations(result) return result def _announce_deprecations(self, result): warnings = result.pop('__warnings', []) for warning in warnings: self.module.deprecate( msg=warning['msg'], version=warning['version'] ) def _check_link_discovery_requirements(self): if self.want.link_discovery in ['enabled', 'enabled-no-delete'] and self.want.virtual_server_discovery == 'disabled': raise F5ModuleError( "Virtual server discovery must be enabled if link discovery is enabled" ) def present(self): if self.exists(): return self.update() else: return self.create() def create(self): if self.want.state == 'disabled': self.want.update({'disabled': True}) elif self.want.state in ['present', 'enabled']: self.want.update({'enabled': True}) self.adjust_server_type_by_version() self.should_update() if self.want.devices is None: raise F5ModuleError( "You must provide an initial device." ) self._assign_creation_defaults() self.handle_prober_settings() self._set_changed_options() if self.module.check_mode: return True self.create_on_device() if self.exists(): return True else: raise F5ModuleError("Failed to create the server") def create_on_device(self): params = self.changes.api_params() params['name'] = self.want.name params['partition'] = self.want.partition uri = "https://{0}:{1}/mgmt/tm/gtm/server/".format( self.client.provider['server'], self.client.provider['server_port'] ) resp = self.client.api.post(uri, json=params) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if 'code' in response and response['code'] in [400, 403]: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp.content) return response['selfLink'] def read_current_from_device(self): uri = "https://{0}:{1}/mgmt/tm/gtm/server/{2}".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.name) ) resp = self.client.api.get(uri) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if 'code' in response and response['code'] == 400: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp.content) return ApiParameters(params=response) def should_update(self): result = self._update_changed_options() if result: return True return False def update_on_device(self): params = self.changes.api_params() uri = "https://{0}:{1}/mgmt/tm/gtm/server/{2}".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.name) ) resp = self.client.api.patch(uri, json=params) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if 'code' in response and response['code'] == 400: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp.content) def absent(self): changed = False if self.exists(): changed = self.remove() return changed def remove(self): if self.module.check_mode: return True self.remove_from_device() if self.exists(): raise F5ModuleError("Failed to delete the server") return True def remove_from_device(self): uri = "https://{0}:{1}/mgmt/tm/gtm/server/{2}".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.name) ) response = self.client.api.delete(uri) if response.status == 200: return True raise F5ModuleError(response.content) def exists(self): uri = "https://{0}:{1}/mgmt/tm/gtm/server/{2}".format( self.client.provider['server'], self.client.provider['server_port'], transform_name(self.want.partition, self.want.name) ) resp = self.client.api.get(uri) try: response = resp.json() except ValueError: return False if resp.status == 404 or 'code' in response and response['code'] == 404: return False return True class V1Manager(BaseManager): def _assign_creation_defaults(self): if self.want.server_type is None: if len(self.want.devices) == 0: raise F5ModuleError( "You must provide at least one device." ) elif len(self.want.devices) == 1: self.want.update({'server_type': 'single-bigip'}) else: self.want.update({'server_type': 'redundant-bigip'}) if self.want.link_discovery is None: self.want.update({'link_discovery': 'disabled'}) if self.want.virtual_server_discovery is None: self.want.update({'virtual_server_discovery': 'disabled'}) self._check_link_discovery_requirements() def adjust_server_type_by_version(self): if len(self.want.devices) == 1 and self.want.server_type == 'bigip': self.want.update({'server_type': 'single-bigip'}) if len(self.want.devices) > 1 and self.want.server_type == 'bigip': self.want.update({'server_type': 'redundant-bigip'}) def update(self): self.have = self.read_current_from_device() self.handle_prober_settings() if not self.should_update(): return False if self.module.check_mode: return True self.update_on_device() return True def handle_prober_settings(self): if self.want.prober_preference is not None: self.want._values.pop('prober_preference') if self.want.prober_fallback is not None: self.want._values.pop('prober_fallback') class V2Manager(BaseManager): def update(self): self.have = self.read_current_from_device() if not self.should_update(): return False if self.module.check_mode: return True self.update_on_device() return True def _assign_creation_defaults(self): if self.want.server_type is None: self.want.update({'server_type': 'bigip'}) if self.want.link_discovery is None: self.want.update({'link_discovery': 'disabled'}) if self.want.virtual_server_discovery is None: self.want.update({'virtual_server_discovery': 'disabled'}) self._check_link_discovery_requirements() def adjust_server_type_by_version(self): pass def handle_prober_settings(self): if self.want.prober_preference == 'pool' and self.want.prober_pool is None: raise F5ModuleError( "A prober_pool needs to be set if prober_preference is set to 'pool'" ) if self.want.prober_preference is not None and self.want.prober_fallback is not None: if self.want.prober_preference == self.want.prober_fallback: raise F5ModuleError( "The parameters for prober_preference and prober_fallback must not be the same." ) if self.want.prober_fallback == 'pool' and self.want.prober_pool is None: raise F5ModuleError( "A prober_pool needs to be set if prober_fallback is set to 'pool'" ) class ArgumentSpec(object): def __init__(self): self.states = ['absent', 'present', 'enabled', 'disabled'] self.server_types = [ 'alteon-ace-director', 'cisco-css', 'cisco-server-load-balancer', 'generic-host', 'radware-wsd', 'windows-nt-4.0', 'bigip', 'cisco-local-director-v2', 'extreme', 'generic-load-balancer', 'sun-solaris', 'cacheflow', 'cisco-local-director-v3', 'foundry-server-iron', 'netapp', 'windows-2000-server' ] self.supports_check_mode = True argument_spec = dict( state=dict( default='present', choices=self.states, ), name=dict(required=True), server_type=dict( choices=self.server_types, aliases=['product'] ), datacenter=dict(), link_discovery=dict( choices=['enabled', 'disabled', 'enabled-no-delete'] ), virtual_server_discovery=dict( choices=['enabled', 'disabled', 'enabled-no-delete'] ), devices=dict( type='list' ), partition=dict( default='Common', fallback=(env_fallback, ['F5_PARTITION']) ), iquery_options=dict( type='dict', options=dict( allow_path=dict(type='bool'), allow_service_check=dict(type='bool'), allow_snmp=dict(type='bool') ) ), availability_requirements=dict( type='dict', options=dict( type=dict( choices=['all', 'at_least', 'require'], required=True ), at_least=dict(type='int'), number_of_probes=dict(type='int'), number_of_probers=dict(type='int') ), mutually_exclusive=[ ['at_least', 'number_of_probes'], ['at_least', 'number_of_probers'], ], required_if=[ ['type', 'at_least', ['at_least']], ['type', 'require', ['number_of_probes', 'number_of_probers']] ] ), limits=dict( type='dict', options=dict( bits_enabled=dict(type='bool'), packets_enabled=dict(type='bool'), connections_enabled=dict(type='bool'), cpu_enabled=dict(type='bool'), memory_enabled=dict(type='bool'), bits_limit=dict(type='int'), packets_limit=dict(type='int'), connections_limit=dict(type='int'), cpu_limit=dict(type='int'), memory_limit=dict(type='int'), ) ), monitors=dict(type='list'), prober_preference=dict( choices=['inside-datacenter', 'outside-datacenter', 'inherit', 'pool'] ), prober_fallback=dict( choices=['inside-datacenter', 'outside-datacenter', 'inherit', 'pool', 'any', 'none'] ), prober_pool=dict() ) self.argument_spec = {} self.argument_spec.update(f5_argument_spec) self.argument_spec.update(argument_spec) def main(): spec = ArgumentSpec() module = AnsibleModule( argument_spec=spec.argument_spec, supports_check_mode=spec.supports_check_mode, ) client = F5RestClient(**module.params) try: mm = ModuleManager(module=module, client=client) results = mm.exec_module() cleanup_tokens(client) exit_json(module, results, client) except F5ModuleError as ex: cleanup_tokens(client) fail_json(module, ex, client) if __name__ == '__main__': main()<|fim▁end|>
"""Returns the probes value from the monitor string. The monitor string for a Require monitor looks like this.
<|file_name|>0004_auto_20170726_0019.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models <|fim▁hole|>class Migration(migrations.Migration): dependencies = [ ('jdpages', '0003_auto_20170725_2349'), ] operations = [ migrations.AlterField( model_name='visionspage', name='vision_pages', field=models.ManyToManyField(blank=True, to='jdpages.VisionPage'), ), ]<|fim▁end|>
<|file_name|>pad.py<|end_file_name|><|fim▁begin|>"""Convenience functions for padding .. versionadded:: 0.1.4 """ from __future__ import division, print_function import numpy as np def _get_pad_left_right(small, large): """Compute left and right padding values. Here we use the convention that if the padding size is odd, we pad the odd part to the right and the even part to the left. Parameters ---------- small: int Old size of original 1D array large: int New size off padded 1D array<|fim▁hole|> (padleft, padright) : tuple The proposed padding sizes. """ assert small < large, "Can only pad when new size larger than old size" padsize = large - small if padsize % 2 != 0: leftpad = (padsize - 1)/2 else: leftpad = padsize/2 rightpad = padsize-leftpad return int(leftpad), int(rightpad) def pad_add(av, size=None, stlen=10): """ Perform linear padding for complex array The input array `av` is padded with a linear ramp starting at the edges and going outwards to an average value computed from a band of thickness `stlen` at the outer boundary of the array. Pads will only be appended, not prepended to the array. If the input array is complex, pads will be complex numbers The average is computed for phase and amplitude separately. Parameters ---------- av: complex 1D or 2D ndarray The array that will be padded. size: int or tuple of length 1 (1D) or tuple of length 2 (2D), optional The final size of the padded array. Defaults to double the size of the input array. stlen: int, optional The thickness of the frame within `av` that will be used to compute an average value for padding. Returns ------- pv: complex 1D or 2D ndarray Padded array `av` with pads appended to right and bottom. """ if size is None: size = list() for s in av.shape: size.append(int(2*s)) elif not hasattr(size, "__len__"): size = [size] assert len(av.shape) in [1, 2], "Only 1D and 2D arrays!" assert len(av.shape) == len( size), "`size` must have same length as `av.shape`!" if len(av.shape) == 2: return _pad_add_2d(av, size, stlen) else: return _pad_add_1d(av, size, stlen) def _pad_add_1d(av, size, stlen): """1D component of `pad_add`""" assert len(size) == 1 padx = _get_pad_left_right(av.shape[0], size[0]) mask = np.zeros(av.shape, dtype=bool) mask[stlen:-stlen] = True border = av[~mask] if av.dtype.name.count("complex"): padval = np.average(np.abs(border)) * \ np.exp(1j*np.average(np.angle(border))) else: padval = np.average(border) if np.__version__[:3] in ["1.7", "1.8", "1.9"]: end_values = ((padval, padval),) else: end_values = (padval,) bv = np.pad(av, padx, mode="linear_ramp", end_values=end_values) # roll the array so that the padding values are on the right bv = np.roll(bv, -padx[0], 0) return bv def _pad_add_2d(av, size, stlen): """2D component of `pad_add`""" assert len(size) == 2 padx = _get_pad_left_right(av.shape[0], size[0]) pady = _get_pad_left_right(av.shape[1], size[1]) mask = np.zeros(av.shape, dtype=bool) mask[stlen:-stlen, stlen:-stlen] = True border = av[~mask] if av.dtype.name.count("complex"): padval = np.average(np.abs(border)) * \ np.exp(1j*np.average(np.angle(border))) else: padval = np.average(border) if np.__version__[:3] in ["1.7", "1.8", "1.9"]: end_values = ((padval, padval), (padval, padval)) else: end_values = (padval,) bv = np.pad(av, (padx, pady), mode="linear_ramp", end_values=end_values) # roll the array so that the padding values are on the right bv = np.roll(bv, -padx[0], 0) bv = np.roll(bv, -pady[0], 1) return bv def pad_rem(pv, size=None): """Removes linear padding from array This is a convenience function that does the opposite of `pad_add`. Parameters ---------- pv: 1D or 2D ndarray The array from which the padding will be removed. size: tuple of length 1 (1D) or 2 (2D), optional The final size of the un-padded array. Defaults to half the size of the input array. Returns ------- pv: 1D or 2D ndarray Padded array `av` with pads appended to right and bottom. """ if size is None: size = list() for s in pv.shape: assert s % 2 == 0, "Uneven size; specify correct size of output!" size.append(int(s/2)) elif not hasattr(size, "__len__"): size = [size] assert len(pv.shape) in [1, 2], "Only 1D and 2D arrays!" assert len(pv.shape) == len( size), "`size` must have same length as `av.shape`!" if len(pv.shape) == 2: return pv[:size[0], :size[1]] else: return pv[:size[0]]<|fim▁end|>
Returns -------
<|file_name|>path.py<|end_file_name|><|fim▁begin|># ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (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.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS IS" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. # # The Original Code is Bespin. # # The Initial Developer of the Original Code is # Mozilla. # Portions created by the Initial Developer are Copyright (C) 2009 # the Initial Developer. All Rights Reserved. # # Contributor(s): # # Alternatively, the contents of this file may be used under the terms of # either the GNU General Public License Version 2 or later (the "GPL"), or # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), # in which case the provisions of the GPL or the LGPL are applicable instead # of those above. If you wish to allow use of your version of this file only # under the terms of either the GPL or the LGPL, and not to allow others to # use your version of this file under the terms of the MPL, indicate your # decision by deleting the provisions above and replace them with the notice # and other provisions required by the GPL or the LGPL. If you do not delete # the provisions above, a recipient may use your version of this file under # the terms of any one of the MPL, the GPL or the LGPL. # # ***** END LICENSE BLOCK ***** """ path.py - An object representing a path to a file or directory. Example: from path import path d = path('/home/guido/bin') for f in d.files('*.py'): f.chmod(0755) This module requires Python 2.5 or later. URL: http://www.jorendorff.com/articles/python/path Author: Jason Orendorff <jason.orendorff\x40gmail\x2ecom> (and others - see the url!) Date: 9 Mar 2007 Slightly modified to eliminate the deprecationwarning for the md5 module. """ # TODO # - Tree-walking functions don't avoid symlink loops. Matt Harrison # sent me a patch for this. # - Bug in write_text(). It doesn't support Universal newline mode. # - Better error message in listdir() when self isn't a # directory. (On Windows, the error message really sucks.) # - Make sure everything has a good docstring. # - Add methods for regex find and replace. # - guess_content_type() method? # - Perhaps support arguments to touch(). import sys, warnings, os, fnmatch, glob, shutil, codecs, hashlib __version__ = '2.2' __all__ = ['path'] # Platform-specific support for path.owner if os.name == 'nt': try: import win32security except ImportError: win32security = None else: try: import pwd except ImportError: pwd = None # Pre-2.3 support. Are unicode filenames supported? _base = str _getcwd = os.getcwd try: if os.path.supports_unicode_filenames: _base = unicode _getcwd = os.getcwdu except AttributeError: pass # Pre-2.3 workaround for booleans try: True, False except NameError: True, False = 1, 0 # Pre-2.3 workaround for basestring. try: basestring except NameError: basestring = (str, unicode) # Universal newline support _textmode = 'r' if hasattr(file, 'newlines'): _textmode = 'U' class TreeWalkWarning(Warning): pass class path(_base): """ Represents a filesystem path. For documentation on individual methods, consult their counterparts in os.path. """ # --- Special Python methods. def __repr__(self): return 'path(%s)' % _base.__repr__(self) # Adding a path and a string yields a path. def __add__(self, more): try: resultStr = _base.__add__(self, more) except TypeError: #Python bug resultStr = NotImplemented if resultStr is NotImplemented: return resultStr return self.__class__(resultStr) def __radd__(self, other): if isinstance(other, basestring): return self.__class__(other.__add__(self)) else: return NotImplemented # The / operator joins paths. def __div__(self, rel): """ fp.__div__(rel) == fp / rel == fp.joinpath(rel) Join two path components, adding a separator character if needed. """ return self.__class__(os.path.join(self, rel)) # Make the / operator work even when true division is enabled. __truediv__ = __div__ def getcwd(cls): """ Return the current working directory as a path object. """ return cls(_getcwd()) getcwd = classmethod(getcwd) # --- Operations on path strings. isabs = os.path.isabs def abspath(self): return self.__class__(os.path.abspath(self)) def normcase(self): return self.__class__(os.path.normcase(self)) def normpath(self): return self.__class__(os.path.normpath(self)) def realpath(self): return self.__class__(os.path.realpath(self)) def expanduser(self): return self.__class__(os.path.expanduser(self)) def expandvars(self): return self.__class__(os.path.expandvars(self)) def dirname(self): return self.__class__(os.path.dirname(self)) basename = os.path.basename def expand(self): """ Clean up a filename by calling expandvars(), expanduser(), and normpath() on it. This is commonly everything needed to clean up a filename read from a configuration file, for example. """ return self.expandvars().expanduser().normpath() def _get_namebase(self): base, ext = os.path.splitext(self.name) return base def _get_ext(self): f, ext = os.path.splitext(_base(self)) return ext def _get_drive(self): drive, r = os.path.splitdrive(self) return self.__class__(drive) parent = property( dirname, None, None, """ This path's parent directory, as a new path object. For example, path('/usr/local/lib/libpython.so').parent == path('/usr/local/lib') """) name = property( basename, None, None, """ The name of this file or directory without the full path. For example, path('/usr/local/lib/libpython.so').name == 'libpython.so' """) namebase = property( _get_namebase, None, None, """ The same as path.name, but with one file extension stripped off. For example, path('/home/guido/python.tar.gz').name == 'python.tar.gz', but path('/home/guido/python.tar.gz').namebase == 'python.tar' """) ext = property( _get_ext, None, None, """ The file extension, for example '.py'. """) drive = property( _get_drive, None, None, """ The drive specifier, for example 'C:'. This is always empty on systems that don't use drive specifiers. """) def splitpath(self): """ p.splitpath() -> Return (p.parent, p.name). """ parent, child = os.path.split(self) return self.__class__(parent), child def splitdrive(self): """ p.splitdrive() -> Return (p.drive, <the rest of p>). Split the drive specifier from this path. If there is no drive specifier, p.drive is empty, so the return value is simply (path(''), p). This is always the case on Unix. """ drive, rel = os.path.splitdrive(self) return self.__class__(drive), rel def splitext(self): """ p.splitext() -> Return (p.stripext(), p.ext). Split the filename extension from this path and return the two parts. Either part may be empty. The extension is everything from '.' to the end of the last path segment. This has the property that if (a, b) == p.splitext(), then a + b == p. """ filename, ext = os.path.splitext(self) return self.__class__(filename), ext def stripext(self): """ p.stripext() -> Remove one file extension from the path. For example, path('/home/guido/python.tar.gz').stripext() returns path('/home/guido/python.tar'). """ return self.splitext()[0] if hasattr(os.path, 'splitunc'): def splitunc(self): unc, rest = os.path.splitunc(self) return self.__class__(unc), rest def _get_uncshare(self): unc, r = os.path.splitunc(self) return self.__class__(unc) uncshare = property( _get_uncshare, None, None, """ The UNC mount point for this path. This is empty for paths on local drives. """) def joinpath(self, *args): """ Join two or more path components, adding a separator character (os.sep) if needed. Returns a new path object. """ return self.__class__(os.path.join(self, *args)) def splitall(self): r""" Return a list of the path components in this path. The first item in the list will be a path. Its value will be either os.curdir, os.pardir, empty, or the root directory of this path (for example, '/' or 'C:\\'). The other items in the list will be strings. path.path.joinpath(*result) will yield the original path. """ parts = [] loc = self while loc != os.curdir and loc != os.pardir: prev = loc loc, child = prev.splitpath() if loc == prev: break parts.append(child) parts.append(loc) parts.reverse() return parts def relpath(self): """ Return this path as a relative path, based from the current working directory. """ cwd = self.__class__(os.getcwd()) return cwd.relpathto(self) <|fim▁hole|> """ Return a relative path from self to dest. If there is no relative path from self to dest, for example if they reside on different drives in Windows, then this returns dest.abspath(). """ origin = self.abspath() dest = self.__class__(dest).abspath() orig_list = origin.normcase().splitall() # Don't normcase dest! We want to preserve the case. dest_list = dest.splitall() if orig_list[0] != os.path.normcase(dest_list[0]): # Can't get here from there. return dest # Find the location where the two paths start to differ. i = 0 for start_seg, dest_seg in zip(orig_list, dest_list): if start_seg != os.path.normcase(dest_seg): break i += 1 # Now i is the point where the two paths diverge. # Need a certain number of "os.pardir"s to work up # from the origin to the point of divergence. segments = [os.pardir] * (len(orig_list) - i) # Need to add the diverging part of dest_list. segments += dest_list[i:] if len(segments) == 0: # If they happen to be identical, use os.curdir. relpath = os.curdir else: relpath = os.path.join(*segments) return self.__class__(relpath) # --- Listing, searching, walking, and matching def listdir(self, pattern=None): """ D.listdir() -> List of items in this directory. Use D.files() or D.dirs() instead if you want a listing of just files or just subdirectories. The elements of the list are path objects. With the optional 'pattern' argument, this only lists items whose names match the given pattern. """ names = os.listdir(self) if pattern is not None: names = fnmatch.filter(names, pattern) return [self / child for child in names] def dirs(self, pattern=None): """ D.dirs() -> List of this directory's subdirectories. The elements of the list are path objects. This does not walk recursively into subdirectories (but see path.walkdirs). With the optional 'pattern' argument, this only lists directories whose names match the given pattern. For example, d.dirs('build-*'). """ return [p for p in self.listdir(pattern) if p.isdir()] def files(self, pattern=None): """ D.files() -> List of the files in this directory. The elements of the list are path objects. This does not walk into subdirectories (see path.walkfiles). With the optional 'pattern' argument, this only lists files whose names match the given pattern. For example, d.files('*.pyc'). """ return [p for p in self.listdir(pattern) if p.isfile()] def walk(self, pattern=None, errors='strict'): """ D.walk() -> iterator over files and subdirs, recursively. The iterator yields path objects naming each child item of this directory and its descendants. This requires that D.isdir(). This performs a depth-first traversal of the directory tree. Each directory is returned just before all its children. The errors= keyword argument controls behavior when an error occurs. The default is 'strict', which causes an exception. The other allowed values are 'warn', which reports the error via warnings.warn(), and 'ignore'. """ if errors not in ('strict', 'warn', 'ignore'): raise ValueError("invalid errors parameter") try: childList = self.listdir() except Exception: if errors == 'ignore': return elif errors == 'warn': warnings.warn( "Unable to list directory '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) return else: raise for child in childList: if pattern is None or child.fnmatch(pattern): yield child try: isdir = child.isdir() except Exception: if errors == 'ignore': isdir = False elif errors == 'warn': warnings.warn( "Unable to access '%s': %s" % (child, sys.exc_info()[1]), TreeWalkWarning) isdir = False else: raise if isdir: for item in child.walk(pattern, errors): yield item def walkdirs(self, pattern=None, errors='strict'): """ D.walkdirs() -> iterator over subdirs, recursively. With the optional 'pattern' argument, this yields only directories whose names match the given pattern. For example, mydir.walkdirs('*test') yields only directories with names ending in 'test'. The errors= keyword argument controls behavior when an error occurs. The default is 'strict', which causes an exception. The other allowed values are 'warn', which reports the error via warnings.warn(), and 'ignore'. """ if errors not in ('strict', 'warn', 'ignore'): raise ValueError("invalid errors parameter") try: dirs = self.dirs() except Exception: if errors == 'ignore': return elif errors == 'warn': warnings.warn( "Unable to list directory '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) return else: raise for child in dirs: if pattern is None or child.fnmatch(pattern): yield child for subsubdir in child.walkdirs(pattern, errors): yield subsubdir def walkfiles(self, pattern=None, errors='strict'): """ D.walkfiles() -> iterator over files in D, recursively. The optional argument, pattern, limits the results to files with names that match the pattern. For example, mydir.walkfiles('*.tmp') yields only files with the .tmp extension. """ if errors not in ('strict', 'warn', 'ignore'): raise ValueError("invalid errors parameter") try: childList = self.listdir() except Exception: if errors == 'ignore': return elif errors == 'warn': warnings.warn( "Unable to list directory '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) return else: raise for child in childList: try: isfile = child.isfile() isdir = not isfile and child.isdir() except: if errors == 'ignore': continue elif errors == 'warn': warnings.warn( "Unable to access '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) continue else: raise if isfile: if pattern is None or child.fnmatch(pattern): yield child elif isdir: for f in child.walkfiles(pattern, errors): yield f def fnmatch(self, pattern): """ Return True if self.name matches the given pattern. pattern - A filename pattern with wildcards, for example '*.py'. """ return fnmatch.fnmatch(self.name, pattern) def glob(self, pattern): """ Return a list of path objects that match the pattern. pattern - a path relative to this directory, with wildcards. For example, path('/users').glob('*/bin/*') returns a list of all the files users have in their bin directories. """ cls = self.__class__ return [cls(s) for s in glob.glob(_base(self / pattern))] # --- Reading or writing an entire file at once. def open(self, mode='r'): """ Open this file. Return a file object. """ return file(self, mode) def bytes(self): """ Open this file, read all bytes, return them as a string. """ f = self.open('rb') try: return f.read() finally: f.close() def write_bytes(self, bytes, append=False): """ Open this file and write the given bytes to it. Default behavior is to overwrite any existing file. Call p.write_bytes(bytes, append=True) to append instead. """ if append: mode = 'ab' else: mode = 'wb' f = self.open(mode) try: f.write(bytes) finally: f.close() def text(self, encoding=None, errors='strict'): r""" Open this file, read it in, return the content as a string. This uses 'U' mode in Python 2.3 and later, so '\r\n' and '\r' are automatically translated to '\n'. Optional arguments: encoding - The Unicode encoding (or character set) of the file. If present, the content of the file is decoded and returned as a unicode object; otherwise it is returned as an 8-bit str. errors - How to handle Unicode errors; see help(str.decode) for the options. Default is 'strict'. """ if encoding is None: # 8-bit f = self.open(_textmode) try: return f.read() finally: f.close() else: # Unicode f = codecs.open(self, 'r', encoding, errors) # (Note - Can't use 'U' mode here, since codecs.open # doesn't support 'U' mode, even in Python 2.3.) try: t = f.read() finally: f.close() return (t.replace(u'\r\n', u'\n') .replace(u'\r\x85', u'\n') .replace(u'\r', u'\n') .replace(u'\x85', u'\n') .replace(u'\u2028', u'\n')) def write_text(self, text, encoding=None, errors='strict', linesep=os.linesep, append=False): r""" Write the given text to this file. The default behavior is to overwrite any existing file; to append instead, use the 'append=True' keyword argument. There are two differences between path.write_text() and path.write_bytes(): newline handling and Unicode handling. See below. Parameters: - text - str/unicode - The text to be written. - encoding - str - The Unicode encoding that will be used. This is ignored if 'text' isn't a Unicode string. - errors - str - How to handle Unicode encoding errors. Default is 'strict'. See help(unicode.encode) for the options. This is ignored if 'text' isn't a Unicode string. - linesep - keyword argument - str/unicode - The sequence of characters to be used to mark end-of-line. The default is os.linesep. You can also specify None; this means to leave all newlines as they are in 'text'. - append - keyword argument - bool - Specifies what to do if the file already exists (True: append to the end of it; False: overwrite it.) The default is False. --- Newline handling. write_text() converts all standard end-of-line sequences ('\n', '\r', and '\r\n') to your platform's default end-of-line sequence (see os.linesep; on Windows, for example, the end-of-line marker is '\r\n'). If you don't like your platform's default, you can override it using the 'linesep=' keyword argument. If you specifically want write_text() to preserve the newlines as-is, use 'linesep=None'. This applies to Unicode text the same as to 8-bit text, except there are three additional standard Unicode end-of-line sequences: u'\x85', u'\r\x85', and u'\u2028'. (This is slightly different from when you open a file for writing with fopen(filename, "w") in C or file(filename, 'w') in Python.) --- Unicode If 'text' isn't Unicode, then apart from newline handling, the bytes are written verbatim to the file. The 'encoding' and 'errors' arguments are not used and must be omitted. If 'text' is Unicode, it is first converted to bytes using the specified 'encoding' (or the default encoding if 'encoding' isn't specified). The 'errors' argument applies only to this conversion. """ if isinstance(text, unicode): if linesep is not None: # Convert all standard end-of-line sequences to # ordinary newline characters. text = (text.replace(u'\r\n', u'\n') .replace(u'\r\x85', u'\n') .replace(u'\r', u'\n') .replace(u'\x85', u'\n') .replace(u'\u2028', u'\n')) text = text.replace(u'\n', linesep) if encoding is None: encoding = sys.getdefaultencoding() bytes = text.encode(encoding, errors) else: # It is an error to specify an encoding if 'text' is # an 8-bit string. assert encoding is None if linesep is not None: text = (text.replace('\r\n', '\n') .replace('\r', '\n')) bytes = text.replace('\n', linesep) self.write_bytes(bytes, append) def lines(self, encoding=None, errors='strict', retain=True): r""" Open this file, read all lines, return them in a list. Optional arguments: encoding - The Unicode encoding (or character set) of the file. The default is None, meaning the content of the file is read as 8-bit characters and returned as a list of (non-Unicode) str objects. errors - How to handle Unicode errors; see help(str.decode) for the options. Default is 'strict' retain - If true, retain newline characters; but all newline character combinations ('\r', '\n', '\r\n') are translated to '\n'. If false, newline characters are stripped off. Default is True. This uses 'U' mode in Python 2.3 and later. """ if encoding is None and retain: f = self.open(_textmode) try: return f.readlines() finally: f.close() else: return self.text(encoding, errors).splitlines(retain) def write_lines(self, lines, encoding=None, errors='strict', linesep=os.linesep, append=False): r""" Write the given lines of text to this file. By default this overwrites any existing file at this path. This puts a platform-specific newline sequence on every line. See 'linesep' below. lines - A list of strings. encoding - A Unicode encoding to use. This applies only if 'lines' contains any Unicode strings. errors - How to handle errors in Unicode encoding. This also applies only to Unicode strings. linesep - The desired line-ending. This line-ending is applied to every line. If a line already has any standard line ending ('\r', '\n', '\r\n', u'\x85', u'\r\x85', u'\u2028'), that will be stripped off and this will be used instead. The default is os.linesep, which is platform-dependent ('\r\n' on Windows, '\n' on Unix, etc.) Specify None to write the lines as-is, like file.writelines(). Use the keyword argument append=True to append lines to the file. The default is to overwrite the file. Warning: When you use this with Unicode data, if the encoding of the existing data in the file is different from the encoding you specify with the encoding= parameter, the result is mixed-encoding data, which can really confuse someone trying to read the file later. """ if append: mode = 'ab' else: mode = 'wb' f = self.open(mode) try: for line in lines: isUnicode = isinstance(line, unicode) if linesep is not None: # Strip off any existing line-end and add the # specified linesep string. if isUnicode: if line[-2:] in (u'\r\n', u'\x0d\x85'): line = line[:-2] elif line[-1:] in (u'\r', u'\n', u'\x85', u'\u2028'): line = line[:-1] else: if line[-2:] == '\r\n': line = line[:-2] elif line[-1:] in ('\r', '\n'): line = line[:-1] line += linesep if isUnicode: if encoding is None: encoding = sys.getdefaultencoding() line = line.encode(encoding, errors) f.write(line) finally: f.close() def read_md5(self): """ Calculate the md5 hash for this file. This reads through the entire file. """ f = self.open('rb') try: m = hashlib.new("md5") while True: d = f.read(8192) if not d: break m.update(d) finally: f.close() return m.digest() # --- Methods for querying the filesystem. exists = os.path.exists isdir = os.path.isdir isfile = os.path.isfile islink = os.path.islink ismount = os.path.ismount if hasattr(os.path, 'samefile'): samefile = os.path.samefile getatime = os.path.getatime atime = property( getatime, None, None, """ Last access time of the file. """) getmtime = os.path.getmtime mtime = property( getmtime, None, None, """ Last-modified time of the file. """) if hasattr(os.path, 'getctime'): getctime = os.path.getctime ctime = property( getctime, None, None, """ Creation time of the file. """) getsize = os.path.getsize size = property( getsize, None, None, """ Size of the file, in bytes. """) if hasattr(os, 'access'): def access(self, mode): """ Return true if current user has access to this path. mode - One of the constants os.F_OK, os.R_OK, os.W_OK, os.X_OK """ return os.access(self, mode) def stat(self): """ Perform a stat() system call on this path. """ return os.stat(self) def lstat(self): """ Like path.stat(), but do not follow symbolic links. """ return os.lstat(self) def get_owner(self): r""" Return the name of the owner of this file or directory. This follows symbolic links. On Windows, this returns a name of the form ur'DOMAIN\User Name'. On Windows, a group can own a file or directory. """ if os.name == 'nt': if win32security is None: raise Exception("path.owner requires win32all to be installed") desc = win32security.GetFileSecurity( self, win32security.OWNER_SECURITY_INFORMATION) sid = desc.GetSecurityDescriptorOwner() account, domain, typecode = win32security.LookupAccountSid(None, sid) return domain + u'\\' + account else: if pwd is None: raise NotImplementedError("path.owner is not implemented on this platform.") st = self.stat() return pwd.getpwuid(st.st_uid).pw_name owner = property( get_owner, None, None, """ Name of the owner of this file or directory. """) if hasattr(os, 'statvfs'): def statvfs(self): """ Perform a statvfs() system call on this path. """ return os.statvfs(self) if hasattr(os, 'pathconf'): def pathconf(self, name): return os.pathconf(self, name) # --- Modifying operations on files and directories def utime(self, times): """ Set the access and modified times of this file. """ os.utime(self, times) def chmod(self, mode): os.chmod(self, mode) if hasattr(os, 'chown'): def chown(self, uid, gid): os.chown(self, uid, gid) def rename(self, new): os.rename(self, new) def renames(self, new): os.renames(self, new) # --- Create/delete operations on directories def mkdir(self, mode=0777): os.mkdir(self, mode) def makedirs(self, mode=0777): os.makedirs(self, mode) def rmdir(self): os.rmdir(self) def removedirs(self): os.removedirs(self) # --- Modifying operations on files def touch(self): """ Set the access/modified times of this file to the current time. Create the file if it does not exist. """ fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0666) os.close(fd) os.utime(self, None) def remove(self): os.remove(self) def unlink(self): os.unlink(self) # --- Links if hasattr(os, 'link'): def link(self, newpath): """ Create a hard link at 'newpath', pointing to this file. """ os.link(self, newpath) if hasattr(os, 'symlink'): def symlink(self, newlink): """ Create a symbolic link at 'newlink', pointing here. """ os.symlink(self, newlink) if hasattr(os, 'readlink'): def readlink(self): """ Return the path to which this symbolic link points. The result may be an absolute or a relative path. """ return self.__class__(os.readlink(self)) def readlinkabs(self): """ Return the path to which this symbolic link points. The result is always an absolute path. """ p = self.readlink() if p.isabs(): return p else: return (self.parent / p).abspath() # --- High-level functions from shutil copyfile = shutil.copyfile copymode = shutil.copymode copystat = shutil.copystat copy = shutil.copy copy2 = shutil.copy2 copytree = shutil.copytree if hasattr(shutil, 'move'): move = shutil.move rmtree = shutil.rmtree # --- Special stuff from os if hasattr(os, 'chroot'): def chroot(self): os.chroot(self) if hasattr(os, 'startfile'): def startfile(self): os.startfile(self)<|fim▁end|>
def relpathto(self, dest):
<|file_name|>summarize.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2017 The Kubernetes 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. """ Summarize groups failed tests together by finding edit distances between their failure strings, and emits JSON for rendering in a browser. """ # pylint: disable=invalid-name,missing-docstring import argparse import functools import hashlib import json import logging import os import re import sys import time import zlib import berghelroach editdist = berghelroach.dist flakeReasonDateRE = re.compile( r'[A-Z][a-z]{2}, \d+ \w+ 2\d{3} [\d.-: ]*([-+]\d+)?|' r'\w{3}\s+\d{1,2} \d+:\d+:\d+(\.\d+)?|(\d{4}-\d\d-\d\d.|.\d{4} )\d\d:\d\d:\d\d(.\d+)?') # Find random noisy strings that should be replaced with renumbered strings, for more similarity. flakeReasonOrdinalRE = re.compile( r'0x[0-9a-fA-F]+' # hex constants r'|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?' # IPs + optional port r'|[0-9a-fA-F]{8}-\S{4}-\S{4}-\S{4}-\S{12}(-\d+)?' # UUIDs + trailing digits r'|[0-9a-f]{12,32}' # hex garbage r'|(?<=minion-group-|default-pool-)[-0-9a-z]{4,}' # node names ) def normalize(s): """ Given a traceback or error message from a text, reduce excess entropy to make clustering easier. This includes: - blanking dates and timestamps - renumbering unique information like - pointer addresses - UUIDs - IP addresses - sorting randomly ordered map[] strings. """ # blank out dates s = flakeReasonDateRE.sub('TIME', s) # do alpha conversion-- rename random garbage strings (hex pointer values, node names, etc) # into 'UNIQ1', 'UNIQ2', etc. matches = {} def repl(m): s = m.group(0) if s not in matches: matches[s] = 'UNIQ%d' % (len(matches) + 1) return matches[s] if 'map[' in s: # Go's maps are in a random order. Try to sort them to reduce diffs. s = re.sub(r'map\[([^][]*)\]', lambda m: 'map[%s]' % ' '.join(sorted(m.group(1).split())), s) s = flakeReasonOrdinalRE.sub(repl, s) if len(s) > 10000: # for long strings, remove repeated lines! s = re.sub(r'(?m)^(.*\n)\1+', r'\1', s) if len(s) > 10000: # ridiculously long test output s = s[:5000] + '\n...[truncated]...\n' + s[-5000:] return s def normalize_name(name): """ Given a test name, remove [...]/{...}. Matches code in testgrid and kubernetes/hack/update_owners.py. """ name = re.sub(r'\[.*?\]|{.*?\}', '', name) name = re.sub(r'\s+', ' ', name) return name.strip() def make_ngram_counts(s, ngram_counts={}): """ Convert a string into a histogram of frequencies for different byte combinations. This can be used as a heuristic to estimate edit distance between two strings in constant time. Instead of counting each ngram individually, they are hashed into buckets. This makes the output count size constant. """ # Yes, I'm intentionally memoizing here. # pylint: disable=dangerous-default-value size = 64 if s not in ngram_counts: counts = [0] * size for x in range(len(s)-3): counts[zlib.crc32(s[x:x+4].encode('utf8')) & (size - 1)] += 1 ngram_counts[s] = counts # memoize return ngram_counts[s] def ngram_editdist(a, b): """ Compute a heuristic lower-bound edit distance using ngram counts. An insert/deletion/substitution can cause up to 4 ngrams to differ: abcdefg => abcefg (abcd, bcde, cdef, defg) => (abce, bcef, cefg) This will underestimate the edit distance in many cases: - ngrams hashing into the same bucket will get confused - a large-scale transposition will barely disturb ngram frequencies, but will have a very large effect on edit distance. It is useful to avoid more expensive precise computations when they are guaranteed to exceed some limit (being a lower bound), or as a proxy when the exact edit distance computation is too expensive (for long inputs). """ counts_a = make_ngram_counts(a) counts_b = make_ngram_counts(b) return sum(abs(x-y) for x, y in zip(counts_a, counts_b))//4 def make_ngram_counts_digest(s): """ Returns a hashed version of the ngram counts. """ return hashlib.sha1(str(make_ngram_counts(s)).encode()).hexdigest()[:20] def file_memoize(description, name): """ Decorator to save a function's results to a file. """ def inner(func): @functools.wraps(func) def wrapper(*args, **kwargs): if os.path.exists(name): with open(name) as f: data = json.load(f) logging.info('done (cached) %s', description) return data data = func(*args, **kwargs) with open(name, 'w') as f: json.dump(data, f) logging.info('done %s', description) return data wrapper.__wrapped__ = func return wrapper return inner @file_memoize('loading failed tests', 'memo_load_failures.json') def load_failures(builds_file, tests_files): """ Load builds and failed tests files. Group builds by path, group test failures by test name. Args: filenames Returns: { build_path: [{ path: build_path, started: 12345, ...} ...], ...}, { test_name: [{build: gs://foo/bar, name: test_name, failure_text: xxx}, ...], ...} """ builds = {} with open(builds_file) as f: for build in json.load(f): if not build['started'] or not build['number']: continue for attr in ('started', 'tests_failed', 'number', 'tests_run'): build[attr] = int(build[attr]) build['elapsed'] = int(float(build['elapsed'])) if 'pr-logs' in build['path']: build['pr'] = build['path'].split('/')[-3] builds[build['path']] = build failed_tests = {} for tests_file in tests_files: with open(tests_file) as f: for line in f: test = json.loads(line) failed_tests.setdefault(test['name'], []).append(test) for tests in failed_tests.values(): tests.sort(key=lambda t: t['build']) return builds, failed_tests def find_match(fnorm, clusters): for ngram_dist, other in sorted((ngram_editdist(fnorm, x), x) for x in clusters): # allow up to 10% differences limit = int((len(fnorm)+len(other))/2.0 * 0.10) if ngram_dist > limit: continue if limit <= 1 and other != fnorm: # no chance continue dist = editdist(fnorm, other, limit) if dist < limit: return other return None def cluster_test(tests): """ Compute failure clusters given a list of failures for one test. Normalize the failure text prior to clustering to avoid needless entropy. Args: [{name: test_name, build: gs://foo/bar, failure_text: xxx}, ...] Returns: {cluster_text_1: [test1, test2, ...]} """ clusters = {} start = time.time() for test in tests: ftext = test['failure_text'] fnorm = normalize(ftext) if fnorm in clusters: clusters[fnorm].append(test) else: other = find_match(fnorm, clusters) if other: clusters[other].append(test) else: clusters[fnorm] = [test] if time.time() > start + 60: logging.info('bailing early, taking too long!') break return clusters @file_memoize('clustering inside each test', 'memo_cluster_local.json') def cluster_local(failed_tests): """ Cluster together the failures for each test. Args: {test_1: [{name: test_1, build: gs://foo/bar, failure_text: xxx}, ...], ...} Returns: {test_1: {cluster_text_1: [test1, test2], ... }, test_2: ...} """ clustered = {} num_failures = 0 start = time.time() logging.info("Clustering failures for %d unique tests...", len(failed_tests)) # Look at tests with the most failures first for n, (test_name, tests) in enumerate( sorted(failed_tests.items(), key=lambda x: len(x[1]), reverse=True), 1): num_failures += len(tests) logging.info('%4d/%4d, %d failures, %s', n, len(failed_tests), len(tests), test_name) sys.stdout.flush() clustered[test_name] = cluster_test(tests) elapsed = time.time() - start logging.info('Finished locally clustering %d unique tests (%d failures) in %dm%ds', len(clustered), num_failures, elapsed / 60, elapsed % 60) return clustered @file_memoize('clustering across tests', 'memo_cluster_global.json') def cluster_global(clustered, previous_clustered): """Combine together clustered failures for each test. This is done hierarchically for efficiency-- each test's failures are likely to be similar, reducing the number of clusters that need to be paired up at this stage. Args: {test_name: {cluster_text_1: [test1, test2, ...], ...}, ...} Returns: {cluster_text_1: [{test_name: [test1, test2, ...]}, ...], ...} """ clusters = {} num_failures = 0 logging.info("Combining clustered failures for %d unique tests...", len(clustered)) start = time.time() if previous_clustered: # seed clusters using output from the previous run n = 0 for cluster in previous_clustered: key = cluster['key'] if key != normalize(key): logging.info(key) logging.info(normalize(key)) n += 1 continue clusters[cluster['key']] = {} logging.info('Seeding with %d previous clusters', len(clusters)) if n: logging.warning('!!! %d clusters lost from different normalization! !!!', n) # Look at tests with the most failures over all clusters first for n, (test_name, test_clusters) in enumerate( sorted(clustered.items(), key=lambda kv: sum(len(x) for x in kv[1].values()), reverse=True), 1): logging.info('%4d/%4d, %d clusters, %s', n, len(clustered), len(test_clusters), test_name) # Look at clusters with the most failures first for key, tests in sorted(test_clusters.items(), key=lambda x: len(x[1]), reverse=True): num_failures += len(tests) if key in clusters: clusters[key].setdefault(test_name, []).extend(tests) else: other = find_match(key, clusters) if other: clusters[other].setdefault(test_name, []).extend(tests) else: clusters[key] = {test_name: list(tests)} # If we seeded clusters using the previous run's keys, some of those # clusters may have disappeared. Remove the resulting empty entries. for k in {k for k, v in clusters.items() if not v}: clusters.pop(k) elapsed = time.time() - start logging.info('Finished clustering %d unique tests (%d failures) into %d clusters in %dm%ds', len(clustered), num_failures, len(clusters), elapsed / 60, elapsed % 60) return clusters def tests_group_by_job(tests, builds): """Turn a list of test failures into {job: [buildnumber, ...], ...}""" groups = {} for test in tests: try: build = builds[test['build']] except KeyError: continue if 'number' in build: groups.setdefault(build['job'], set()).add(build['number']) return sorted(((key, sorted(value, reverse=True)) for key, value in groups.items()), key=lambda kv: (-len(kv[1]), kv[0])) SPAN_RE = re.compile(r'\w+|\W+') def common_spans(xs): """ Finds something similar to the longest common subsequence of xs, but much faster. Returns a list of [matchlen_1, mismatchlen_2, matchlen_2, mismatchlen_2, ...], representing sequences of the first element of the list that are present in all members. """ common = None for x in xs: x_split = SPAN_RE.findall(x) if common is None: # first iteration common = set(x_split) else: common.intersection_update(x_split) spans = [] match = True span_len = 0 for x in SPAN_RE.findall(xs[0]): if x in common: if not match: match = True spans.append(span_len) span_len = 0 span_len += len(x) else: if match: match = False spans.append(span_len) span_len = 0 span_len += len(x) if span_len: spans.append(span_len) return spans def clusters_to_display(clustered, builds): """Transpose and sort the output of cluster_global.""" return [{ "key": key, "id": key_id, "spans": common_spans([f['failure_text'] for _, fs in clusters for f in fs]), "text": clusters[0][1][0]['failure_text'], "tests": [{ "name": test_name, "jobs": [{"name": n, "builds": [str(x) for x in b]} for n, b in tests_group_by_job(tests, builds)] } for test_name, tests in sorted(clusters, key=lambda nt: (-len(nt[1]), nt[0])) ] } for key, key_id, clusters in clustered if sum(len(x[1]) for x in clusters) > 1 ] def builds_to_columns(builds): """Convert a list of build dictionaries into a columnar form. This compresses much better with gzip.""" jobs = {} cols = {v: [] for v in 'started tests_failed elapsed tests_run result executor pr'.split()} out = {'jobs': jobs, 'cols': cols, 'job_paths': {}} for build in sorted(builds.values(), key=lambda b: (b['job'], b['number'])): if 'number' not in build: continue index = len(cols['started']) for key, entries in cols.items(): entries.append(build.get(key)) job = jobs.setdefault(build['job'], {}) if not job: out['job_paths'][build['job']] = build['path'][:build['path'].rindex('/')] job[build['number']] = index for k, indexes in jobs.items(): numbers = sorted(indexes) base = indexes[numbers[0]] count = len(numbers) # optimization: if we have a dense sequential mapping of builds=>indexes, # store only the first build number, the run length, and the first index number. if numbers[-1] == numbers[0] + count - 1 and \ all(indexes[k] == n + base for n, k in enumerate(numbers)): jobs[k] = [numbers[0], count, base] for n in numbers: assert n <= numbers[0] + len(numbers), (k, n, jobs[k], len(numbers), numbers) return out def render(builds, clustered): clustered_sorted = sorted( clustered.items(), key=lambda kv: (-sum(len(ts) for ts in kv[1].values()), kv[0])) clustered_tuples = [(k, make_ngram_counts_digest(k), sorted(clusters.items(), key=lambda nt: (-len(nt[1]), nt[0]))) for k, clusters in clustered_sorted] return {'clustered': clusters_to_display(clustered_tuples, builds), 'builds': builds_to_columns(builds)} SIG_LABEL_RE = re.compile(r'\[sig-([^]]*)\]') def annotate_owners(data, builds, owners): """ Assign ownership to a cluster based on the share of hits in the last day. """ owner_re = re.compile(r'(?:%s)' % '|'.join( '(?P<%s>%s)' % ( sig.replace('-', '_'), # regex group names can't have - '|'.join(re.escape(p) for p in prefixes) ) for sig, prefixes in owners.items() )) job_paths = data['builds']['job_paths'] yesterday = max(data['builds']['cols']['started']) - (60 * 60 * 24) for cluster in data['clustered']: owner_counts = {} for test in cluster['tests']: m = SIG_LABEL_RE.search(test['name']) if m: owner = m.group(1) else: m = owner_re.match(normalize_name(test['name'])) if not m or not m.groupdict(): continue owner = next(k for k, v in m.groupdict().items() if v) owner = owner.replace('_', '-') counts = owner_counts.setdefault(owner, [0, 0]) for job in test['jobs']: if ':' in job['name']: # non-standard CI continue job_path = job_paths[job['name']] for build in job['builds']: if builds['%s/%s' % (job_path, build)]['started'] > yesterday: counts[0] += 1 else: counts[1] += 1 if owner_counts: owner = max(owner_counts.items(), key=lambda oc: (oc[1], oc[0]))[0] cluster['owner'] = owner else: cluster['owner'] = 'testing' def render_slice(data, builds, prefix='', owner=''): clustered = [] builds_out = {} jobs = set() for cluster in data['clustered']: # print [cluster['id'], prefix] if owner and cluster.get('owner') == owner: clustered.append(cluster) elif prefix and cluster['id'].startswith(prefix): clustered.append(cluster) else: continue for test in cluster['tests']: for job in test['jobs']: jobs.add(job['name']) for path, build in builds.items(): if build['job'] in jobs: builds_out[path] = build return {'clustered': clustered, 'builds': builds_to_columns(builds_out)} def setup_logging(): """Initialize logging to screen""" # See https://docs.python.org/2/library/logging.html#logrecord-attributes # [IWEF]mmdd HH:MM:SS.mmm] msg fmt = '%(levelname).1s%(asctime)s.%(msecs)03d] %(message)s' # pylint: disable=line-too-long datefmt = '%m%d %H:%M:%S' logging.basicConfig( level=logging.INFO, format=fmt, datefmt=datefmt, )<|fim▁hole|>def parse_args(args): parser = argparse.ArgumentParser() parser.add_argument('builds', help='builds.json file from BigQuery') parser.add_argument('tests', help='tests.json file from BigQuery', nargs='+') parser.add_argument('--previous', help='previous output', type=argparse.FileType('r')) parser.add_argument('--owners', help='test owner SIGs', type=argparse.FileType('r')) parser.add_argument('--output', default='failure_data.json') parser.add_argument('--output_slices', help='Output slices to this path (must include PREFIX in template)') return parser.parse_args(args) def main(args): setup_logging() builds, failed_tests = load_failures(args.builds, args.tests) previous_clustered = None if args.previous: logging.info('loading previous') previous_clustered = json.load(args.previous)['clustered'] clustered_local = cluster_local(failed_tests) clustered = cluster_global(clustered_local, previous_clustered) logging.info("Rendering results...") start = time.time() data = render(builds, clustered) if args.owners: owners = json.load(args.owners) annotate_owners(data, builds, owners) with open(args.output, 'w') as f: json.dump(data, f, sort_keys=True) if args.output_slices: assert 'PREFIX' in args.output_slices for subset in range(256): id_prefix = '%02x' % subset with open(args.output_slices.replace('PREFIX', id_prefix), 'w') as f: json.dump(render_slice(data, builds, id_prefix), f, sort_keys=True) if args.owners: owners.setdefault('testing', []) # for output for owner in owners: with open(args.output_slices.replace('PREFIX', 'sig-' + owner), 'w') as f: json.dump(render_slice(data, builds, prefix='', owner=owner), f, sort_keys=True) elapsed = time.time() - start logging.info('Finished rendering results in %dm%ds', elapsed / 60, elapsed % 60) if __name__ == '__main__': main(parse_args(sys.argv[1:]))<|fim▁end|>
<|file_name|>bill.js<|end_file_name|><|fim▁begin|>/*! 一叶孤舟 | qq:28701884 | 欢迎指教 */ var bill = bill || {}; //初始化 bill.init = function (){ if (com.store){ clearInterval(bill.timer); bill.setBillList(com.arr2Clone(com.initMap)); //写入棋谱列表 play.isPlay=false; com.show(); }else { bill.timer = setInterval("bill.init()",300); } } //把所有棋谱写入棋谱列表 bill.setBillList = function (map){ var list=com.get("billList") for (var i=0; i < com.store.length ; i++){ var option = document.createElement('option'); option.text='棋谱'+(i+1); option.value=i; list.add(option , null); } list.addEventListener("change", function(e) { bill.setBox (com.store[this.value], map) }) bill.setBox (com.store[0], map) } //棋谱分析 写入 bill.setMove = function (bl,inx,map){<|fim▁hole|> var key = map[i][n]; if (key){ com.mans[key].x=n; com.mans[key].y=i; com.mans[key].isShow = true; } } } for (var i=0; i<= inx ; i++){ var n = i*4 var y = bl[n+1] var newX = bl[n+2] var x = bl[n+0] var newY = bl[n+3] if (com.mans[map[newY][newX]]) { com.mans[map[newY][newX]].isShow = false; } com.mans[map[y][x]].x = newX; com.mans[map[y][x]].y = newY; if (i == inx) { com.showPane(x ,y,newX,newY); } map[newY][newX] = map[y][x]; delete map[y][x]; } return map; } //写入棋谱 bill.setBox = function (bl,initMap){ var map = com.arr2Clone(initMap); var bl= bl.split(""); var h=''; for (var i=0; i< bl.length ; i+=4){ h +='<li id="move_'+(i/4)+'">'; var x = bl[i+0]; var y = bl[i+1]; var newX = bl[i+2]; var newY = bl[i+3]; h += com.createMove(map,x,y,newX,newY); h +='</li>\n\r'; } com.get("billBox").innerHTML = h; var doms=com.get("billBox").getElementsByTagName("li"); for (var i=0; i<doms.length; i++){ doms[i].addEventListener("click", function(e) { var inx = this.getAttribute("id").split("_")[1]; bill.setMove (bl , inx , initMap) com.show(); }) } }<|fim▁end|>
var map = com.arr2Clone(map); for (var i=0; i<map.length; i++){ for (var n=0; n<map[i].length; n++){
<|file_name|>vhtml-tests.ts<|end_file_name|><|fim▁begin|>/** * Tests for Hyperscript */ import h = require('vhtml'); // Empty element // $ExpectType string h('div'); // $ExpectType string h('span', null, 'Hello, world!'); // $ExpectType string h( 'section', { id: 'some-id' }, h('h1', null, 'Title'), 'List of items:', h('ol', null, h('li', null, 'First item'), h('li', null, 'Second item'), h('li', null, 'Third item')), ); // Children can be of any type // $ExpectType string h( 'blockquote', null, h('span', null, 99), h('span', null, 'string'), h('span', null, true), h('span', null, /pattern.*/), h('span', null, null), h('span', null, undefined), ); // Incorrect attribute type // $ExpectError h('div', { class: 1 }); // data-* attributes // (for hyperscript, allow unknown fields to have arbitrary types) // $ExpectType string h('div', { 'data-value': 1, 'data-value-2': 'asdf' }); // $ExpectError h('div', { class: 1, 'data-value': 1, 'data-value-2': 'asdf' }); // Unknown tags can have arbitrary attributes // $ExpectType string h('mytag', { foo: 1, bar: true }); // -------- Special attributes -------- // // Both htmlFor and for are supported // $ExpectType string h('label', { htmlFor: 'foo' }); // $ExpectType string<|fim▁hole|>// $ExpectType string h('button', { className: 'bar' }); // $ExpectType string h('button', { class: 'bar' }); // dangerouslySetInnerHTML // $ExpectType string h('main', { dangerouslySetInnerHTML: { __html: '&trade;' } }); // $ExpectError h('main', { dangerouslySetInnerHTML: 'foo bar' }); // -------- Functional Pseudo-Components -------- // function Component({ prop1, prop2 }: { prop1: string; prop2?: number }): string { return h('div', { id: prop1 }, prop2); } // $ExpectType string h(Component, { prop1: 'foo', prop2: 125 }); // $ExpectType string h('body', null, h(Component, { prop1: 'foo', prop2: 125 })); // Missing required prop // $ExpectError h(Component, { prop2: 125 }); // Incorrect prop type // $ExpectError h(Component, { prop1: 250 });<|fim▁end|>
h('label', { for: 'foo' }); // Both className and class are supported
<|file_name|>_redis.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import redis import json class Redis(object): def __init__(self, host="localhost", port=6379): self._host = host self._port = port self._redis_cursor = None def conn(self): if self._redis_cursor is None: pool = redis.ConnectionPool(host=self._host, port=self._port, db=0) self._redis_cursor = redis.Redis(connection_pool=pool) def enqueue(self, qname, data):<|fim▁hole|> self.conn() self._redis_cursor.rpush(qname, json.dumps(data)) def dequeue(self, qname): self.conn() r = self._redis_cursor.blpop(qname) return json.loads(r[1]) if __name__ == "__main__": pass<|fim▁end|>
<|file_name|>TargetsParams.ts<|end_file_name|><|fim▁begin|>import { ProjectOperationCredentials } from "../ProjectOperationCredentials"; import { RepoFilter } from "../repoFilter"; import { RemoteRepoRef, RepoRef, } from "../RepoId"; import { Credentialed } from "./Credentialed"; import { RemoteLocator } from "./RemoteLocator"; import { GitHubNameRegExp } from "./validationPatterns"; /** * Base parameters for working with repo(s). * Allows use of regex. */ export abstract class TargetsParams implements Credentialed, RemoteLocator { public abstract owner: string; /** * Repo name. May be a repo name or a string containing a regular expression. */ public abstract repo: string; <|fim▁hole|> public abstract branch: string; public abstract credentials: ProjectOperationCredentials; get usesRegex(): boolean { return !!this.repo && (!GitHubNameRegExp.pattern.test(this.repo) || !this.owner); } public abstract repoRef: RemoteRepoRef; /** * If we're not tied to a single repo ref, test this RepoRef * @param {RepoRef} rr * @return {boolean} */ public test: RepoFilter = rr => { if (this.repoRef) { const my = this.repoRef; return my.owner === rr.owner && my.repo === rr.repo; } if (this.usesRegex) { if (this.owner && this.owner !== rr.owner) { return false; } return new RegExp(this.repo).test(rr.repo); } return false; } }<|fim▁end|>
public abstract sha: string;
<|file_name|>main.go<|end_file_name|><|fim▁begin|>// Copyright 2013 The Prometheus 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. package main import ( "bufio" "fmt" "net" "net/http" _ "net/http/pprof" "os" "os/signal" "strconv" "syscall" "github.com/go-kit/log" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/common/promlog" "github.com/prometheus/common/promlog/flag" "github.com/prometheus/common/version" "gopkg.in/alecthomas/kingpin.v2" "github.com/prometheus/statsd_exporter/pkg/address" "github.com/prometheus/statsd_exporter/pkg/event" "github.com/prometheus/statsd_exporter/pkg/exporter" "github.com/prometheus/statsd_exporter/pkg/level" "github.com/prometheus/statsd_exporter/pkg/line" "github.com/prometheus/statsd_exporter/pkg/listener" "github.com/prometheus/statsd_exporter/pkg/mapper" "github.com/prometheus/statsd_exporter/pkg/mappercache/lru" "github.com/prometheus/statsd_exporter/pkg/mappercache/randomreplacement" "github.com/prometheus/statsd_exporter/pkg/relay" ) var ( eventStats = promauto.NewCounterVec( prometheus.CounterOpts{ Name: "statsd_exporter_events_total", Help: "The total number of StatsD events seen.", }, []string{"type"}, ) eventsFlushed = promauto.NewCounter( prometheus.CounterOpts{ Name: "statsd_exporter_event_queue_flushed_total", Help: "Number of times events were flushed to exporter", }, ) eventsUnmapped = promauto.NewCounter( prometheus.CounterOpts{ Name: "statsd_exporter_events_unmapped_total", Help: "The total number of StatsD events no mapping was found for.", }) udpPackets = promauto.NewCounter( prometheus.CounterOpts{ Name: "statsd_exporter_udp_packets_total", Help: "The total number of StatsD packets received over UDP.", }, ) tcpConnections = promauto.NewCounter( prometheus.CounterOpts{ Name: "statsd_exporter_tcp_connections_total", Help: "The total number of TCP connections handled.", }, ) tcpErrors = promauto.NewCounter( prometheus.CounterOpts{ Name: "statsd_exporter_tcp_connection_errors_total", Help: "The number of errors encountered reading from TCP.", }, ) tcpLineTooLong = promauto.NewCounter( prometheus.CounterOpts{ Name: "statsd_exporter_tcp_too_long_lines_total", Help: "The number of lines discarded due to being too long.", }, ) unixgramPackets = promauto.NewCounter( prometheus.CounterOpts{ Name: "statsd_exporter_unixgram_packets_total", Help: "The total number of StatsD packets received over Unixgram.", }, ) linesReceived = promauto.NewCounter( prometheus.CounterOpts{ Name: "statsd_exporter_lines_total", Help: "The total number of StatsD lines received.", }, ) samplesReceived = promauto.NewCounter( prometheus.CounterOpts{ Name: "statsd_exporter_samples_total", Help: "The total number of StatsD samples received.", }, ) sampleErrors = promauto.NewCounterVec( prometheus.CounterOpts{ Name: "statsd_exporter_sample_errors_total", Help: "The total number of errors parsing StatsD samples.", }, []string{"reason"}, ) tagsReceived = promauto.NewCounter( prometheus.CounterOpts{ Name: "statsd_exporter_tags_total", Help: "The total number of DogStatsD tags processed.", }, ) tagErrors = promauto.NewCounter( prometheus.CounterOpts{ Name: "statsd_exporter_tag_errors_total", Help: "The number of errors parsing DogStatsD tags.", }, ) configLoads = promauto.NewCounterVec( prometheus.CounterOpts{ Name: "statsd_exporter_config_reloads_total", Help: "The number of configuration reloads.", }, []string{"outcome"}, ) mappingsCount = promauto.NewGauge(prometheus.GaugeOpts{ Name: "statsd_exporter_loaded_mappings", Help: "The current number of configured metric mappings.", }) conflictingEventStats = promauto.NewCounterVec( prometheus.CounterOpts{ Name: "statsd_exporter_events_conflict_total", Help: "The total number of StatsD events with conflicting names.", }, []string{"type"}, ) errorEventStats = promauto.NewCounterVec( prometheus.CounterOpts{ Name: "statsd_exporter_events_error_total", Help: "The total number of StatsD events discarded due to errors.", }, []string{"reason"}, ) eventsActions = promauto.NewCounterVec( prometheus.CounterOpts{ Name: "statsd_exporter_events_actions_total", Help: "The total number of StatsD events by action.", }, []string{"action"}, ) metricsCount = promauto.NewGaugeVec( prometheus.GaugeOpts{ Name: "statsd_exporter_metrics_total", Help: "The total number of metrics.", }, []string{"type"}, ) ) func serveHTTP(mux http.Handler, listenAddress string, logger log.Logger) { level.Error(logger).Log("msg", http.ListenAndServe(listenAddress, mux)) os.Exit(1) } func sighupConfigReloader(fileName string, mapper *mapper.MetricMapper, logger log.Logger) { signals := make(chan os.Signal, 1) signal.Notify(signals, syscall.SIGHUP) for s := range signals { if fileName == "" { level.Warn(logger).Log("msg", "Received signal but no mapping config to reload", "signal", s) continue } level.Info(logger).Log("msg", "Received signal, attempting reload", "signal", s) reloadConfig(fileName, mapper, logger) } } func reloadConfig(fileName string, mapper *mapper.MetricMapper, logger log.Logger) { err := mapper.InitFromFile(fileName) if err != nil { level.Info(logger).Log("msg", "Error reloading config", "error", err) configLoads.WithLabelValues("failure").Inc() } else { level.Info(logger).Log("msg", "Config reloaded successfully") configLoads.WithLabelValues("success").Inc() } } func dumpFSM(mapper *mapper.MetricMapper, dumpFilename string, logger log.Logger) error { f, err := os.Create(dumpFilename) if err != nil { return err } level.Info(logger).Log("msg", "Start dumping FSM", "file_name", dumpFilename) w := bufio.NewWriter(f) mapper.FSM.DumpFSM(w) w.Flush() f.Close() level.Info(logger).Log("msg", "Finish dumping FSM") return nil } func getCache(cacheSize int, cacheType string, registerer prometheus.Registerer) (mapper.MetricMapperCache, error) {<|fim▁hole|> return nil, nil } else { switch cacheType { case "lru": cache, err = lru.NewMetricMapperLRUCache(registerer, cacheSize) case "random": cache, err = randomreplacement.NewMetricMapperRRCache(registerer, cacheSize) default: err = fmt.Errorf("unsupported cache type %q", cacheType) } if err != nil { return nil, err } } return cache, nil } func main() { var ( listenAddress = kingpin.Flag("web.listen-address", "The address on which to expose the web interface and generated Prometheus metrics.").Default(":9102").String() enableLifecycle = kingpin.Flag("web.enable-lifecycle", "Enable shutdown and reload via HTTP request.").Default("false").Bool() metricsEndpoint = kingpin.Flag("web.telemetry-path", "Path under which to expose metrics.").Default("/metrics").String() statsdListenUDP = kingpin.Flag("statsd.listen-udp", "The UDP address on which to receive statsd metric lines. \"\" disables it.").Default(":9125").String() statsdListenTCP = kingpin.Flag("statsd.listen-tcp", "The TCP address on which to receive statsd metric lines. \"\" disables it.").Default(":9125").String() statsdListenUnixgram = kingpin.Flag("statsd.listen-unixgram", "The Unixgram socket path to receive statsd metric lines in datagram. \"\" disables it.").Default("").String() // not using Int here because flag displays default in decimal, 0755 will show as 493 statsdUnixSocketMode = kingpin.Flag("statsd.unixsocket-mode", "The permission mode of the unix socket.").Default("755").String() mappingConfig = kingpin.Flag("statsd.mapping-config", "Metric mapping configuration file name.").String() readBuffer = kingpin.Flag("statsd.read-buffer", "Size (in bytes) of the operating system's transmit read buffer associated with the UDP or Unixgram connection. Please make sure the kernel parameters net.core.rmem_max is set to a value greater than the value specified.").Int() cacheSize = kingpin.Flag("statsd.cache-size", "Maximum size of your metric mapping cache. Relies on least recently used replacement policy if max size is reached.").Default("1000").Int() cacheType = kingpin.Flag("statsd.cache-type", "Metric mapping cache type. Valid options are \"lru\" and \"random\"").Default("lru").Enum("lru", "random") eventQueueSize = kingpin.Flag("statsd.event-queue-size", "Size of internal queue for processing events.").Default("10000").Uint() eventFlushThreshold = kingpin.Flag("statsd.event-flush-threshold", "Number of events to hold in queue before flushing.").Default("1000").Int() eventFlushInterval = kingpin.Flag("statsd.event-flush-interval", "Maximum time between event queue flushes.").Default("200ms").Duration() dumpFSMPath = kingpin.Flag("debug.dump-fsm", "The path to dump internal FSM generated for glob matching as Dot file.").Default("").String() checkConfig = kingpin.Flag("check-config", "Check configuration and exit.").Default("false").Bool() dogstatsdTagsEnabled = kingpin.Flag("statsd.parse-dogstatsd-tags", "Parse DogStatsd style tags. Enabled by default.").Default("true").Bool() influxdbTagsEnabled = kingpin.Flag("statsd.parse-influxdb-tags", "Parse InfluxDB style tags. Enabled by default.").Default("true").Bool() libratoTagsEnabled = kingpin.Flag("statsd.parse-librato-tags", "Parse Librato style tags. Enabled by default.").Default("true").Bool() signalFXTagsEnabled = kingpin.Flag("statsd.parse-signalfx-tags", "Parse SignalFX style tags. Enabled by default.").Default("true").Bool() relayAddr = kingpin.Flag("statsd.relay.address", "The UDP relay target address (host:port)").String() relayPacketLen = kingpin.Flag("statsd.relay.packet-length", "Maximum relay output packet length to avoid fragmentation").Default("1400").Uint() ) promlogConfig := &promlog.Config{} flag.AddFlags(kingpin.CommandLine, promlogConfig) kingpin.Version(version.Print("statsd_exporter")) kingpin.HelpFlag.Short('h') kingpin.Parse() logger := promlog.New(promlogConfig) if err := level.SetLogLevel(promlogConfig.Level.String()); err != nil { level.Error(logger).Log("msg", "failed to set log level", "error", err) os.Exit(1) } prometheus.MustRegister(version.NewCollector("statsd_exporter")) parser := line.NewParser() if *dogstatsdTagsEnabled { parser.EnableDogstatsdParsing() } if *influxdbTagsEnabled { parser.EnableInfluxdbParsing() } if *libratoTagsEnabled { parser.EnableLibratoParsing() } if *signalFXTagsEnabled { parser.EnableSignalFXParsing() } level.Info(logger).Log("msg", "Starting StatsD -> Prometheus Exporter", "version", version.Info()) level.Info(logger).Log("msg", "Build context", "context", version.BuildContext()) events := make(chan event.Events, *eventQueueSize) defer close(events) eventQueue := event.NewEventQueue(events, *eventFlushThreshold, *eventFlushInterval, eventsFlushed) thisMapper := &mapper.MetricMapper{Registerer: prometheus.DefaultRegisterer, MappingsCount: mappingsCount, Logger: logger} cache, err := getCache(*cacheSize, *cacheType, thisMapper.Registerer) if err != nil { level.Error(logger).Log("msg", "Unable to setup metric mapper cache", "error", err) os.Exit(1) } thisMapper.UseCache(cache) if *mappingConfig != "" { err := thisMapper.InitFromFile(*mappingConfig) if err != nil { level.Error(logger).Log("msg", "error loading config", "error", err) os.Exit(1) } if *dumpFSMPath != "" { err := dumpFSM(thisMapper, *dumpFSMPath, logger) if err != nil { level.Error(logger).Log("msg", "error dumping FSM", "error", err) // Failure to dump the FSM is an error (the user asked for it and it // didn't happen) but not fatal (the exporter is fully functional // afterwards). } } } exporter := exporter.NewExporter(prometheus.DefaultRegisterer, thisMapper, logger, eventsActions, eventsUnmapped, errorEventStats, eventStats, conflictingEventStats, metricsCount) if *checkConfig { level.Info(logger).Log("msg", "Configuration check successful, exiting") return } var relayTarget *relay.Relay if *relayAddr != "" { var err error relayTarget, err = relay.NewRelay(logger, *relayAddr, *relayPacketLen) if err != nil { level.Error(logger).Log("msg", "Unable to create relay", "err", err) os.Exit(1) } } level.Info(logger).Log("msg", "Accepting StatsD Traffic", "udp", *statsdListenUDP, "tcp", *statsdListenTCP, "unixgram", *statsdListenUnixgram) level.Info(logger).Log("msg", "Accepting Prometheus Requests", "addr", *listenAddress) if *statsdListenUDP == "" && *statsdListenTCP == "" && *statsdListenUnixgram == "" { level.Error(logger).Log("At least one of UDP/TCP/Unixgram listeners must be specified.") os.Exit(1) } if *statsdListenUDP != "" { udpListenAddr, err := address.UDPAddrFromString(*statsdListenUDP) if err != nil { level.Error(logger).Log("msg", "invalid UDP listen address", "address", *statsdListenUDP, "error", err) os.Exit(1) } uconn, err := net.ListenUDP("udp", udpListenAddr) if err != nil { level.Error(logger).Log("msg", "failed to start UDP listener", "error", err) os.Exit(1) } if *readBuffer != 0 { err = uconn.SetReadBuffer(*readBuffer) if err != nil { level.Error(logger).Log("msg", "error setting UDP read buffer", "error", err) os.Exit(1) } } ul := &listener.StatsDUDPListener{ Conn: uconn, EventHandler: eventQueue, Logger: logger, LineParser: parser, UDPPackets: udpPackets, LinesReceived: linesReceived, EventsFlushed: eventsFlushed, Relay: relayTarget, SampleErrors: *sampleErrors, SamplesReceived: samplesReceived, TagErrors: tagErrors, TagsReceived: tagsReceived, } go ul.Listen() } if *statsdListenTCP != "" { tcpListenAddr, err := address.TCPAddrFromString(*statsdListenTCP) if err != nil { level.Error(logger).Log("msg", "invalid TCP listen address", "address", *statsdListenUDP, "error", err) os.Exit(1) } tconn, err := net.ListenTCP("tcp", tcpListenAddr) if err != nil { level.Error(logger).Log("msg", err) os.Exit(1) } defer tconn.Close() tl := &listener.StatsDTCPListener{ Conn: tconn, EventHandler: eventQueue, Logger: logger, LineParser: parser, LinesReceived: linesReceived, EventsFlushed: eventsFlushed, Relay: relayTarget, SampleErrors: *sampleErrors, SamplesReceived: samplesReceived, TagErrors: tagErrors, TagsReceived: tagsReceived, TCPConnections: tcpConnections, TCPErrors: tcpErrors, TCPLineTooLong: tcpLineTooLong, } go tl.Listen() } if *statsdListenUnixgram != "" { var err error if _, err = os.Stat(*statsdListenUnixgram); !os.IsNotExist(err) { level.Error(logger).Log("msg", "Unixgram socket already exists", "socket_name", *statsdListenUnixgram) os.Exit(1) } uxgconn, err := net.ListenUnixgram("unixgram", &net.UnixAddr{ Net: "unixgram", Name: *statsdListenUnixgram, }) if err != nil { level.Error(logger).Log("msg", "failed to listen on Unixgram socket", "error", err) os.Exit(1) } defer uxgconn.Close() if *readBuffer != 0 { err = uxgconn.SetReadBuffer(*readBuffer) if err != nil { level.Error(logger).Log("msg", "error setting Unixgram read buffer", "error", err) os.Exit(1) } } ul := &listener.StatsDUnixgramListener{ Conn: uxgconn, EventHandler: eventQueue, Logger: logger, LineParser: parser, UnixgramPackets: unixgramPackets, LinesReceived: linesReceived, EventsFlushed: eventsFlushed, Relay: relayTarget, SampleErrors: *sampleErrors, SamplesReceived: samplesReceived, TagErrors: tagErrors, TagsReceived: tagsReceived, } go ul.Listen() // if it's an abstract unix domain socket, it won't exist on fs // so we can't chmod it either if _, err := os.Stat(*statsdListenUnixgram); !os.IsNotExist(err) { defer os.Remove(*statsdListenUnixgram) // convert the string to octet perm, err := strconv.ParseInt("0"+string(*statsdUnixSocketMode), 8, 32) if err != nil { level.Warn(logger).Log("Bad permission %s: %v, ignoring\n", *statsdUnixSocketMode, err) } else { err = os.Chmod(*statsdListenUnixgram, os.FileMode(perm)) if err != nil { level.Warn(logger).Log("Failed to change unixgram socket permission: %v", err) } } } } mux := http.DefaultServeMux mux.Handle(*metricsEndpoint, promhttp.Handler()) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`<html> <head><title>StatsD Exporter</title></head> <body> <h1>StatsD Exporter</h1> <p><a href="` + *metricsEndpoint + `">Metrics</a></p> </body> </html>`)) }) quitChan := make(chan struct{}, 1) if *enableLifecycle { mux.HandleFunc("/-/reload", func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodPut || r.Method == http.MethodPost { fmt.Fprintf(w, "Requesting reload") if *mappingConfig == "" { level.Warn(logger).Log("msg", "Received lifecycle api reload but no mapping config to reload") return } level.Info(logger).Log("msg", "Received lifecycle api reload, attempting reload") reloadConfig(*mappingConfig, thisMapper, logger) } }) mux.HandleFunc("/-/quit", func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodPut || r.Method == http.MethodPost { fmt.Fprintf(w, "Requesting termination... Goodbye!") quitChan <- struct{}{} } }) } mux.HandleFunc("/-/healthy", func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet { level.Debug(logger).Log("msg", "Received health check") w.WriteHeader(http.StatusOK) fmt.Fprintf(w, "Statsd Exporter is Healthy.\n") } }) mux.HandleFunc("/-/ready", func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet { level.Debug(logger).Log("msg", "Received ready check") w.WriteHeader(http.StatusOK) fmt.Fprintf(w, "Statsd Exporter is Ready.\n") } }) go serveHTTP(mux, *listenAddress, logger) go sighupConfigReloader(*mappingConfig, thisMapper, logger) go exporter.Listen(events) signals := make(chan os.Signal, 1) signal.Notify(signals, os.Interrupt, syscall.SIGTERM) // quit if we get a message on either channel select { case sig := <-signals: level.Info(logger).Log("msg", "Received os signal, exiting", "signal", sig.String()) case <-quitChan: level.Info(logger).Log("msg", "Received lifecycle api quit, exiting") } }<|fim▁end|>
var cache mapper.MetricMapperCache var err error if cacheSize == 0 {
<|file_name|>debounce.py<|end_file_name|><|fim▁begin|>"""Debouncing provides functions for delaying or skipping a queue `push` subject to a specified debouncing constraint. When used with idempotent operations, this provides a safe and consistent method of throttling queue pushes within Deferrable itself. The debouncing constraint is defined as follows: If `debounce_always_delay` is `False`, items should be made available for execution as quickly as possible subject to the constraint that the same item be made available at most once per `debounce_seconds` seconds. If 'debounce_always_delay` is `True`, the item will be always either be skipped (debounced) or delayed by the full `debounce_seconds` amount. The constraint that the item is processed at most once per `debounce_seconds` seconds still holds.""" import math import time class DebounceStrategy(object): PUSH_NOW = 1<|fim▁hole|> return u"debounce.{}.{}.{}".format(item['method'], item['args'], item['kwargs']) def _last_push_key(item): return u"last_push.{}.{}.{}".format(item['method'], item['args'], item['kwargs']) def set_debounce_keys_for_push_now(redis_client, item, debounce_seconds): """Set a key in Redis indicating the last time this item was potentially available inside a non-delay queue. Expires after 2*delay period to keep Redis clean. The 2* ensures that the key would have been stale at the period it is reaped.""" redis_client.set(_last_push_key(item), time.time(), px=int(2*debounce_seconds*1000)) def set_debounce_keys_for_push_delayed(redis_client, item, seconds_to_delay, debounce_seconds): redis_client.scripts.set_debounce_keys(keys=[_last_push_key(item), _debounce_key(item)], args=[time.time(), seconds_to_delay, debounce_seconds]) def get_debounce_strategy(redis_client, item, debounce_seconds, debounce_always_delay): last_push_time, debounce_value = redis_client.scripts.get_debounce_keys(keys=[_last_push_key(item), _debounce_key(item)]) if debounce_value: return DebounceStrategy.SKIP, 0 if debounce_always_delay: return DebounceStrategy.PUSH_DELAYED, debounce_seconds if not last_push_time: return DebounceStrategy.PUSH_NOW, 0 seconds_since_last_push = time.time() - float(last_push_time) if seconds_since_last_push > debounce_seconds: return DebounceStrategy.PUSH_NOW, 0 return DebounceStrategy.PUSH_DELAYED, math.ceil(debounce_seconds - seconds_since_last_push)<|fim▁end|>
PUSH_DELAYED = 2 SKIP = 3 def _debounce_key(item):
<|file_name|>add_db.py<|end_file_name|><|fim▁begin|># coding: utf-8 import db_info import db_cancel import db_news import hashlib from tweeter import format_info, format_cancel, format_news import settings log = settings.log def add_info_to_queue(q, *args):<|fim▁hole|> # 更新した数をカウント updated = 0 for lec_info in args: id = db_info.add_info(*lec_info) if id is not False: lec_info.append(id) # Tweetする用に文章をフォーマット t = format_info(*lec_info) # キューに投入 q.put(t) updated += 1 else: pass else: # 更新した数を返す return updated except Exception as e: log.exception(e) def add_cancel_to_queue(q, *args): try: # 更新した数をカウント updated = 0 for lec_cancel in args: cancel_id = db_cancel.add_cancel(*lec_cancel) if cancel_id is not False: lec_cancel.append(cancel_id) # Tweetする用に文章をフォーマット t = format_cancel(*lec_cancel) # キューに投入 q.put(t) updated += 1 else: pass else: # 更新数を返す return updated except Exception as e: log.exception(e) def add_news_to_queue(q, *args): try: # 更新した数をカウント updated = 0 for news in args: news_id = db_news.add_news(*news) if news_id is not False: news.append(news_id) # Tweetする用に文章をフォーマット t = format_news(*news) # キューに投入 q.put(t) updated += 1 else: pass else: # 更新数を返す return updated except Exception as e: log.exception(e)<|fim▁end|>
try:
<|file_name|>simulated_annealing_test.py<|end_file_name|><|fim▁begin|>import unittest import numpy as np import pyoptima as opt class SimulatedAnnealingTest(unittest.TestCase): def test_with_parabola(self): """ Test with a simple parabolic function with 2 variables """ def neighbour_func(params): new_params = params params['x0'] += np.random.uniform(-1., 1.) params['x1'] += np.random.uniform(-1., 1.) return new_params hyper_params = { 'temperature_func': lambda t, i: t/np.log(i+2), 'neighbour_func': neighbour_func, 'initial_temp': 1000000.0 } params = {} params["x0"] = np.random.uniform(-10., 10.) params["x1"] = np.random.uniform(-10., 10.) s = opt.SimulatedAnnealing(params, hyper_params) s.optimize(opt.parabola, 100000) bst_solution = s.get_best_parameters() self.assertAlmostEqual(bst_solution['x0'], 0, 2)<|fim▁hole|>if __name__ == "__main__": unittest.main()<|fim▁end|>
self.assertAlmostEqual(bst_solution['x1'], 0, 2)
<|file_name|>install.py<|end_file_name|><|fim▁begin|># # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # from __future__ import print_function import errno import logging import os import pickle import shutil import sys import tempfile import textwrap import six from ipalib.install import certmonger, sysrestore from ipapython import ipautil from ipapython.ipautil import ( format_netloc, ipa_generate_password, run, user_input) from ipapython.admintool import ScriptError from ipaplatform import services from ipaplatform.paths import paths from ipaplatform.tasks import tasks from ipalib import api, errors, x509 from ipalib.constants import DOMAIN_LEVEL_0 from ipalib.util import ( validate_domain_name, no_matching_interface_for_ip_address_warning, ) import ipaclient.install.ntpconf from ipaserver.install import ( adtrust, bindinstance, ca, dns, dsinstance, httpinstance, installutils, kra, krbinstance, ntpinstance, otpdinstance, custodiainstance, replication, service, sysupgrade) from ipaserver.install.installutils import ( IPA_MODULES, BadHostError, get_fqdn, get_server_ip_address, is_ipa_configured, load_pkcs12, read_password, verify_fqdn, update_hosts_file) if six.PY3: unicode = str try: from ipaserver.install import adtrustinstance _server_trust_ad_installed = True except ImportError: _server_trust_ad_installed = False NoneType = type(None) logger = logging.getLogger(__name__) SYSRESTORE_DIR_PATH = paths.SYSRESTORE def validate_dm_password(password): if len(password) < 8: raise ValueError("Password must be at least 8 characters long") if any(ord(c) < 0x20 for c in password): raise ValueError("Password must not contain control characters") if any(ord(c) >= 0x7F for c in password): raise ValueError("Password must only contain ASCII characters") # Disallow characters that pkisilent doesn't process properly: bad_characters = '\\' if any(c in bad_characters for c in password): raise ValueError('Password must not contain these characters: %s' % ', '.join('"%s"' % c for c in bad_characters)) # TODO: Check https://fedorahosted.org/389/ticket/47849 # Actual behavior of setup-ds.pl is that it does not accept white # space characters in password when called interactively but does when # provided such password in INF file. But it ignores leading and trailing # white spaces in INF file. # Disallow leading/trailing whaitespaces if password.strip() != password: raise ValueError('Password must not start or end with whitespace.') def validate_admin_password(password): if len(password) < 8: raise ValueError("Password must be at least 8 characters long") if any(ord(c) < 0x20 for c in password): raise ValueError("Password must not contain control characters") if any(ord(c) >= 0x7F for c in password): raise ValueError("Password must only contain ASCII characters") # Disallow characters that pkisilent doesn't process properly: bad_characters = '\\' if any(c in bad_characters for c in password): raise ValueError('Password must not contain these characters: %s' % ', '.join('"%s"' % c for c in bad_characters)) def read_cache(dm_password): """ Returns a dict of cached answers or empty dict if no cache file exists. """ if not os.path.isfile(paths.ROOT_IPA_CACHE): return {} top_dir = tempfile.mkdtemp("ipa") fname = "%s/cache" % top_dir try: installutils.decrypt_file(paths.ROOT_IPA_CACHE, fname, dm_password, top_dir) except Exception as e: shutil.rmtree(top_dir) raise Exception("Decryption of answer cache in %s failed, please " "check your password." % paths.ROOT_IPA_CACHE) try: with open(fname, 'rb') as f: try: optdict = pickle.load(f) except Exception as e: raise Exception("Parse error in %s: %s" % (paths.ROOT_IPA_CACHE, str(e))) except IOError as e: raise Exception("Read error in %s: %s" % (paths.ROOT_IPA_CACHE, str(e))) finally: shutil.rmtree(top_dir) # These are the only ones that may be overridden try: del optdict['external_cert_files'] except KeyError: pass return optdict def write_cache(options): """ Takes a dict as input and writes a cached file of answers """ top_dir = tempfile.mkdtemp("ipa") fname = "%s/cache" % top_dir try: with open(fname, 'wb') as f: pickle.dump(options, f)<|fim▁hole|> paths.ROOT_IPA_CACHE, options['dm_password'], top_dir) except IOError as e: raise Exception("Unable to cache command-line options %s" % str(e)) finally: shutil.rmtree(top_dir) def read_host_name(host_default, no_host_dns=False): print("Enter the fully qualified domain name of the computer") print("on which you're setting up server software. Using the form") print("<hostname>.<domainname>") print("Example: master.example.com.") print("") print("") if host_default == "": host_default = "master.example.com" host_name = user_input("Server host name", host_default, allow_empty=False) print("") verify_fqdn(host_name, no_host_dns) return host_name def read_domain_name(domain_name, unattended): print("The domain name has been determined based on the host name.") print("") if not unattended: domain_name = str(user_input("Please confirm the domain name", domain_name)) print("") return domain_name def read_realm_name(domain_name, unattended): print("The kerberos protocol requires a Realm name to be defined.") print("This is typically the domain name converted to uppercase.") print("") if unattended: return domain_name.upper() realm_name = str(user_input("Please provide a realm name", domain_name.upper())) upper_dom = realm_name.upper() if upper_dom != realm_name: print("An upper-case realm name is required.") if not user_input("Do you want to use " + upper_dom + " as realm name?", True): raise ScriptError( "An upper-case realm name is required. Unable to continue.") else: realm_name = upper_dom print("") return realm_name def read_dm_password(): print("Certain directory server operations require an administrative user.") print("This user is referred to as the Directory Manager and has full " "access") print("to the Directory for system management tasks and will be added to " "the") print("instance of directory server created for IPA.") print("The password must be at least 8 characters long.") print("") # TODO: provide the option of generating a random password dm_password = read_password("Directory Manager", validator=validate_dm_password) return dm_password def read_admin_password(): print("The IPA server requires an administrative user, named 'admin'.") print("This user is a regular system account used for IPA server " "administration.") print("") # TODO: provide the option of generating a random password admin_password = read_password("IPA admin", validator=validate_admin_password) return admin_password def check_dirsrv(unattended): (ds_unsecure, ds_secure) = dsinstance.check_ports() if not ds_unsecure or not ds_secure: msg = ("IPA requires ports 389 and 636 for the Directory Server.\n" "These are currently in use:\n") if not ds_unsecure: msg += "\t389\n" if not ds_secure: msg += "\t636\n" raise ScriptError(msg) def common_cleanup(func): def decorated(installer): success = False try: func(installer) success = True except KeyboardInterrupt: ds = installer._ds print("\nCleaning up...") if ds: print("Removing configuration for %s instance" % ds.serverid) ds.stop() if ds.serverid: try: dsinstance.remove_ds_instance(ds.serverid) except ipautil.CalledProcessError: logger.error("Failed to remove DS instance. You " "may need to remove instance data " "manually") raise ScriptError() finally: if not success and installer._installation_cleanup: # Do a cautious clean up as we don't know what failed and # what is the state of the environment try: installer._fstore.restore_file(paths.HOSTS) except Exception: pass return decorated def remove_master_from_managed_topology(api_instance, options): try: # we may force the removal server_del_options = dict( force=True, ignore_topology_disconnect=options.ignore_topology_disconnect, ignore_last_of_role=options.ignore_last_of_role ) replication.run_server_del_as_cli( api_instance, api_instance.env.host, **server_del_options) except errors.ServerRemovalError as e: raise ScriptError(str(e)) except Exception as e: # if the master was already deleted we will just get a warning logger.warning("Failed to delete master: %s", e) @common_cleanup def install_check(installer): options = installer dirsrv_pkcs12_file = installer._dirsrv_pkcs12_file http_pkcs12_file = installer._http_pkcs12_file pkinit_pkcs12_file = installer._pkinit_pkcs12_file dirsrv_pkcs12_info = installer._dirsrv_pkcs12_info http_pkcs12_info = installer._http_pkcs12_info pkinit_pkcs12_info = installer._pkinit_pkcs12_info external_cert_file = installer._external_cert_file external_ca_file = installer._external_ca_file http_ca_cert = installer._ca_cert tasks.check_ipv6_stack_enabled() tasks.check_selinux_status() if options.master_password: msg = ("WARNING:\noption '-P/--master-password' is deprecated. " "KDC master password of sufficient strength is autogenerated " "during IPA server installation and should not be set " "manually.") print(textwrap.fill(msg, width=79, replace_whitespace=False)) installer._installation_cleanup = True print("\nThe log file for this installation can be found in " "/var/log/ipaserver-install.log") if (not options.external_ca and not options.external_cert_files and is_ipa_configured()): installer._installation_cleanup = False raise ScriptError( "IPA server is already configured on this system.\n" "If you want to reinstall the IPA server, please uninstall " "it first using 'ipa-server-install --uninstall'.") client_fstore = sysrestore.FileStore(paths.IPA_CLIENT_SYSRESTORE) if client_fstore.has_files(): installer._installation_cleanup = False raise ScriptError( "IPA client is already configured on this system.\n" "Please uninstall it before configuring the IPA server, " "using 'ipa-client-install --uninstall'") fstore = sysrestore.FileStore(SYSRESTORE_DIR_PATH) sstore = sysrestore.StateFile(SYSRESTORE_DIR_PATH) # This will override any settings passed in on the cmdline if os.path.isfile(paths.ROOT_IPA_CACHE): if options.dm_password is not None: dm_password = options.dm_password else: dm_password = read_password("Directory Manager", confirm=False) if dm_password is None: raise ScriptError("Directory Manager password required") try: cache_vars = read_cache(dm_password) options.__dict__.update(cache_vars) if cache_vars.get('external_ca', False): options.external_ca = False options.interactive = False except Exception as e: raise ScriptError("Cannot process the cache file: %s" % str(e)) # We only set up the CA if the PKCS#12 options are not given. if options.dirsrv_cert_files: setup_ca = False else: setup_ca = True options.setup_ca = setup_ca if not setup_ca and options.ca_subject: raise ScriptError( "--ca-subject cannot be used with CA-less installation") if not setup_ca and options.subject_base: raise ScriptError( "--subject-base cannot be used with CA-less installation") if not setup_ca and options.setup_kra: raise ScriptError( "--setup-kra cannot be used with CA-less installation") print("=======================================" "=======================================") print("This program will set up the FreeIPA Server.") print("") print("This includes:") if setup_ca: print(" * Configure a stand-alone CA (dogtag) for certificate " "management") if not options.no_ntp: print(" * Configure the Network Time Daemon (ntpd)") print(" * Create and configure an instance of Directory Server") print(" * Create and configure a Kerberos Key Distribution Center (KDC)") print(" * Configure Apache (httpd)") if options.setup_kra: print(" * Configure KRA (dogtag) for secret management") if options.setup_dns: print(" * Configure DNS (bind)") if options.setup_adtrust: print(" * Configure Samba (smb) and winbind for managing AD trusts") if not options.no_pkinit: print(" * Configure the KDC to enable PKINIT") if options.no_ntp: print("") print("Excluded by options:") print(" * Configure the Network Time Daemon (ntpd)") if installer.interactive: print("") print("To accept the default shown in brackets, press the Enter key.") print("") if not options.external_cert_files: # Make sure the 389-ds ports are available check_dirsrv(not installer.interactive) if not options.no_ntp: try: ipaclient.install.ntpconf.check_timedate_services() except ipaclient.install.ntpconf.NTPConflictingService as e: print(("WARNING: conflicting time&date synchronization service '%s'" " will be disabled" % e.conflicting_service)) print("in favor of ntpd") print("") except ipaclient.install.ntpconf.NTPConfigurationError: pass # Check to see if httpd is already configured to listen on 443 if httpinstance.httpd_443_configured(): raise ScriptError("Aborting installation") if not options.setup_dns and installer.interactive: if ipautil.user_input("Do you want to configure integrated DNS " "(BIND)?", False): options.setup_dns = True print("") # check bind packages are installed if options.setup_dns: # Don't require an external DNS to say who we are if we are # setting up a local DNS server. options.no_host_dns = True # check the hostname is correctly configured, it must be as the kldap # utilities just use the hostname as returned by getaddrinfo to set # up some of the standard entries if options.host_name: host_default = options.host_name else: host_default = get_fqdn() try: if not installer.interactive or options.host_name: verify_fqdn(host_default, options.no_host_dns) host_name = host_default else: host_name = read_host_name(host_default, options.no_host_dns) except BadHostError as e: raise ScriptError(e) host_name = host_name.lower() logger.debug("will use host_name: %s\n", host_name) if not options.domain_name: domain_name = read_domain_name(host_name[host_name.find(".")+1:], not installer.interactive) logger.debug("read domain_name: %s\n", domain_name) try: validate_domain_name(domain_name) except ValueError as e: raise ScriptError("Invalid domain name: %s" % unicode(e)) else: domain_name = options.domain_name domain_name = domain_name.lower() if not options.realm_name: realm_name = read_realm_name(domain_name, not installer.interactive) logger.debug("read realm_name: %s\n", realm_name) try: validate_domain_name(realm_name, entity="realm") except ValueError as e: raise ScriptError("Invalid realm name: {}".format(unicode(e))) else: realm_name = options.realm_name.upper() if not options.subject_base: options.subject_base = installutils.default_subject_base(realm_name) if not options.ca_subject: options.ca_subject = \ installutils.default_ca_subject_dn(options.subject_base) if options.http_cert_files: if options.http_pin is None: options.http_pin = installutils.read_password( "Enter Apache Server private key unlock", confirm=False, validate=False, retry=False) if options.http_pin is None: raise ScriptError( "Apache Server private key unlock password required") http_pkcs12_file, http_pin, http_ca_cert = load_pkcs12( cert_files=options.http_cert_files, key_password=options.http_pin, key_nickname=options.http_cert_name, ca_cert_files=options.ca_cert_files, host_name=host_name) http_pkcs12_info = (http_pkcs12_file.name, http_pin) if options.dirsrv_cert_files: if options.dirsrv_pin is None: options.dirsrv_pin = read_password( "Enter Directory Server private key unlock", confirm=False, validate=False, retry=False) if options.dirsrv_pin is None: raise ScriptError( "Directory Server private key unlock password required") dirsrv_pkcs12_file, dirsrv_pin, dirsrv_ca_cert = load_pkcs12( cert_files=options.dirsrv_cert_files, key_password=options.dirsrv_pin, key_nickname=options.dirsrv_cert_name, ca_cert_files=options.ca_cert_files, host_name=host_name) dirsrv_pkcs12_info = (dirsrv_pkcs12_file.name, dirsrv_pin) if options.pkinit_cert_files: if options.pkinit_pin is None: options.pkinit_pin = read_password( "Enter Kerberos KDC private key unlock", confirm=False, validate=False, retry=False) if options.pkinit_pin is None: raise ScriptError( "Kerberos KDC private key unlock password required") pkinit_pkcs12_file, pkinit_pin, pkinit_ca_cert = load_pkcs12( cert_files=options.pkinit_cert_files, key_password=options.pkinit_pin, key_nickname=options.pkinit_cert_name, ca_cert_files=options.ca_cert_files, realm_name=realm_name) pkinit_pkcs12_info = (pkinit_pkcs12_file.name, pkinit_pin) if (options.http_cert_files and options.dirsrv_cert_files and http_ca_cert != dirsrv_ca_cert): raise ScriptError( "Apache Server SSL certificate and Directory Server SSL " "certificate are not signed by the same CA certificate") if (options.http_cert_files and options.pkinit_cert_files and http_ca_cert != pkinit_ca_cert): raise ScriptError( "Apache Server SSL certificate and PKINIT KDC " "certificate are not signed by the same CA certificate") if not options.dm_password: dm_password = read_dm_password() if dm_password is None: raise ScriptError("Directory Manager password required") else: dm_password = options.dm_password if not options.master_password: master_password = ipa_generate_password() else: master_password = options.master_password if not options.admin_password: admin_password = read_admin_password() if admin_password is None: raise ScriptError("IPA admin password required") else: admin_password = options.admin_password # Configuration for ipalib, we will bootstrap and finalize later, after # we are sure we have the configuration file ready. cfg = dict( context='installer', confdir=paths.ETC_IPA, in_server=True, # make sure host name specified by user is used instead of default host=host_name, ) if setup_ca: # we have an IPA-integrated CA cfg['ca_host'] = host_name # Create the management framework config file and finalize api target_fname = paths.IPA_DEFAULT_CONF fd = open(target_fname, "w") fd.write("[global]\n") fd.write("host=%s\n" % host_name) fd.write("basedn=%s\n" % ipautil.realm_to_suffix(realm_name)) fd.write("realm=%s\n" % realm_name) fd.write("domain=%s\n" % domain_name) fd.write("xmlrpc_uri=https://%s/ipa/xml\n" % format_netloc(host_name)) fd.write("ldap_uri=ldapi://%%2fvar%%2frun%%2fslapd-%s.socket\n" % installutils.realm_to_serverid(realm_name)) if setup_ca: fd.write("enable_ra=True\n") fd.write("ra_plugin=dogtag\n") fd.write("dogtag_version=10\n") else: fd.write("enable_ra=False\n") fd.write("ra_plugin=none\n") fd.write("mode=production\n") fd.close() # Must be readable for everyone os.chmod(target_fname, 0o644) api.bootstrap(**cfg) api.finalize() if setup_ca: ca.install_check(False, None, options) if options.setup_kra: kra.install_check(api, None, options) if options.setup_dns: dns.install_check(False, api, False, options, host_name) ip_addresses = dns.ip_addresses else: ip_addresses = get_server_ip_address(host_name, not installer.interactive, False, options.ip_addresses) # check addresses here, dns module is doing own check no_matching_interface_for_ip_address_warning(ip_addresses) instance_name = "-".join(realm_name.split(".")) dirsrv = services.knownservices.dirsrv if (options.external_cert_files and dirsrv.is_installed(instance_name) and not dirsrv.is_running(instance_name)): logger.debug('Starting Directory Server') services.knownservices.dirsrv.start(instance_name) if options.setup_adtrust: adtrust.install_check(False, options, api) # installer needs to update hosts file when DNS subsystem will be # installed or custom addresses are used if options.ip_addresses or options.setup_dns: installer._update_hosts_file = True print() print("The IPA Master Server will be configured with:") print("Hostname: %s" % host_name) print("IP address(es): %s" % ", ".join(str(ip) for ip in ip_addresses)) print("Domain name: %s" % domain_name) print("Realm name: %s" % realm_name) print() if setup_ca: ca.print_ca_configuration(options) print() if options.setup_dns: print("BIND DNS server will be configured to serve IPA domain with:") print("Forwarders: %s" % ( "No forwarders" if not options.forwarders else ", ".join([str(ip) for ip in options.forwarders]) )) print('Forward policy: %s' % options.forward_policy) print("Reverse zone(s): %s" % ( "No reverse zone" if options.no_reverse or not dns.reverse_zones else ", ".join(str(rz) for rz in dns.reverse_zones) )) print() if not options.setup_adtrust: # If domain name and realm does not match, IPA server will not be able # to establish trust with Active Directory. Print big fat warning. realm_not_matching_domain = (domain_name.upper() != realm_name) if realm_not_matching_domain: print("WARNING: Realm name does not match the domain name.\n" "You will not be able to establish trusts with Active " "Directory unless\nthe realm name of the IPA server matches " "its domain name.\n\n") if installer.interactive and not user_input( "Continue to configure the system with these values?", False): raise ScriptError("Installation aborted") options.realm_name = realm_name options.domain_name = domain_name options.dm_password = dm_password options.master_password = master_password options.admin_password = admin_password options._host_name_overridden = bool(options.host_name) options.host_name = host_name options.ip_addresses = ip_addresses installer._fstore = fstore installer._sstore = sstore installer._dirsrv_pkcs12_file = dirsrv_pkcs12_file installer._http_pkcs12_file = http_pkcs12_file installer._pkinit_pkcs12_file = pkinit_pkcs12_file installer._dirsrv_pkcs12_info = dirsrv_pkcs12_info installer._http_pkcs12_info = http_pkcs12_info installer._pkinit_pkcs12_info = pkinit_pkcs12_info installer._external_cert_file = external_cert_file installer._external_ca_file = external_ca_file installer._ca_cert = http_ca_cert @common_cleanup def install(installer): options = installer fstore = installer._fstore sstore = installer._sstore dirsrv_pkcs12_info = installer._dirsrv_pkcs12_info http_pkcs12_info = installer._http_pkcs12_info pkinit_pkcs12_info = installer._pkinit_pkcs12_info http_ca_cert = installer._ca_cert realm_name = options.realm_name domain_name = options.domain_name dm_password = options.dm_password master_password = options.master_password admin_password = options.admin_password host_name = options.host_name ip_addresses = options.ip_addresses setup_ca = options.setup_ca # Installation has started. No IPA sysrestore items are restored in case of # failure to enable root cause investigation installer._installation_cleanup = False if installer.interactive: print("") print("The following operations may take some minutes to complete.") print("Please wait until the prompt is returned.") print("") # set hostname (transient and static) if user instructed us to do so if options._host_name_overridden: tasks.backup_hostname(fstore, sstore) tasks.set_hostname(host_name) if installer._update_hosts_file: update_hosts_file(ip_addresses, host_name, fstore) # Create a directory server instance if not options.external_cert_files: # Configure ntpd if not options.no_ntp: ipaclient.install.ntpconf.force_ntpd(sstore) ntp = ntpinstance.NTPInstance(fstore) if not ntp.is_configured(): ntp.create_instance() if options.dirsrv_cert_files: ds = dsinstance.DsInstance(fstore=fstore, domainlevel=options.domainlevel, config_ldif=options.dirsrv_config_file) installer._ds = ds ds.create_instance(realm_name, host_name, domain_name, dm_password, dirsrv_pkcs12_info, idstart=options.idstart, idmax=options.idmax, subject_base=options.subject_base, ca_subject=options.ca_subject, hbac_allow=not options.no_hbac_allow, setup_pkinit=not options.no_pkinit) else: ds = dsinstance.DsInstance(fstore=fstore, domainlevel=options.domainlevel, config_ldif=options.dirsrv_config_file) installer._ds = ds ds.create_instance(realm_name, host_name, domain_name, dm_password, idstart=options.idstart, idmax=options.idmax, subject_base=options.subject_base, ca_subject=options.ca_subject, hbac_allow=not options.no_hbac_allow, setup_pkinit=not options.no_pkinit) ntpinstance.ntp_ldap_enable(host_name, ds.suffix, realm_name) else: api.Backend.ldap2.connect() ds = dsinstance.DsInstance(fstore=fstore, domainlevel=options.domainlevel) installer._ds = ds ds.init_info( realm_name, host_name, domain_name, dm_password, options.subject_base, options.ca_subject, 1101, 1100, None, setup_pkinit=not options.no_pkinit) krb = krbinstance.KrbInstance(fstore) if not options.external_cert_files: krb.create_instance(realm_name, host_name, domain_name, dm_password, master_password, setup_pkinit=not options.no_pkinit, pkcs12_info=pkinit_pkcs12_info, subject_base=options.subject_base) else: krb.init_info(realm_name, host_name, setup_pkinit=not options.no_pkinit, subject_base=options.subject_base) if setup_ca: if not options.external_cert_files and options.external_ca: # stage 1 of external CA installation options.realm_name = realm_name options.domain_name = domain_name options.master_password = master_password options.dm_password = dm_password options.admin_password = admin_password options.host_name = host_name options.reverse_zones = dns.reverse_zones cache_vars = {n: options.__dict__[n] for o, n in installer.knobs() if n in options.__dict__} write_cache(cache_vars) ca.install_step_0(False, None, options) else: # Put the CA cert where other instances expect it x509.write_certificate(http_ca_cert, paths.IPA_CA_CRT) os.chmod(paths.IPA_CA_CRT, 0o444) if not options.no_pkinit: x509.write_certificate(http_ca_cert, paths.KDC_CA_BUNDLE_PEM) else: with open(paths.KDC_CA_BUNDLE_PEM, 'w'): pass os.chmod(paths.KDC_CA_BUNDLE_PEM, 0o444) x509.write_certificate(http_ca_cert, paths.CA_BUNDLE_PEM) os.chmod(paths.CA_BUNDLE_PEM, 0o444) # we now need to enable ssl on the ds ds.enable_ssl() if setup_ca: ca.install_step_1(False, None, options) otpd = otpdinstance.OtpdInstance() otpd.create_instance('OTPD', host_name, ipautil.realm_to_suffix(realm_name)) custodia = custodiainstance.CustodiaInstance(host_name, realm_name) custodia.create_instance() # Create a HTTP instance http = httpinstance.HTTPInstance(fstore) if options.http_cert_files: http.create_instance( realm_name, host_name, domain_name, dm_password, pkcs12_info=http_pkcs12_info, subject_base=options.subject_base, auto_redirect=not options.no_ui_redirect, ca_is_configured=setup_ca) else: http.create_instance( realm_name, host_name, domain_name, dm_password, subject_base=options.subject_base, auto_redirect=not options.no_ui_redirect, ca_is_configured=setup_ca) tasks.restore_context(paths.CACHE_IPA_SESSIONS) ca.set_subject_base_in_config(options.subject_base) # configure PKINIT now that all required services are in place krb.enable_ssl() # Apply any LDAP updates. Needs to be done after the configuration file # is created. DS is restarted in the process. service.print_msg("Applying LDAP updates") ds.apply_updates() # Restart krb after configurations have been changed service.print_msg("Restarting the KDC") krb.restart() if options.setup_kra: kra.install(api, None, options) if options.setup_dns: dns.install(False, False, options) else: # Create a BIND instance bind = bindinstance.BindInstance(fstore) bind.setup(host_name, ip_addresses, realm_name, domain_name, (), 'first', (), zonemgr=options.zonemgr, no_dnssec_validation=options.no_dnssec_validation) bind.create_file_with_system_records() if options.setup_adtrust: adtrust.install(False, options, fstore, api) # Set the admin user kerberos password ds.change_admin_password(admin_password) # Call client install script service.print_msg("Configuring client side components") try: args = [paths.IPA_CLIENT_INSTALL, "--on-master", "--unattended", "--domain", domain_name, "--server", host_name, "--realm", realm_name, "--hostname", host_name] if options.no_dns_sshfp: args.append("--no-dns-sshfp") if options.ssh_trust_dns: args.append("--ssh-trust-dns") if options.no_ssh: args.append("--no-ssh") if options.no_sshd: args.append("--no-sshd") if options.mkhomedir: args.append("--mkhomedir") run(args, redirect_output=True) print() except Exception: raise ScriptError("Configuration of client side components failed!") # Everything installed properly, activate ipa service. services.knownservices.ipa.enable() print("=======================================" "=======================================") print("Setup complete") print("") print("Next steps:") print("\t1. You must make sure these network ports are open:") print("\t\tTCP Ports:") print("\t\t * 80, 443: HTTP/HTTPS") print("\t\t * 389, 636: LDAP/LDAPS") print("\t\t * 88, 464: kerberos") if options.setup_dns: print("\t\t * 53: bind") print("\t\tUDP Ports:") print("\t\t * 88, 464: kerberos") if options.setup_dns: print("\t\t * 53: bind") if not options.no_ntp: print("\t\t * 123: ntp") print("") print("\t2. You can now obtain a kerberos ticket using the command: " "'kinit admin'") print("\t This ticket will allow you to use the IPA tools (e.g., ipa " "user-add)") print("\t and the web user interface.") if not services.knownservices.ntpd.is_running(): print("\t3. Kerberos requires time synchronization between clients") print("\t and servers for correct operation. You should consider " "enabling ntpd.") print("") if setup_ca: print(("Be sure to back up the CA certificates stored in " + paths.CACERT_P12)) print("These files are required to create replicas. The password for " "these") print("files is the Directory Manager password") if os.path.isfile(paths.ROOT_IPA_CACHE): os.remove(paths.ROOT_IPA_CACHE) @common_cleanup def uninstall_check(installer): options = installer tasks.check_selinux_status() installer._installation_cleanup = False if not is_ipa_configured(): print("WARNING:\nIPA server is not configured on this system. " "If you want to install the\nIPA server, please install " "it using 'ipa-server-install'.") fstore = sysrestore.FileStore(SYSRESTORE_DIR_PATH) sstore = sysrestore.StateFile(SYSRESTORE_DIR_PATH) # Configuration for ipalib, we will bootstrap and finalize later, after # we are sure we have the configuration file ready. cfg = dict( context='installer', confdir=paths.ETC_IPA, in_server=True, ) # We will need at least api.env, finalize api now. This system is # already installed, so the configuration file is there. api.bootstrap(**cfg) api.finalize() if installer.interactive: print("\nThis is a NON REVERSIBLE operation and will delete all data " "and configuration!\nIt is highly recommended to take a backup of " "existing data and configuration using ipa-backup utility " "before proceeding.\n") if not user_input("Are you sure you want to continue with the " "uninstall procedure?", False): raise ScriptError("Aborting uninstall operation.") try: api.Backend.ldap2.connect(autobind=True) domain_level = dsinstance.get_domain_level(api) except Exception: msg = ("\nWARNING: Failed to connect to Directory Server to find " "information about replication agreements. Uninstallation " "will continue despite the possible existing replication " "agreements.\n\n" "If this server is the last instance of CA, KRA, or DNSSEC " "master, uninstallation may result in data loss.\n\n" ) print(textwrap.fill(msg, width=80, replace_whitespace=False)) if (installer.interactive and not user_input( "Are you sure you want to continue with the uninstall " "procedure?", False)): raise ScriptError("Aborting uninstall operation.") else: dns.uninstall_check(options) if domain_level == DOMAIN_LEVEL_0: rm = replication.ReplicationManager( realm=api.env.realm, hostname=api.env.host, dirman_passwd=None, conn=api.Backend.ldap2 ) agreements = rm.find_ipa_replication_agreements() if agreements: other_masters = [a.get('cn')[0][4:] for a in agreements] msg = ( "\nReplication agreements with the following IPA masters " "found: %s. Removing any replication agreements before " "uninstalling the server is strongly recommended. You can " "remove replication agreements by running the following " "command on any other IPA master:\n" % ", ".join( other_masters) ) cmd = "$ ipa-replica-manage del %s\n" % api.env.host print(textwrap.fill(msg, width=80, replace_whitespace=False)) print(cmd) if (installer.interactive and not user_input("Are you sure you want to continue with" " the uninstall procedure?", False)): raise ScriptError("Aborting uninstall operation.") else: remove_master_from_managed_topology(api, options) api.Backend.ldap2.disconnect() installer._fstore = fstore installer._sstore = sstore @common_cleanup def uninstall(installer): fstore = installer._fstore sstore = installer._sstore rv = 0 print("Shutting down all IPA services") try: services.knownservices.ipa.stop() except Exception: # Fallback to direct ipactl stop only if system command fails try: run([paths.IPACTL, "stop"], raiseonerr=False) except Exception: pass ntpinstance.NTPInstance(fstore).uninstall() kra.uninstall() ca.uninstall() dns.uninstall() httpinstance.HTTPInstance(fstore).uninstall() krbinstance.KrbInstance(fstore).uninstall() dsinstance.DsInstance(fstore=fstore).uninstall() if _server_trust_ad_installed: adtrustinstance.ADTRUSTInstance(fstore).uninstall() custodiainstance.CustodiaInstance().uninstall() otpdinstance.OtpdInstance().uninstall() tasks.restore_hostname(fstore, sstore) fstore.restore_all_files() try: os.remove(paths.ROOT_IPA_CACHE) except Exception: pass try: os.remove(paths.ROOT_IPA_CSR) except Exception: pass # ipa-client-install removes /etc/ipa/default.conf sstore._load() ipaclient.install.ntpconf.restore_forced_ntpd(sstore) # Clean up group_exists (unused since IPA 2.2, not being set since 4.1) sstore.restore_state("install", "group_exists") services.knownservices.ipa.disable() # remove upgrade state file sysupgrade.remove_upgrade_file() if fstore.has_files(): logger.error('Some files have not been restored, see ' '%s/sysrestore.index', SYSRESTORE_DIR_PATH) has_state = False for module in IPA_MODULES: # from installutils if sstore.has_state(module): logger.error('Some installation state for %s has not been ' 'restored, see %s/sysrestore.state', module, SYSRESTORE_DIR_PATH) has_state = True rv = 1 if has_state: logger.error('Some installation state has not been restored.\n' 'This may cause re-installation to fail.\n' 'It should be safe to remove %s/sysrestore.state ' 'but it may\n' 'mean your system hasn\'t be restored to its ' 'pre-installation state.', SYSRESTORE_DIR_PATH) # Note that this name will be wrong after the first uninstall. dirname = dsinstance.config_dirname( installutils.realm_to_serverid(api.env.realm)) dirs = [dirname, paths.PKI_TOMCAT_ALIAS_DIR, paths.HTTPD_ALIAS_DIR] ids = certmonger.check_state(dirs) if ids: logger.error('Some certificates may still be tracked by ' 'certmonger.\n' 'This will cause re-installation to fail.\n' 'Start the certmonger service and list the ' 'certificates being tracked\n' ' # getcert list\n' 'These may be untracked by executing\n' ' # getcert stop-tracking -i <request_id>\n' 'for each id in: %s', ', '.join(ids)) # Remove the cert renewal lock file try: os.remove(paths.IPA_RENEWAL_LOCK) except OSError as e: if e.errno != errno.ENOENT: logger.warning("Failed to remove file %s: %s", paths.IPA_RENEWAL_LOCK, e) print("Removing IPA client configuration") try: result = run([paths.IPA_CLIENT_INSTALL, "--on-master", "--unattended", "--uninstall"], raiseonerr=False, redirect_output=True) if result.returncode not in [0, 2]: raise RuntimeError("Failed to configure the client") except Exception: rv = 1 print("Uninstall of client side components failed!") sys.exit(rv) def init(installer): installer.unattended = not installer.interactive installer.domainlevel = installer.domain_level installer._installation_cleanup = True installer._ds = None installer._dirsrv_pkcs12_file = None installer._http_pkcs12_file = None installer._pkinit_pkcs12_file = None installer._dirsrv_pkcs12_info = None installer._http_pkcs12_info = None installer._pkinit_pkcs12_info = None installer._external_cert_file = None installer._external_ca_file = None installer._ca_cert = None installer._update_hosts_file = False<|fim▁end|>
installutils.encrypt_file(fname,
<|file_name|>en.js<|end_file_name|><|fim▁begin|>/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'toolbar', 'en', { toolbarCollapse: 'Collapse Toolbar',<|fim▁hole|> document: 'Document', clipboard: 'Clipboard/Undo', editing: 'Editing', forms: 'Forms', basicstyles: 'Basic Styles', paragraph: 'Paragraph', links: 'Links', insert: 'Insert', styles: 'Styles', colors: 'Colors', tools: 'Tools' }, toolbars: 'Editor toolbars' } );<|fim▁end|>
toolbarExpand: 'Expand Toolbar', toolbarGroups: {
<|file_name|>types.ts<|end_file_name|><|fim▁begin|>/* * The MIT License (MIT) * * Copyright (c) 2020 Looker Data Sciences, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy<|fim▁hole|> * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import { MessageHandlerProps } from '../../App' export interface HomeSceneProps extends MessageHandlerProps { /** * Determines if the configure button should be visible or not. */ canConfigure: boolean }<|fim▁end|>
* of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell