prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>text.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/. */ //! Text layout. use layout::box::{RenderBox, RenderBoxBase, TextRenderBox, UnscannedTextRenderBoxClass}; use gfx::text::text_run::TextRun; use servo_util::range::Range; pub struct TextBoxData { run: @TextRun, range: Range, } impl TextBoxData { pub fn new(run: @TextRun, range: Range) -> TextBoxData { TextBoxData { run: run, range: range, } } } pub fn adapt_textbox_with_range(mut base: RenderBoxBase, run: @TextRun, range: Range) -> TextRenderBox { assert!(range.begin() < run.char_len()); assert!(range.end() <= run.char_len()); assert!(range.length() > 0); debug!("Creating textbox with span: (strlen=%u, off=%u, len=%u) of textrun: %s", run.char_len(), range.begin(), range.length(), run.text); let new_text_data = TextBoxData::new(run, range); let metrics = run.metrics_for_range(&range); base.position.size = metrics.bounding_box.size; TextRenderBox { base: base, text_data: new_text_data, } } pub trait UnscannedMethods { /// Copies out the text from an unscanned text box. Fails if this is not an unscanned text box. fn raw_text(&self) -> ~str;<|fim▁hole|> impl UnscannedMethods for RenderBox { fn raw_text(&self) -> ~str { match *self { UnscannedTextRenderBoxClass(text_box) => copy text_box.text, _ => fail!(~"unsupported operation: box.raw_text() on non-unscanned text box."), } } }<|fim▁end|>
}
<|file_name|>generator.py<|end_file_name|><|fim▁begin|>def is_tl(data): return isinstance(data, tuple) or isinstance(data, list) def get_depth(data): ''' :type data: list or tuple get the depth of nested list 'x' is 0 ['x', 'y'] is 1<|fim▁hole|> if is_tl(data): depths = [] for i in data: depths.append(1+get_depth(i)) return max(depths) else: return 0 def reduce_d2(a, b): ''' generate all combination from a, b ''' if not is_tl(a): a = [a] if not is_tl(b): b = [b] result = [] for i in a: for j in b: result.append('%s%s' % (i, j)) return result def _generate_d2(data): return reduce(reduce_d2, data) def _generate(data): ''' recursively generate the list ''' depth = get_depth(data) if depth > 2: temp = [] for i in data: temp.append(_generate(i)) return _generate(temp) elif depth == 2: return _generate_d2(data) elif depth == 1: return data else: return [str(data)] def generate(data): ''' :rtype: list of str :type data: list or tuple generate the final result ''' result = _generate(data) # fix if initial data's depth == 1 if result == data: result = _generate_d2(data) return result if __name__ == '__main__': nested = [range(2), [range(3), range(4)]] print(generate(nested)) print(generate([1, [2, 3]])) print(generate([1, 2])) print(generate(1))<|fim▁end|>
['x', ['y', 'z'] is 2 '''
<|file_name|>cuke.rs<|end_file_name|><|fim▁begin|>extern crate calculator; #[macro_use] extern crate cucumber; mod step_definitions; mod support; use step_definitions::{calculator_steps, display_steps};<|fim▁hole|> cucumber::create_config(CalculatorWorld::new()) .registrar_fn(&calculator_steps::register_steps) .registrar_fn(&display_steps::register_steps) .start(); }<|fim▁end|>
use support::env::CalculatorWorld; #[test] fn main() {
<|file_name|>express-ntlm-tests.ts<|end_file_name|><|fim▁begin|>import express = require('express'); import ntlm = require('express-ntlm');<|fim▁hole|>app.use(ntlm({ debug() { const args = Array.prototype.slice.apply(arguments); console.log.apply(null, args); }, domain: 'MYDOMAIN', domaincontroller: 'ldap://myad.example', // use different port (default: 389) // domaincontroller: 'ldap://myad.example:3899', })); app.all('*', (request, response) => { response.end(JSON.stringify(request.ntlm)); // {"DomainName":"MYDOMAIN","UserName":"MYUSER","Workstation":"MYWORKSTATION"} }); app.listen(80);<|fim▁end|>
const app = express();
<|file_name|>cli.rs<|end_file_name|><|fim▁begin|>use clap::{crate_version, App, AppSettings, Arg}; <|fim▁hole|> .version(crate_version!()) .author("Stuart Moss <[email protected]>") .setting(AppSettings::ArgRequiredElseHelp) .arg( Arg::with_name("mp4") .long("mp4") .short("a") .help("Use mp4 as the output container format") .conflicts_with("mkv") .takes_value(false), ) .arg( Arg::with_name("mkv") .long("mkv") .short("b") .help("Use mkv as the output container format") .conflicts_with("mp4") .takes_value(false), ) .arg( Arg::with_name("test") .required(false) .long("test") .short("t") .help("Test to see if conversion is required") .takes_value(false), ) .arg( Arg::with_name("file") .required(true) .index(1) .multiple(true) .takes_value(true) .help("The files to convert"), ) }<|fim▁end|>
pub fn build_cli() -> App<'static, 'static> { App::new("chromecastise")
<|file_name|>form-fileupload.js<|end_file_name|><|fim▁begin|>var FormFileUpload = function () { return { //main function to initiate the module init: function () { // Initialize the jQuery File Upload widget: $('#fileupload').fileupload({ disableImageResize: false, autoUpload: false, disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent), maxFileSize: 5000000, acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, // Uncomment the following to send cross-domain cookies: //xhrFields: {withCredentials: true}, }); // Enable iframe cross-domain access via redirect option: $('#fileupload').fileupload( 'option', 'redirect', window.location.href.replace( /\/[^\/]*$/, '/cors/result.html?%s' ) ); // Upload server status check for browsers with CORS support: if ($.support.cors) { $.ajax({ type: 'HEAD' <|fim▁hole|> .text('Upload server currently unavailable - ' + new Date()) .appendTo('#fileupload'); }); } // Load & display existing files: $('#fileupload').addClass('fileupload-processing'); $.ajax({ // Uncomment the following to send cross-domain cookies: //xhrFields: {withCredentials: true}, url: $('#fileupload').fileupload('option', 'url'), dataType: 'json', context: $('#fileupload')[0] }).always(function () { $(this).removeClass('fileupload-processing'); }).done(function (result) { $(this).fileupload('option', 'done') .call(this, $.Event('done'), {result: result}); }); } }; }();<|fim▁end|>
}).fail(function () { $('<div class="alert alert-danger"/>')
<|file_name|>serial_link.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (C) 2011-2014 Swift Navigation Inc. # Contact: Fergus Noble <[email protected]> # # This source is subject to the license found in the file 'LICENSE' which must # be be distributed together with this source. All other rights reserved. # # THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, # EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. import re import struct import threading import time import sys import sbp_piksi as ids import cPickle as pickle import calendar import socket DEFAULT_PORT = '/dev/ttyUSB0' DEFAULT_BAUD = 1000000 SBP_PREAMBLE = 0x55 crc16_tab = [ 0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7, 0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef, 0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6, 0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de, 0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485, 0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d, 0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4, 0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc, 0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823, 0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b, 0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12, 0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a, 0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41, 0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49, 0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70, 0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78, 0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f, 0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067, 0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e, 0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256, 0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d, 0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405, 0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c, 0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634, 0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab, 0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3, 0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a, 0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92, 0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9, 0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1, 0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8, 0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0 ] # CRC16 implementation acording to CCITT standards. def crc16(s, crc=0): for ch in s: crc = ((crc<<8)&0xFFFF) ^ crc16_tab[ ((crc>>8)&0xFF) ^ (ord(ch)&0xFF) ] crc &= 0xFFFF return crc class ListenerThread (threading.Thread): def __init__(self, link, print_unhandled=False): super(ListenerThread, self).__init__() self.link = link self.wants_to_stop = False self.print_unhandled = print_unhandled self.daemon = True def stop(self): self.wants_to_stop = True def run(self): while not self.wants_to_stop: try: sbp = self.link.get_message() mt, ms, md = sbp.msg_type, sbp.sender, sbp.payload # Will throw away last message here even if it is valid. if self.wants_to_stop: if self.link.ser: self.link.ser.close() break if mt is not None: for cb in self.link.get_global_callbacks(): cb(sbp) cbs = self.link.get_callback(mt) if cbs is None or len(cbs) == 0: if self.print_unhandled: print "Host Side Unhandled message %02X" % mt else: for cb in cbs: try: cb(md, sender=ms) except TypeError: cb(md) except (IOError, OSError): # Piksi was disconnected print "ERROR: Piksi disconnected!" return except: import traceback print traceback.format_exc() def list_ports(self=None): import serial.tools.list_ports ports = serial.tools.list_ports.comports() # Remove ports matching "ttyS*" (non-virtual serial ports on Linux). ports = filter(lambda x: x[1][0:4] != "ttyS", ports) if not any(ports): return None else: return ports class SerialLink: def __init__(self, port=DEFAULT_PORT, baud=DEFAULT_BAUD, use_ftdi=False, print_unhandled=False): self.print_unhandled = print_unhandled self.unhandled_bytes = 0 self.callbacks = {} self.global_callbacks = [] if use_ftdi: import pylibftdi self.ser = pylibftdi.Device() self.ser.baudrate = baud else: import serial try: self.ser = serial.Serial(port, baud, timeout=1) except serial.SerialException: print print "Serial device '%s' not found" % port print print "The following serial devices were detected:" print for p in list_ports(): p_name, p_desc, _ = p if p_desc == p_name: print "\t%s" % p_name else: print "\t%s (%s)" % (p_name, p_desc) sys.exit(1) # Delay then flush the buffer to make sure the receive buffer starts empty. time.sleep(0.5) self.ser.flush() self.lt = ListenerThread(self, print_unhandled) self.lt.start() def __del__(self): self.close() def close(self): try: self.lt.stop() while self.lt.isAlive(): time.sleep(0.1) except AttributeError: pass def get_message(self): while True: if self.lt.wants_to_stop: return ids.SBP(None, None, None, None, None) # Sync with magic start bytes magic = self.ser.read(1) if magic: if ord(magic) == SBP_PREAMBLE: break else: self.unhandled_bytes += 1 if self.print_unhandled: print "Host Side Unhandled byte : 0x%02x," % ord(magic), \ "total", \ self.unhandled_bytes hdr = "" while len(hdr) < 5: hdr = self.ser.read(5 - len(hdr)) msg_type, sender_id, msg_len = struct.unpack('<HHB', hdr) crc = crc16(hdr, 0) data = "" while len(data) < msg_len: data += self.ser.read(msg_len - len(data)) crc = crc16(data, crc) crc_received = "" while len(crc_received) < 2: crc_received = self.ser.read(2 - len(crc_received)) crc_received = struct.unpack('<H', crc_received)[0] if crc != crc_received: print "Host Side CRC mismatch: 0x%04X 0x%04X" % (crc, crc_received) return ids.SBP(None, None, None, None, None) return ids.SBP(msg_type, sender_id, msg_len, data, crc) def send_message(self, msg_type, msg, sender_id=0x42): framed_msg = struct.pack('<BHHB', SBP_PREAMBLE, msg_type, sender_id, len(msg)) framed_msg += msg crc = crc16(framed_msg[1:], 0) framed_msg += struct.pack('<H', crc) self.ser.write(framed_msg) def send_char(self, char): self.ser.write(char) def add_callback(self, msg_type, callback): """ Add a named callback for a specific SBP message type. """ try: self.callbacks[msg_type].append(callback) except KeyError: self.callbacks[msg_type] = [callback] def add_global_callback(self, callback): """ Add a global callback for all SBP messages. """ self.global_callbacks.append(callback) def rm_callback(self, msg_type, callback): try: self.callbacks[msg_type].remove(callback) except KeyError: print "Can't remove callback for msg 0x%04x: message not registered" \ % msg_type except ValueError: print "Can't remove callback for msg 0x%04x: callback not registered" \ % msg_type def get_callback(self, msg_type): """ Retrieve a named callback for a specific SBP message type. """ if msg_type in self.callbacks: return self.callbacks[msg_type] else: return None def get_global_callbacks(self): """ Retrieve a named callback for a specific SBP message type, or a global callback for all SBP messages. """ return self.global_callbacks def wait_message(self, msg_type, timeout=None): ev = threading.Event() d = {'data': None} def cb(data): d['data'] = data ev.set() self.add_callback(msg_type, cb) ev.wait(timeout) self.rm_callback(msg_type, cb) return d['data'] def default_print_callback(data): sys.stdout.write(data) def default_log_callback(handle): """ Callback for binary serializing Python objects to a file with a consistent logging format: (delta, timestamp, item) : tuple delta = msec reference timestamp (int) timestamp = current timestamp (int - UTC epoch) item = Python object to serialize Parameters ---------- handle : file An already-opened file handle Returns ---------- pickler : lambda data Function that will serialize Python object to open file_handle """ ref_time = time.time() protocol = 2 return lambda data: pickle.dump(format_log_entry(ref_time, data), handle, protocol) def generate_log_filename(): """ Generates a consistent filename for logging, for example: serial_link_log_20141125-140552.log Returns ---------- filename : str """ return time.strftime("serial_link_log_%Y%m%d-%H%M%S.log") def format_log_entry(t0, item): """ Generates a Python object with logging metadata.<|fim▁hole|> Parameters ---------- t0 : float Reference time (seconds) item : object Python object to serialize Returns ---------- (delta, timestamp, item) : tuple delta = msec reference timestamp (int) timestamp = current timestamp (int - UTC epoch) item = Python object to serialize """ timestamp = calendar.timegm(time.gmtime()) delta = int((time.time() - t0)*1000) return (delta, timestamp, item) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Swift Nav Serial Link.') parser.add_argument('-p', '--port', default=[DEFAULT_PORT], nargs=1, help='specify the serial port to use.') parser.add_argument("-b", "--baud", default=[DEFAULT_BAUD], nargs=1, help="specify the baud rate to use.") parser.add_argument("-v", "--verbose", help="print extra debugging information.", action="store_true") parser.add_argument("-f", "--ftdi", help="use pylibftdi instead of pyserial.", action="store_true") parser.add_argument("-l", "--log", action="store_true", help="serialize SBP messages to autogenerated log file.") parser.add_argument("-t", "--timeout", default=[None], nargs=1, help="exit after TIMEOUT seconds have elapsed.") parser.add_argument("-r", "--reset", action="store_true", help="reset device after connection.") args = parser.parse_args() serial_port = args.port[0] baud = args.baud[0] link = SerialLink(serial_port, baud, use_ftdi=args.ftdi, print_unhandled=args.verbose) link.add_callback(ids.PRINT, default_print_callback) # Setup logging log_file = None if args.log: log_name = generate_log_filename() log_file = open(log_name, 'w+') print "Logging at %s." % log_name link.add_global_callback(default_log_callback(log_file)) if args.reset: link.send_message(ids.RESET, '') try: if args.timeout[0] is None: # Wait forever until the user presses Ctrl-C while True: time.sleep(0.1) else: # Wait until the timeout has elapsed time.sleep(float(args.timeout[0])) except KeyboardInterrupt: pass finally: if log_file: log_file.close() link.close()<|fim▁end|>
<|file_name|>test_Endianess.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- #+---------------------------------------------------------------------------+ #| 01001110 01100101 01110100 01111010 01101111 01100010 | #| | #| Netzob : Inferring communication protocols | #+---------------------------------------------------------------------------+ #| Copyright (C) 2011 Georges Bossert and Frédéric Guihéry |<|fim▁hole|>#| 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/>. | #+---------------------------------------------------------------------------+ #| @url : http://www.netzob.org | #| @contact : [email protected] | #| @sponsors : Amossys, http://www.amossys.fr | #| Supélec, http://www.rennes.supelec.fr/ren/rd/cidre/ | #+---------------------------------------------------------------------------+ from netzob.Common.Type.Endianess import Endianess from common.NetzobTestCase import NetzobTestCase class test_Endianess(NetzobTestCase): def test_BIG(self): self.assertEqual(Endianess.BIG, "big-endian") def test_LITTLE(self): self.assertEqual(Endianess.LITTLE, "little-endian")<|fim▁end|>
#| This program is free software: you can redistribute it and/or modify |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from __future__ import print_function from __future__ import unicode_literals from django.contrib import admin from .models import Conference from .models import Paper from .models import Author from .models import Attachment from .actions import paper_actions class AttachInline(admin.TabularInline): model = Attachment class ConferenceAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("name",)} list_display = ('name', 'place', 'date') search_fields = ('name', 'place') date_hierarchy = 'date' class PaperAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("title",)} list_display = ('title', 'conference', 'status', 'pauthors', 'hasattach') list_filter = ('status', 'conference') search_fields = ('title', 'conference__name', 'conference__place', 'authors__first_name', 'authors__last_name', 'authors__email') filter_horizontal = ('authors', ) inlines = [AttachInline, ] <|fim▁hole|> return ', '.join(i.get_full_name() for i in obj.authors.all()) pauthors.short_description = 'Authors' def hasattach(self, obj): return obj.attachs.exists() hasattach.short_description = 'Attach?' hasattach.boolean = True class AuthorAdmin(admin.ModelAdmin): list_display = ('email', 'first_name', 'last_name') search_fields = ('email', 'first_name', 'last_name') class AttachmentAdmin(admin.ModelAdmin): list_display = ('attach', 'paper', 'uploaded') admin.site.register(Conference, ConferenceAdmin) admin.site.register(Paper, PaperAdmin) admin.site.register(Author, AuthorAdmin) admin.site.register(Attachment, AttachmentAdmin)<|fim▁end|>
actions = paper_actions def pauthors(self, obj):
<|file_name|>base.py<|end_file_name|><|fim▁begin|>import pyactiveresource.connection from pyactiveresource.activeresource import ActiveResource, ResourceMeta, formats import shopify.yamlobjects import shopify.mixins as mixins import shopify import threading import sys from six.moves import urllib import six from shopify.collection import PaginatedCollection from pyactiveresource.collection import Collection # Store the response from the last request in the connection object class ShopifyConnection(pyactiveresource.connection.Connection): response = None def __init__(self, site, user=None, password=None, timeout=None, format=formats.JSONFormat): super(ShopifyConnection, self).__init__(site, user, password, timeout, format) def _open(self, *args, **kwargs): self.response = None try: self.response = super(ShopifyConnection, self)._open(*args, **kwargs) except pyactiveresource.connection.ConnectionError as err: self.response = err.response raise return self.response # Inherit from pyactiveresource's metaclass in order to use ShopifyConnection class ShopifyResourceMeta(ResourceMeta): @property def connection(cls): """HTTP connection for the current thread""" local = cls._threadlocal if not getattr(local, "connection", None): # Make sure these variables are no longer affected by other threads. local.user = cls.user local.password = cls.password local.site = cls.site local.timeout = cls.timeout local.headers = cls.headers local.format = cls.format local.version = cls.version local.url = cls.url if cls.site is None: raise ValueError("No shopify session is active") local.connection = ShopifyConnection(cls.site, cls.user, cls.password, cls.timeout, cls.format) return local.connection def get_user(cls): return getattr(cls._threadlocal, "user", ShopifyResource._user) def set_user(cls, value): cls._threadlocal.connection = None ShopifyResource._user = cls._threadlocal.user = value user = property(get_user, set_user, None, "The username for HTTP Basic Auth.") def get_password(cls): return getattr(cls._threadlocal, "password", ShopifyResource._password) def set_password(cls, value): cls._threadlocal.connection = None ShopifyResource._password = cls._threadlocal.password = value password = property(get_password, set_password, None, "The password for HTTP Basic Auth.") def get_site(cls): return getattr(cls._threadlocal, "site", ShopifyResource._site) def set_site(cls, value): cls._threadlocal.connection = None ShopifyResource._site = cls._threadlocal.site = value if value is not None: parts = urllib.parse.urlparse(value) host = parts.hostname if parts.port: host += ":" + str(parts.port) new_site = urllib.parse.urlunparse((parts.scheme, host, parts.path, "", "", "")) ShopifyResource._site = cls._threadlocal.site = new_site if parts.username: cls.user = urllib.parse.unquote(parts.username) if parts.password: cls.password = urllib.parse.unquote(parts.password) site = property(get_site, set_site, None, "The base REST site to connect to.") def get_timeout(cls): return getattr(cls._threadlocal, "timeout", ShopifyResource._timeout) def set_timeout(cls, value): cls._threadlocal.connection = None ShopifyResource._timeout = cls._threadlocal.timeout = value timeout = property(get_timeout, set_timeout, None, "Socket timeout for HTTP requests") <|fim▁hole|> return cls._threadlocal.headers def set_headers(cls, value): cls._threadlocal.headers = value headers = property(get_headers, set_headers, None, "The headers sent with HTTP requests") def get_format(cls): return getattr(cls._threadlocal, "format", ShopifyResource._format) def set_format(cls, value): cls._threadlocal.connection = None ShopifyResource._format = cls._threadlocal.format = value format = property(get_format, set_format, None, "Encoding used for request and responses") def get_prefix_source(cls): """Return the prefix source, by default derived from site.""" try: return cls.override_prefix() except AttributeError: if hasattr(cls, "_prefix_source"): return cls.site + cls._prefix_source else: return cls.site def set_prefix_source(cls, value): """Set the prefix source, which will be rendered into the prefix.""" cls._prefix_source = value prefix_source = property(get_prefix_source, set_prefix_source, None, "prefix for lookups for this type of object.") def get_version(cls): if hasattr(cls._threadlocal, "version") or ShopifyResource._version: return getattr(cls._threadlocal, "version", ShopifyResource._version) elif ShopifyResource._site is not None: return ShopifyResource._site.split("/")[-1] def set_version(cls, value): ShopifyResource._version = cls._threadlocal.version = value version = property(get_version, set_version, None, "Shopify Api Version") def get_url(cls): return getattr(cls._threadlocal, "url", ShopifyResource._url) def set_url(cls, value): ShopifyResource._url = cls._threadlocal.url = value url = property(get_url, set_url, None, "Base URL including protocol and shopify domain") @six.add_metaclass(ShopifyResourceMeta) class ShopifyResource(ActiveResource, mixins.Countable): _format = formats.JSONFormat _threadlocal = threading.local() _headers = {"User-Agent": "ShopifyPythonAPI/%s Python/%s" % (shopify.VERSION, sys.version.split(" ", 1)[0])} _version = None _url = None def __init__(self, attributes=None, prefix_options=None): if attributes is not None and prefix_options is None: prefix_options, attributes = self.__class__._split_options(attributes) return super(ShopifyResource, self).__init__(attributes, prefix_options) def is_new(self): return not self.id def _load_attributes_from_response(self, response): if response.body.strip(): self._update(self.__class__.format.decode(response.body)) @classmethod def activate_session(cls, session): cls.site = session.site cls.url = session.url cls.user = None cls.password = None cls.version = session.api_version.name cls.headers["X-Shopify-Access-Token"] = session.token @classmethod def clear_session(cls): cls.site = None cls.url = None cls.user = None cls.password = None cls.version = None cls.headers.pop("X-Shopify-Access-Token", None) @classmethod def find(cls, id_=None, from_=None, **kwargs): """Checks the resulting collection for pagination metadata.""" collection = super(ShopifyResource, cls).find(id_=id_, from_=from_, **kwargs) if isinstance(collection, Collection) and "headers" in collection.metadata: return PaginatedCollection(collection, metadata={"resource_class": cls}, **kwargs) return collection<|fim▁end|>
def get_headers(cls): if not hasattr(cls._threadlocal, "headers"): cls._threadlocal.headers = ShopifyResource._headers.copy()
<|file_name|>parse.go<|end_file_name|><|fim▁begin|>// Package json is a JSON parser following the specifications at http://json.org/. package json // import "github.com/tdewolff/parse/json" import ( "io" "strconv" "github.com/tdewolff/parse" "github.com/tdewolff/parse/buffer" ) // GrammarType determines the type of grammar type GrammarType uint32 <|fim▁hole|> LiteralGrammar NumberGrammar StringGrammar StartObjectGrammar // { EndObjectGrammar // } StartArrayGrammar // [ EndArrayGrammar // ] ) // String returns the string representation of a GrammarType. func (gt GrammarType) String() string { switch gt { case ErrorGrammar: return "Error" case WhitespaceGrammar: return "Whitespace" case LiteralGrammar: return "Literal" case NumberGrammar: return "Number" case StringGrammar: return "String" case StartObjectGrammar: return "StartObject" case EndObjectGrammar: return "EndObject" case StartArrayGrammar: return "StartArray" case EndArrayGrammar: return "EndArray" } return "Invalid(" + strconv.Itoa(int(gt)) + ")" } //////////////////////////////////////////////////////////////// // State determines the current state the parser is in. type State uint32 // State values. const ( ValueState State = iota // extra token when errors occur ObjectKeyState ObjectValueState ArrayState ) // String returns the string representation of a State. func (state State) String() string { switch state { case ValueState: return "Value" case ObjectKeyState: return "ObjectKey" case ObjectValueState: return "ObjectValue" case ArrayState: return "Array" } return "Invalid(" + strconv.Itoa(int(state)) + ")" } //////////////////////////////////////////////////////////////// // Parser is the state for the lexer. type Parser struct { r *buffer.Lexer state []State err error needComma bool } // NewParser returns a new Parser for a given io.Reader. func NewParser(r io.Reader) *Parser { return &Parser{ r: buffer.NewLexer(r), state: []State{ValueState}, } } // Err returns the error encountered during tokenization, this is often io.EOF but also other errors can be returned. func (p *Parser) Err() error { if p.err != nil { return p.err } return p.r.Err() } // Restore restores the NULL byte at the end of the buffer. func (p *Parser) Restore() { p.r.Restore() } // Next returns the next Grammar. It returns ErrorGrammar when an error was encountered. Using Err() one can retrieve the error message. func (p *Parser) Next() (GrammarType, []byte) { p.moveWhitespace() c := p.r.Peek(0) state := p.state[len(p.state)-1] if c == ',' { if state != ArrayState && state != ObjectKeyState { p.err = parse.NewErrorLexer("unexpected comma character outside an array or object", p.r) return ErrorGrammar, nil } p.r.Move(1) p.moveWhitespace() p.needComma = false c = p.r.Peek(0) } p.r.Skip() if p.needComma && c != '}' && c != ']' && c != 0 { p.err = parse.NewErrorLexer("expected comma character or an array or object ending", p.r) return ErrorGrammar, nil } else if c == '{' { p.state = append(p.state, ObjectKeyState) p.r.Move(1) return StartObjectGrammar, p.r.Shift() } else if c == '}' { if state != ObjectKeyState { p.err = parse.NewErrorLexer("unexpected right brace character", p.r) return ErrorGrammar, nil } p.needComma = true p.state = p.state[:len(p.state)-1] if p.state[len(p.state)-1] == ObjectValueState { p.state[len(p.state)-1] = ObjectKeyState } p.r.Move(1) return EndObjectGrammar, p.r.Shift() } else if c == '[' { p.state = append(p.state, ArrayState) p.r.Move(1) return StartArrayGrammar, p.r.Shift() } else if c == ']' { p.needComma = true if state != ArrayState { p.err = parse.NewErrorLexer("unexpected right bracket character", p.r) return ErrorGrammar, nil } p.state = p.state[:len(p.state)-1] if p.state[len(p.state)-1] == ObjectValueState { p.state[len(p.state)-1] = ObjectKeyState } p.r.Move(1) return EndArrayGrammar, p.r.Shift() } else if state == ObjectKeyState { if c != '"' || !p.consumeStringToken() { p.err = parse.NewErrorLexer("expected object key to be a quoted string", p.r) return ErrorGrammar, nil } n := p.r.Pos() p.moveWhitespace() if c := p.r.Peek(0); c != ':' { p.err = parse.NewErrorLexer("expected colon character after object key", p.r) return ErrorGrammar, nil } p.r.Move(1) p.state[len(p.state)-1] = ObjectValueState return StringGrammar, p.r.Shift()[:n] } else { p.needComma = true if state == ObjectValueState { p.state[len(p.state)-1] = ObjectKeyState } if c == '"' && p.consumeStringToken() { return StringGrammar, p.r.Shift() } else if p.consumeNumberToken() { return NumberGrammar, p.r.Shift() } else if p.consumeLiteralToken() { return LiteralGrammar, p.r.Shift() } } return ErrorGrammar, nil } // State returns the state the parser is currently in (ie. which token is expected). func (p *Parser) State() State { return p.state[len(p.state)-1] } //////////////////////////////////////////////////////////////// /* The following functions follow the specifications at http://json.org/ */ func (p *Parser) moveWhitespace() { for { if c := p.r.Peek(0); c != ' ' && c != '\n' && c != '\r' && c != '\t' { break } p.r.Move(1) } } func (p *Parser) consumeLiteralToken() bool { c := p.r.Peek(0) if c == 't' && p.r.Peek(1) == 'r' && p.r.Peek(2) == 'u' && p.r.Peek(3) == 'e' { p.r.Move(4) return true } else if c == 'f' && p.r.Peek(1) == 'a' && p.r.Peek(2) == 'l' && p.r.Peek(3) == 's' && p.r.Peek(4) == 'e' { p.r.Move(5) return true } else if c == 'n' && p.r.Peek(1) == 'u' && p.r.Peek(2) == 'l' && p.r.Peek(3) == 'l' { p.r.Move(4) return true } return false } func (p *Parser) consumeNumberToken() bool { mark := p.r.Pos() if p.r.Peek(0) == '-' { p.r.Move(1) } c := p.r.Peek(0) if c >= '1' && c <= '9' { p.r.Move(1) for { if c := p.r.Peek(0); c < '0' || c > '9' { break } p.r.Move(1) } } else if c != '0' { p.r.Rewind(mark) return false } else { p.r.Move(1) // 0 } if c := p.r.Peek(0); c == '.' { p.r.Move(1) if c := p.r.Peek(0); c < '0' || c > '9' { p.r.Move(-1) return true } for { if c := p.r.Peek(0); c < '0' || c > '9' { break } p.r.Move(1) } } mark = p.r.Pos() if c := p.r.Peek(0); c == 'e' || c == 'E' { p.r.Move(1) if c := p.r.Peek(0); c == '+' || c == '-' { p.r.Move(1) } if c := p.r.Peek(0); c < '0' || c > '9' { p.r.Rewind(mark) return true } for { if c := p.r.Peek(0); c < '0' || c > '9' { break } p.r.Move(1) } } return true } func (p *Parser) consumeStringToken() bool { // assume to be on " p.r.Move(1) for { c := p.r.Peek(0) if c == '"' { escaped := false for i := p.r.Pos() - 1; i >= 0; i-- { if p.r.Lexeme()[i] == '\\' { escaped = !escaped } else { break } } if !escaped { p.r.Move(1) break } } else if c == 0 { return false } p.r.Move(1) } return true }<|fim▁end|>
// GrammarType values. const ( ErrorGrammar GrammarType = iota // extra grammar when errors occur WhitespaceGrammar
<|file_name|>L0.ts<|end_file_name|><|fim▁begin|>import fs = require('fs'); import assert = require('assert'); import path = require('path'); <|fim▁hole|>describe('AzureIoTEdgeV2 Suite', function () { before(() => { }); after(() => { }); it('Does a basic hello world test', function(done: MochaDone) { // TODO - add real tests done(); }); });<|fim▁end|>
<|file_name|>LBiObjLongPredicate.java<|end_file_name|><|fim▁begin|>/* * This file is part of "lunisolar-magma". * * (C) Copyright 2014-2022 Lunisolar (http://lunisolar.eu/). * * 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 eu.lunisolar.magma.func.predicate; import javax.annotation.Nonnull; // NOSONAR import javax.annotation.Nullable; // NOSONAR import javax.annotation.concurrent.NotThreadSafe; // NOSONAR import java.util.Comparator; // NOSONAR import java.util.Objects; // NOSONAR import eu.lunisolar.magma.basics.*; //NOSONAR import eu.lunisolar.magma.basics.builder.*; // NOSONAR import eu.lunisolar.magma.basics.exceptions.*; // NOSONAR import eu.lunisolar.magma.basics.meta.*; // NOSONAR import eu.lunisolar.magma.basics.meta.aType.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR import eu.lunisolar.magma.func.IA; import eu.lunisolar.magma.func.SA; import eu.lunisolar.magma.func.*; // NOSONAR import eu.lunisolar.magma.func.tuple.*; // NOSONAR import java.util.concurrent.*; // NOSONAR import java.util.function.*; // NOSONAR import java.util.*; // NOSONAR import java.lang.reflect.*; // NOSONAR import eu.lunisolar.magma.func.action.*; // NOSONAR import eu.lunisolar.magma.func.consumer.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR import eu.lunisolar.magma.func.function.*; // NOSONAR import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR import eu.lunisolar.magma.func.function.from.*; // NOSONAR import eu.lunisolar.magma.func.function.to.*; // NOSONAR import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR import eu.lunisolar.magma.func.predicate.*; // NOSONAR import eu.lunisolar.magma.func.supplier.*; // NOSONAR /** * Non-throwing functional interface (lambda) LBiObjLongPredicate for Java 8. * * Type: predicate * * Domain (lvl: 3): T1 a1,T2 a2,long a3 * * Co-domain: boolean * */ @FunctionalInterface @SuppressWarnings("UnusedDeclaration") public interface LBiObjLongPredicate<T1, T2> extends MetaPredicate, MetaInterface.NonThrowing, Codomain<aBool>, Domain3<a<T1>, a<T2>, aLong> { // NOSONAR String DESCRIPTION = "LBiObjLongPredicate: boolean test(T1 a1,T2 a2,long a3)"; // boolean test(T1 a1,T2 a2,long a3) ; default boolean test(T1 a1, T2 a2, long a3) { // return nestingTest(a1,a2,a3); try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call test(T1 a1,T2 a2,long a3) */ boolean testX(T1 a1, T2 a2, long a3) throws Throwable; default boolean tupleTest(LBiObjLongTriple<T1, T2> args) { return test(args.first(), args.second(), args.third()); } /** Function call that handles exceptions according to the instructions. */ default boolean handlingTest(T1 a1, T2 a2, long a3, HandlingInstructions<Throwable, RuntimeException> handling) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handler.handleOrNest(e, handling); } } default LBiObjLongPredicate<T1, T2> handling(HandlingInstructions<Throwable, RuntimeException> handling) { return (a1, a2, a3) -> handlingTest(a1, a2, a3, handling); } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage); } } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage, param1); } } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage, param1, param2); } } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage, param1, param2, param3); } } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage); } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage, param1); } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage, param1, param1); } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage, param1, param2, param3); } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWF<RuntimeException> factory) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory); } } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWF<RuntimeException> factory) { return (a1, a2, a3) -> test(a1, a2, a3, factory); } default boolean testThen(T1 a1, T2 a2, long a3, @Nonnull LPredicate<Throwable> handler) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR Handling.handleErrors(e); return handler.test(e); } } default LBiObjLongPredicate<T1, T2> tryingThen(@Nonnull LPredicate<Throwable> handler) { return (a1, a2, a3) -> testThen(a1, a2, a3, handler); } /** Function call that handles exceptions by always nesting checked exceptions and propagating the others as is. */ default boolean nestingTest(T1 a1, T2 a2, long a3) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** Function call that handles exceptions by always propagating them as is, even when they are undeclared checked ones. */ default boolean shovingTest(T1 a1, T2 a2, long a3) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.shoveIt(e); } } static <T1, T2> boolean shovingTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.shovingTest(a1, a2, a3); } static <T1, T2> boolean handlingTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, HandlingInstructions<Throwable, RuntimeException> handling) { // <- Null.nonNullArg(func, "func"); return func.handlingTest(a1, a2, a3, handling); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.nestingTest(a1, a2, a3); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage, param1); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage, param1, param2); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage, param1, param2, param3); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWF<RuntimeException> factory) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory); } static <T1, T2> boolean tryTestThen(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull LPredicate<Throwable> handler) { Null.nonNullArg(func, "func"); return func.testThen(a1, a2, a3, handler); } default boolean failSafeTest(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<T1, T2> failSafe) { try { return test(a1, a2, a3); } catch (Throwable e) { // NOSONAR Handling.handleErrors(e); return failSafe.test(a1, a2, a3); } } static <T1, T2> boolean failSafeTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull LBiObjLongPredicate<T1, T2> failSafe) { Null.nonNullArg(failSafe, "failSafe"); if (func == null) { return failSafe.test(a1, a2, a3); } else { return func.failSafeTest(a1, a2, a3, failSafe); } } static <T1, T2> LBiObjLongPredicate<T1, T2> failSafe(LBiObjLongPredicate<T1, T2> func, @Nonnull LBiObjLongPredicate<T1, T2> failSafe) { Null.nonNullArg(failSafe, "failSafe"); return (a1, a2, a3) -> failSafeTest(a1, a2, a3, func, failSafe); } default boolean doIf(T1 a1, T2 a2, long a3, LAction action) { Null.nonNullArg(action, "action"); if (test(a1, a2, a3)) { action.execute(); return true; } else { return false; } } static <T1, T2> boolean doIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<T1, T2> predicate, @Nonnull LAction action) { Null.nonNullArg(predicate, "predicate"); return predicate.doIf(a1, a2, a3, action); } static <T1, T2> boolean doIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<T1, T2> predicate, @Nonnull LBiObjLongConsumer<? super T1, ? super T2> consumer) { Null.nonNullArg(predicate, "predicate"); return predicate.doIf(a1, a2, a3, consumer); } default boolean doIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongConsumer<? super T1, ? super T2> consumer) { Null.nonNullArg(consumer, "consumer"); if (test(a1, a2, a3)) { consumer.accept(a1, a2, a3); return true; } else { return false; } } /** Just to mirror the method: Ensures the result is not null */ default boolean nonNullTest(T1 a1, T2 a2, long a3) { return test(a1, a2, a3); } /** For convenience, where "test()" makes things more confusing than "applyAsBoolean()". */ default boolean doApplyAsBoolean(T1 a1, T2 a2, long a3) { return test(a1, a2, a3); } <|fim▁hole|> } /** From-To. Intended to be used with non-capturing lambda. */ public static <T1, T2> void fromTo(long min_a3, long max_a3, T1 a1, T2 a2, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); if (min_a3 <= max_a3) { for (long a3 = min_a3; a3 <= max_a3; a3++) { func.test(a1, a2, a3); } } else { for (long a3 = min_a3; a3 >= max_a3; a3--) { func.test(a1, a2, a3); } } } /** From-To. Intended to be used with non-capturing lambda. */ public static <T1, T2> void fromTill(long min_a3, long max_a3, T1 a1, T2 a2, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); if (min_a3 <= max_a3) { for (long a3 = min_a3; a3 < max_a3; a3++) { func.test(a1, a2, a3); } } else { for (long a3 = min_a3; a3 > max_a3; a3--) { func.test(a1, a2, a3); } } } /** From-To. Intended to be used with non-capturing lambda. */ public static <T1, T2> void times(long max_a3, T1 a1, T2 a2, @Nonnull LBiObjLongPredicate<T1, T2> func) { if (max_a3 < 0) return; fromTill(0, max_a3, a1, a2, func); } /** Extract and apply function. */ public static <M, K, V, T2> boolean from(@Nonnull M container, LBiFunction<M, K, V> extractor, K key, T2 a2, long a3, @Nonnull LBiObjLongPredicate<V, T2> function) { Null.nonNullArg(container, "container"); Null.nonNullArg(function, "function"); V value = extractor.apply(container, key); if (value != null) { return function.test(value, a2, a3); } return false; } default LObjLongPredicate<T2> lShrink(@Nonnull LObjLongFunction<T2, T1> left) { Null.nonNullArg(left, "left"); return (a2, a3) -> test(left.apply(a2, a3), a2, a3); } default LObjLongPredicate<T2> lShrink_(T1 a1) { return (a2, a3) -> test(a1, a2, a3); } public static <T2, T1> LObjLongPredicate<T2> lShrunken(@Nonnull LObjLongFunction<T2, T1> left, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(left, "left"); Null.nonNullArg(func, "func"); return func.lShrink(left); } public static <T2, T1> LObjLongPredicate<T2> lShrunken_(T1 a1, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.lShrink_(a1); } default LBiPredicate<T1, T2> rShrink(@Nonnull LToLongBiFunction<T1, T2> right) { Null.nonNullArg(right, "right"); return (a1, a2) -> test(a1, a2, right.applyAsLong(a1, a2)); } default LBiPredicate<T1, T2> rShrink_(long a3) { return (a1, a2) -> test(a1, a2, a3); } public static <T1, T2> LBiPredicate<T1, T2> rShrunken(@Nonnull LToLongBiFunction<T1, T2> right, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(right, "right"); Null.nonNullArg(func, "func"); return func.rShrink(right); } public static <T1, T2> LBiPredicate<T1, T2> rShrunken_(long a3, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.rShrink_(a3); } /** */ public static <T1, T2> LBiObjLongPredicate<T1, T2> uncurry(@Nonnull LFunction<T1, LFunction<T2, LLongPredicate>> func) { Null.nonNullArg(func, "func"); return (T1 a1, T2 a2, long a3) -> func.apply(a1).apply(a2).test(a3); } /** Cast that removes generics. */ default LBiObjLongPredicate untyped() { return this; } /** Cast that replace generics. */ default <V2, V3> LBiObjLongPredicate<V2, V3> cast() { return untyped(); } /** Cast that replace generics. */ public static <V2, V3> LBiObjLongPredicate<V2, V3> cast(LBiObjLongPredicate<?, ?> function) { return (LBiObjLongPredicate) function; } /** Change function to consumer that ignores output. */ default LBiObjLongConsumer<T1, T2> toConsumer() { return this::test; } /** Calls domain consumer before main function. */ default LBiObjLongPredicate<T1, T2> beforeDo(@Nonnull LBiObjLongConsumer<T1, T2> before) { Null.nonNullArg(before, "before"); return (T1 a1, T2 a2, long a3) -> { before.accept(a1, a2, a3); return test(a1, a2, a3); }; } /** Calls codomain consumer after main function. */ default LBiObjLongPredicate<T1, T2> afterDo(@Nonnull LBoolConsumer after) { Null.nonNullArg(after, "after"); return (T1 a1, T2 a2, long a3) -> { final boolean retval = test(a1, a2, a3); after.accept(retval); return retval; }; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (!pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (!pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(msg, a1, a2, a3) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2, param3) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(msg, a1, a2, a3) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2, param3) + ' ' + m); } return a1; } /** Captures arguments but delays the evaluation. */ default LBoolSupplier capture(T1 a1, T2 a2, long a3) { return () -> this.test(a1, a2, a3); } /** Creates function that always returns the same value. */ static <T1, T2> LBiObjLongPredicate<T1, T2> constant(boolean r) { return (a1, a2, a3) -> r; } /** Captures single parameter function into this interface where only 1st parameter will be used. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> test1st(@Nonnull LPredicate<T1> func) { return (a1, a2, a3) -> func.test(a1); } /** Captures single parameter function into this interface where only 2nd parameter will be used. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> test2nd(@Nonnull LPredicate<T2> func) { return (a1, a2, a3) -> func.test(a2); } /** Captures single parameter function into this interface where only 3rd parameter will be used. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> test3rd(@Nonnull LLongPredicate func) { return (a1, a2, a3) -> func.test(a3); } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPred(final @Nonnull LBiObjLongPredicate<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** A completely inconvenient method in case lambda expression and generic arguments are ambiguous for the compiler. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPred(@Nullable Class<T1> c1, @Nullable Class<T2> c2, final @Nonnull LBiObjLongPredicate<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } final class S<T1, T2> implements LBiObjLongPredicate<T1, T2> { private LBiObjLongPredicate<T1, T2> target = null; @Override public boolean testX(T1 a1, T2 a2, long a3) throws Throwable { return target.testX(a1, a2, a3); } } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> recursive(final @Nonnull LFunction<LBiObjLongPredicate<T1, T2>, LBiObjLongPredicate<T1, T2>> selfLambda) { final S<T1, T2> single = new S(); LBiObjLongPredicate<T1, T2> func = selfLambda.apply(single); single.target = func; return func; } public static <T1, T2> M<T1, T2> mementoOf(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> function) { var initialValue = function.test(a1, a2, a3); return initializedMementoOf(initialValue, function); } public static <T1, T2> M<T1, T2> initializedMementoOf(boolean initialValue, LBiObjLongPredicate<T1, T2> function) { return memento(initialValue, initialValue, function, (m, x1, x2) -> x2); } public static <T1, T2> M<T1, T2> deltaOf(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> function, LLogicalBinaryOperator deltaFunction) { var initialValue = function.test(a1, a2, a3); return initializedDeltaOf(initialValue, function, deltaFunction); } public static <T1, T2> M<T1, T2> deltaOf(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> function) { var initialValue = function.test(a1, a2, a3); return initializedDeltaOf(initialValue, function, (x1, x2) -> x1 != x2); } public static <T1, T2> M<T1, T2> initializedDeltaOf(boolean initialValue, LBiObjLongPredicate<T1, T2> function, LLogicalBinaryOperator deltaFunction) { return memento(initialValue, deltaFunction.apply(initialValue, initialValue), function, (m, x1, x2) -> deltaFunction.apply(x1, x2)); } public static <T1, T2> M<T1, T2> memento(boolean initialBaseValue, boolean initialValue, LBiObjLongPredicate<T1, T2> baseFunction, LLogicalTernaryOperator mementoFunction) { return new M(initialBaseValue, initialValue, baseFunction, mementoFunction); } /** * Implementation that allows to create derivative functions (do not confuse it with math concepts). Very short name is intended to be used with parent (LBiObjLongPredicate.M) */ @NotThreadSafe final class M<T1, T2> implements LBiObjLongPredicate<T1, T2> { private final LBiObjLongPredicate<T1, T2> baseFunction; private boolean lastBaseValue; private boolean lastValue; private final LLogicalTernaryOperator mementoFunction; private M(boolean lastBaseValue, boolean lastValue, LBiObjLongPredicate<T1, T2> baseFunction, LLogicalTernaryOperator mementoFunction) { this.baseFunction = baseFunction; this.lastBaseValue = lastBaseValue; this.lastValue = lastValue; this.mementoFunction = mementoFunction; } @Override public boolean testX(T1 a1, T2 a2, long a3) throws Throwable { boolean x1 = lastBaseValue; boolean x2 = lastBaseValue = baseFunction.testX(a1, a2, a3); return lastValue = mementoFunction.apply(lastValue, x1, x2); } public boolean lastValue() { return lastValue; }; public boolean lastBaseValue() { return lastBaseValue; }; } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPredThrowing(final @Nonnull ExF<Throwable> exF) { Null.nonNullArg(exF, "exF"); return (a1, a2, a3) -> { throw exF.produce(); }; } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPredThrowing(final String message, final @Nonnull ExMF<Throwable> exF) { Null.nonNullArg(exF, "exF"); return (a1, a2, a3) -> { throw exF.produce(message); }; } // <editor-fold desc="wrap variants"> /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T1, T2> LBiObjLongPredicate.LObj0Long2Obj1Pred<T1, T2> obj0Long2Obj1Pred(final @Nonnull LBiObjLongPredicate.LObj0Long2Obj1Pred<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T2, T1> LBiObjLongPredicate.LObj1Obj0Long2Pred<T2, T1> obj1Obj0Long2Pred(final @Nonnull LBiObjLongPredicate.LObj1Obj0Long2Pred<T2, T1> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T2, T1> LBiObjLongPredicate.LObj1Long2Obj0Pred<T2, T1> obj1Long2Obj0Pred(final @Nonnull LBiObjLongPredicate.LObj1Long2Obj0Pred<T2, T1> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T1, T2> LBiObjLongPredicate.LLong2Obj0Obj1Pred<T1, T2> long2Obj0Obj1Pred(final @Nonnull LBiObjLongPredicate.LLong2Obj0Obj1Pred<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T2, T1> LBiObjLongPredicate.LLong2Obj1Obj0Pred<T2, T1> long2Obj1Obj0Pred(final @Nonnull LBiObjLongPredicate.LLong2Obj1Obj0Pred<T2, T1> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } // </editor-fold> static <T1, T2> boolean call(T1 a1, T2 a2, long a3, final @Nonnull LBiObjLongPredicate<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda.test(a1, a2, a3); } // <editor-fold desc="wrap"> // </editor-fold> // <editor-fold desc="predicate"> /** * Returns a predicate that represents the logical negation of this predicate. * * @see {@link java.util.function.Predicate#negate} */ @Nonnull default LBiObjLongPredicate<T1, T2> negate() { return (a1, a2, a3) -> !test(a1, a2, a3); } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> not(@Nonnull LBiObjLongPredicate<T1, T2> pred) { Null.nonNullArg(pred, "pred"); return pred.negate(); } /** * Returns a predicate that represents the logical AND of evaluation of this predicate and the argument one. * @see {@link java.util.function.Predicate#and()} */ @Nonnull default LBiObjLongPredicate<T1, T2> and(@Nonnull LBiObjLongPredicate<? super T1, ? super T2> other) { Null.nonNullArg(other, "other"); return (a1, a2, a3) -> test(a1, a2, a3) && other.test(a1, a2, a3); } @Nonnull public static <T1, T2> LBiObjLongPredicate<T1, T2> and(@Nonnull LBiObjLongPredicate<? super T1, ? super T2>... predicates) { Null.nonNullArg(predicates, "predicates"); return (a1, a2, a3) -> { for (LBiObjLongPredicate<? super T1, ? super T2> p : predicates) { if (!p.test(a1, a2, a3)) { return false; } } return true; }; } /** * Returns a predicate that represents the logical OR of evaluation of this predicate and the argument one. * @see {@link java.util.function.Predicate#or} */ @Nonnull default LBiObjLongPredicate<T1, T2> or(@Nonnull LBiObjLongPredicate<? super T1, ? super T2> other) { Null.nonNullArg(other, "other"); return (a1, a2, a3) -> test(a1, a2, a3) || other.test(a1, a2, a3); } @Nonnull public static <T1, T2> LBiObjLongPredicate<T1, T2> or(@Nonnull LBiObjLongPredicate<? super T1, ? super T2>... predicates) { Null.nonNullArg(predicates, "predicates"); return (a1, a2, a3) -> { for (LBiObjLongPredicate<? super T1, ? super T2> p : predicates) { if (p.test(a1, a2, a3)) { return true; } } return false; }; } /** * Returns a predicate that represents the logical XOR of evaluation of this predicate and the argument one. * @see {@link java.util.function.Predicate#or} */ @Nonnull default LBiObjLongPredicate<T1, T2> xor(@Nonnull LBiObjLongPredicate<? super T1, ? super T2> other) { Null.nonNullArg(other, "other"); return (a1, a2, a3) -> test(a1, a2, a3) ^ other.test(a1, a2, a3); } /** * Creates predicate that evaluates if an object is equal with the argument one. * @see {@link java.util.function.Predicate#isEqual() */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> isEqual(T1 v1, T2 v2, long v3) { return (a1, a2, a3) -> (a1 == null ? v1 == null : a1.equals(v1)) && (a2 == null ? v2 == null : a2.equals(v2)) && (a3 == v3); } // </editor-fold> // <editor-fold desc="compose (functional)"> /** Allows to manipulate the domain of the function. */ @Nonnull default <V1, V2> LBiObjLongPredicate<V1, V2> compose(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LLongUnaryOperator before3) { Null.nonNullArg(before1, "before1"); Null.nonNullArg(before2, "before2"); Null.nonNullArg(before3, "before3"); return (v1, v2, v3) -> this.test(before1.apply(v1), before2.apply(v2), before3.applyAsLong(v3)); } public static <V1, V2, T1, T2> LBiObjLongPredicate<V1, V2> composed(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LLongUnaryOperator before3, LBiObjLongPredicate<T1, T2> after) { return after.compose(before1, before2, before3); } /** Allows to manipulate the domain of the function. */ @Nonnull default <V1, V2, V3> LTriPredicate<V1, V2, V3> biObjLongPredCompose(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LToLongFunction<? super V3> before3) { Null.nonNullArg(before1, "before1"); Null.nonNullArg(before2, "before2"); Null.nonNullArg(before3, "before3"); return (v1, v2, v3) -> this.test(before1.apply(v1), before2.apply(v2), before3.applyAsLong(v3)); } public static <V1, V2, V3, T1, T2> LTriPredicate<V1, V2, V3> composed(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LToLongFunction<? super V3> before3, LBiObjLongPredicate<T1, T2> after) { return after.biObjLongPredCompose(before1, before2, before3); } // </editor-fold> // <editor-fold desc="then (functional)"> /** Combines two functions together in a order. */ @Nonnull default <V> LBiObjLongFunction<T1, T2, V> boolToBiObjLongFunc(@Nonnull LBoolFunction<? extends V> after) { Null.nonNullArg(after, "after"); return (a1, a2, a3) -> after.apply(this.test(a1, a2, a3)); } /** Combines two functions together in a order. */ @Nonnull default LBiObjLongPredicate<T1, T2> boolToBiObjLongPred(@Nonnull LLogicalOperator after) { Null.nonNullArg(after, "after"); return (a1, a2, a3) -> after.apply(this.test(a1, a2, a3)); } // </editor-fold> // <editor-fold desc="variant conversions"> // </editor-fold> // <editor-fold desc="interface variants"> /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LObj0Long2Obj1Pred<T1, T2> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call test(T1 a1,T2 a2,long a3) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testObj0Long2Obj1(a1, a3, a2); } // boolean testObj0Long2Obj1(T1 a1,long a3,T2 a2) ; default boolean testObj0Long2Obj1(T1 a1, long a3, T2 a2) { // return nestingTestObj0Long2Obj1(a1,a3,a2); try { return this.testObj0Long2Obj1X(a1, a3, a2); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testObj0Long2Obj1(T1 a1,long a3,T2 a2) */ boolean testObj0Long2Obj1X(T1 a1, long a3, T2 a2) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LObj1Obj0Long2Pred<T2, T1> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testObj0Long2Obj1(T1 a1,long a3,T2 a2) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testObj1Obj0Long2(a2, a1, a3); } // boolean testObj1Obj0Long2(T2 a2,T1 a1,long a3) ; default boolean testObj1Obj0Long2(T2 a2, T1 a1, long a3) { // return nestingTestObj1Obj0Long2(a2,a1,a3); try { return this.testObj1Obj0Long2X(a2, a1, a3); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testObj1Obj0Long2(T2 a2,T1 a1,long a3) */ boolean testObj1Obj0Long2X(T2 a2, T1 a1, long a3) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LObj1Long2Obj0Pred<T2, T1> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testObj1Obj0Long2(T2 a2,T1 a1,long a3) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testObj1Long2Obj0(a2, a3, a1); } // boolean testObj1Long2Obj0(T2 a2,long a3,T1 a1) ; default boolean testObj1Long2Obj0(T2 a2, long a3, T1 a1) { // return nestingTestObj1Long2Obj0(a2,a3,a1); try { return this.testObj1Long2Obj0X(a2, a3, a1); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testObj1Long2Obj0(T2 a2,long a3,T1 a1) */ boolean testObj1Long2Obj0X(T2 a2, long a3, T1 a1) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LLong2Obj0Obj1Pred<T1, T2> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testObj1Long2Obj0(T2 a2,long a3,T1 a1) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testLong2Obj0Obj1(a3, a1, a2); } // boolean testLong2Obj0Obj1(long a3,T1 a1,T2 a2) ; default boolean testLong2Obj0Obj1(long a3, T1 a1, T2 a2) { // return nestingTestLong2Obj0Obj1(a3,a1,a2); try { return this.testLong2Obj0Obj1X(a3, a1, a2); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testLong2Obj0Obj1(long a3,T1 a1,T2 a2) */ boolean testLong2Obj0Obj1X(long a3, T1 a1, T2 a2) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LLong2Obj1Obj0Pred<T2, T1> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testLong2Obj0Obj1(long a3,T1 a1,T2 a2) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testLong2Obj1Obj0(a3, a2, a1); } // boolean testLong2Obj1Obj0(long a3,T2 a2,T1 a1) ; default boolean testLong2Obj1Obj0(long a3, T2 a2, T1 a1) { // return nestingTestLong2Obj1Obj0(a3,a2,a1); try { return this.testLong2Obj1Obj0X(a3, a2, a1); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testLong2Obj1Obj0(long a3,T2 a2,T1 a1) */ boolean testLong2Obj1Obj0X(long a3, T2 a2, T1 a1) throws Throwable; } // </editor-fold> // >>> LBiObjLongPredicate<T1,T2> /** Returns TRUE. */ public static <T1, T2> boolean alwaysTrue(T1 a1, T2 a2, long a3) { return true; } /** Returns FALSE. */ public static <T1, T2> boolean alwaysFalse(T1 a1, T2 a2, long a3) { return false; } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, C3> void filterForEach(IndexedRead<C1, a<T1>> ia1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); size = Integer.min(size, ia2.size(source2)); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); size = Integer.min(size, ia3.size(source3)); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; for (; i < size; i++) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = oiFunc2.apply(source2, i); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, I1, C2, C3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); int size = ia2.size(source2); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); size = Integer.min(size, ia3.size(source3)); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; while (testFunc1.test(iterator1) && i < size) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = oiFunc2.apply(source2, i); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, I2, C3> void filterIterate(IndexedRead<C1, a<T1>> ia1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); size = Integer.min(size, ia3.size(source3)); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; while (i < size && testFunc2.test(iterator2)) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = nextFunc2.apply(iterator2); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, I1, C2, I2, C3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); int size = ia3.size(source3); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; while (testFunc1.test(iterator1) && testFunc2.test(iterator2) && i < size) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = nextFunc2.apply(iterator2); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, C3, I3> void filterIterate(IndexedRead<C1, a<T1>> ia1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); size = Integer.min(size, ia2.size(source2)); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); int i = 0; while (i < size && testFunc3.test(iterator3)) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = oiFunc2.apply(source2, i); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, I1, C2, C3, I3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); int size = ia2.size(source2); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); int i = 0; while (testFunc1.test(iterator1) && i < size && testFunc3.test(iterator3)) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = oiFunc2.apply(source2, i); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, I2, C3, I3> void filterIterate(IndexedRead<C1, a<T1>> ia1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); int i = 0; while (i < size && testFunc2.test(iterator2) && testFunc3.test(iterator3)) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = nextFunc2.apply(iterator2); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method depends highly on the arguments. */ default <C1, I1, C2, I2, C3, I3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); while (testFunc1.test(iterator1) && testFunc2.test(iterator2) && testFunc3.test(iterator3)) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = nextFunc2.apply(iterator2); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); } } }<|fim▁end|>
/** Returns description of the functional interface. */ @Nonnull default String functionalInterfaceDescription() { return LBiObjLongPredicate.DESCRIPTION;
<|file_name|>TempDirectory.cpp<|end_file_name|><|fim▁begin|>/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ /* Sonic Visualiser An audio file viewer and annotation editor. Centre for Digital Music, Queen Mary, University of London. This file copyright 2006 Chris Cannam. 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. See the file COPYING included with this distribution for more information. */ #include "TempDirectory.h" #include "ResourceFinder.h" #include "system/System.h" #include "Exceptions.h" #include <QDir> #include <QFile> #include <QMutexLocker> #include <QSettings> #include <iostream> #include <cassert> #include <unistd.h> #include <time.h> TempDirectory * TempDirectory::m_instance = new TempDirectory; TempDirectory * TempDirectory::getInstance() { return m_instance; } TempDirectory::TempDirectory() : m_tmpdir("") { } TempDirectory::~TempDirectory() { cerr << "TempDirectory::~TempDirectory" << endl; cleanup(); } void TempDirectory::cleanup() { cleanupDirectory(""); } QString TempDirectory::getContainingPath() { QMutexLocker locker(&m_mutex); QSettings settings; settings.beginGroup("TempDirectory"); QString svDirParent = settings.value("create-in", "$HOME").toString(); settings.endGroup(); QString svDir = ResourceFinder().getUserResourcePrefix(); if (svDirParent != "$HOME") { //!!! iffy svDir.replace(QDir::home().absolutePath(), svDirParent); } if (!QFileInfo(svDir).exists()) { if (!QDir(svDirParent).mkpath(svDir)) { throw DirectoryCreationFailed(QString("%1 directory in %2") .arg(svDir).arg(svDirParent)); } } else if (!QFileInfo(svDir).isDir()) { throw DirectoryCreationFailed(QString("%1 is not a directory") .arg(svDir)); } cleanupAbandonedDirectories(svDir); return svDir; } QString TempDirectory::getPath() { if (m_tmpdir != "") return m_tmpdir; return createTempDirectoryIn(getContainingPath()); } QString TempDirectory::createTempDirectoryIn(QString dir) { // Entered with mutex held. QDir tempDirBase(dir); // Generate a temporary directory. Qt4.1 doesn't seem to be able // to do this for us, and mkdtemp is not standard. This method is // based on the way glibc does mkdtemp. static QString chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; QString suffix; int padlen = 6, attempts = 100; unsigned int r = (unsigned int)(time(0) ^ getpid()); for (int i = 0; i < padlen; ++i) { suffix += "X"; } for (int j = 0; j < attempts; ++j) { unsigned int v = r; for (int i = 0; i < padlen; ++i) { suffix[i] = chars[v % 62]; v /= 62; } QString candidate = QString("sv_%1").arg(suffix); if (tempDirBase.mkpath(candidate)) { m_tmpdir = tempDirBase.filePath(candidate); break; } r = r + 7777; } if (m_tmpdir == "") { throw DirectoryCreationFailed(QString("temporary subdirectory in %1") .arg(tempDirBase.canonicalPath())); } QString pidpath = QDir(m_tmpdir).filePath(QString("%1.pid").arg(getpid())); QFile pidfile(pidpath); if (!pidfile.open(QIODevice::WriteOnly)) { throw DirectoryCreationFailed(QString("pid file creation in %1") .arg(m_tmpdir)); } else { pidfile.close(); } return m_tmpdir; } QString TempDirectory::getSubDirectoryPath(QString subdir) { QString tmpdirpath = getPath(); QMutexLocker locker(&m_mutex); QDir tmpdir(tmpdirpath); QFileInfo fi(tmpdir.filePath(subdir)); if (!fi.exists()) { if (!tmpdir.mkdir(subdir)) { throw DirectoryCreationFailed(fi.filePath()); } else { return fi.filePath(); } } else if (fi.isDir()) { return fi.filePath(); } else { throw DirectoryCreationFailed(fi.filePath()); } } void TempDirectory::cleanupDirectory(QString tmpdir) { bool isRoot = false; if (tmpdir == "") { m_mutex.lock(); isRoot = true; tmpdir = m_tmpdir; if (tmpdir == "") { m_mutex.unlock(); return; } } QDir dir(tmpdir); dir.setFilter(QDir::Dirs | QDir::Files); for (unsigned int i = 0; i < dir.count(); ++i) { if (dir[i] == "." || dir[i] == "..") continue; QFileInfo fi(dir.filePath(dir[i])); if (fi.isDir()) { cleanupDirectory(fi.absoluteFilePath()); } else { if (!QFile(fi.absoluteFilePath()).remove()) {<|fim▁hole|> << "Failed to unlink file \"" << fi.absoluteFilePath() << "\"" << endl; } } } QString dirname = dir.dirName(); if (dirname != "") { if (!dir.cdUp()) { cerr << "WARNING: TempDirectory::cleanup: " << "Failed to cd to parent directory of " << tmpdir << endl; return; } if (!dir.rmdir(dirname)) { cerr << "WARNING: TempDirectory::cleanup: " << "Failed to remove directory " << dirname << endl; } } if (isRoot) { m_tmpdir = ""; m_mutex.unlock(); } } void TempDirectory::cleanupAbandonedDirectories(QString svDir) { QDir dir(svDir, "sv_*", QDir::Name, QDir::Dirs); for (unsigned int i = 0; i < dir.count(); ++i) { QString dirpath = dir.filePath(dir[i]); QDir subdir(dirpath, "*.pid", QDir::Name, QDir::Files); if (subdir.count() == 0) { cerr << "INFO: Found temporary directory with no .pid file in it!\n(directory=\"" << dirpath << "\"). Removing it..." << endl; cleanupDirectory(dirpath); cerr << "...done." << endl; continue; } for (unsigned int j = 0; j < subdir.count(); ++j) { bool ok = false; int pid = QFileInfo(subdir[j]).baseName().toInt(&ok); if (!ok) continue; if (GetProcessStatus(pid) == ProcessNotRunning) { cerr << "INFO: Found abandoned temporary directory from " << "a previous, defunct process\n(pid=" << pid << ", directory=\"" << dirpath << "\"). Removing it..." << endl; cleanupDirectory(dirpath); cerr << "...done." << endl; break; } } } }<|fim▁end|>
cerr << "WARNING: TempDirectory::cleanup: "
<|file_name|>cmdargs.py<|end_file_name|><|fim▁begin|><|fim▁hole|>import collections CmdArgs = collections.namedtuple('CmdArgs', ['split_channels', 'merge', 'image', 'prefix', 'list', 'layer'])<|fim▁end|>
<|file_name|>squareplot.py<|end_file_name|><|fim▁begin|># Simple plotter for Gut books. # All this does is draw a sqare for every stat in the input<|fim▁hole|># # Another fine example of how Viz lies to you. You will # need to fudge the range by adjusting the clipping. import numpy as np import matplotlib.pyplot as plt import sys as sys if len(sys.argv) <2: print "Need an input file with many rows of 'id score'\n" sys.exit(1) fname = sys.argv[1] vals = np.loadtxt(fname) ids = vals[:,0] score = vals[:,1] score_max = 400; #max(score) #score_max = max(score) score = np.clip(score, 10, score_max) score = score/score_max # want 3x1 ratio, so 3n*n= 30824 (max entries), horiz=3n=300 NUM_COLS=300 fig = plt.figure(figsize=(12,9)) ax = fig.add_subplot(111) ax.set_axis_bgcolor('0.50') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) for i in range(len(vals)): #print i, ids[i] row = int(ids[i]) / NUM_COLS col = int(ids[i]) % NUM_COLS cval = score[i] #score[i]*score[i] # Square the values to drop the lower end cmap = plt.get_cmap('hot') val = cmap(cval) ax.add_patch(plt.Rectangle((col,row),1,1,color=val)); #, cmap=plt.cm.autumn)) ax.set_aspect('equal') print cmap(0.1) print cmap(0.9) plt.xlim([0,NUM_COLS]) plt.ylim([0,1+int(max(ids))/NUM_COLS]) plt.show()<|fim▁end|>
# and color it based on the score.
<|file_name|>bibedit_templates.py<|end_file_name|><|fim▁begin|>## This file is part of Invenio. ## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2013 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. # pylint: disable=C0103 """BibEdit Templates.""" __revision__ = "$Id$" from invenio.config import CFG_SITE_URL from invenio.messages import gettext_set_language class Template: """BibEdit Templates Class.""" def __init__(self): """Initialize.""" pass def menu(self): """Create the menu.""" recordmenu = '<div class="bibEditMenuSectionHeader">\n' \ ' %(imgCompressMenuSection)sRecord\n' \ ' %(imgNewRecord)s\n' \ ' %(imgCloneRecord)s\n' \ ' %(imgTemplateRecord)s\n' \ ' </div>\n' \ ' <table>\n' \ ' <col width="28px">\n' \ ' <col width="40px">\n' \ ' <col width="40px">\n' \ ' <col width="28px">\n' \ ' <tr>\n' \ ' <td colspan="2">\n' \ ' <form onsubmit="return false;">\n' \ ' %(txtSearchPattern)s\n' \ ' </form>\n' \ ' <td colspan="2">%(sctSearchType)s</td>\n' \ ' </tr>\n' \ ' <tr>\n' \ ' <td colspan="4">%(btnSearch)s</td>\n' \ ' </tr>\n' \ ' <tr id="rowRecordBrowser" style="display: none">\n' \ ' <td>%(btnPrev)s</td>\n' \ ' <td colspan="2" id="cellRecordNo"\n' \ ' style="text-align: center">1/1</td>\n' \ ' <td>%(btnNext)s</td>\n' \ ' </tr>\n' \ ' <tr>\n' \ ' <td colspan="2">%(btnSubmit)s</td>\n' \ ' <td colspan="2">%(btnCancel)s</td>\n' \ ' </tr>\n' \<|fim▁hole|> ' <tr class="bibEditMenuMore">\n' \ ' <td>%(imgDeleteRecord)s</td>\n' \ ' <td colspan="3">%(btnDeleteRecord)s</td>\n' \ ' </tr>\n' \ ' <tr class="bibEditmenuMore">\n' \ ' <td>Switch to:</td>\n' \ ' <td colspan="3">%(btnSwitchReadOnly)s</td>\n' \ ' </tr>' \ ' </table>' % { 'imgCompressMenuSection': img('/img/bullet_toggle_minus.png', 'bibEditImgCompressMenuSection', id='ImgRecordMenu'), 'imgNewRecord': img('/img/table.png', 'bibEditImgCtrlEnabled', id='imgNewRecord', title='New record'), \ 'imgCloneRecord': img('/img/table_multiple.png', 'bibEditImgCtrlDisabled', id='imgCloneRecord', title='Clone record'), \ 'imgTemplateRecord': img('/img/page_edit.png', 'bibEditImgCtrlEnabled', id='imgTemplateRecord', title='Manage templates'), \ 'txtSearchPattern': inp('text', id='txtSearchPattern'), \ 'sctSearchType': '<select id="sctSearchType">\n' \ ' <option value="recID">Rec ID</option>\n' \ ' <option value="reportnumber">Rep No</option>\n' \ ' <option value="anywhere">Anywhere</option>\n' \ ' </select>', 'btnSearch': button('button', 'Search', 'bibEditBtnBold', id='btnSearch'), 'btnPrev': button('button', '&lt;', id='btnPrev', disabled='disabled'), 'btnNext': button('button', '&gt;', id='btnNext', disabled='disabled'), 'btnSubmit': button('button', 'Submit', 'bibEditBtnBold', id='btnSubmit', disabled='disabled'), 'btnCancel': button('button', 'Cancel', id='btnCancel', disabled='disabled'), 'imgDeleteRecord': img('/img/table_delete.png'), 'btnDeleteRecord': button('button', 'Delete', id='btnDeleteRecord', disabled='disabled'), 'btnSwitchReadOnly' : button('button', 'Read-only', id='btnSwitchReadOnly') } fieldmenu = '<div class="bibEditMenuSectionHeader">\n' \ ' %(imgCompressMenuSection)sFields\n' \ ' </div>\n' \ ' <table class="bibEditMenuMore">\n' \ ' <col width="28px">\n' \ ' <col>\n' \ ' <tr>\n' \ ' <td>%(imgAddField)s</td>\n' \ ' <td>%(btnAddField)s</td>\n' \ ' </tr>\n' \ ' <tr>\n' \ ' <td>%(imgDeleteSelected)s</td>\n' \ ' <td>%(btnDeleteSelected)s</td>\n' \ ' </tr>\n' \ ' </table>' % { 'imgCompressMenuSection': img('/img/bullet_toggle_minus.png', 'bibEditImgCompressMenuSection', id='ImgFieldMenu'), 'imgAddField': img('/img/table_row_insert.png'), 'btnAddField': button('button', 'Add', id='btnAddField', disabled='disabled'), 'imgDeleteSelected': img('/img/table_row_delete.png'), 'btnDeleteSelected': button('button', 'Delete selected', id='btnDeleteSelected', disabled='disabled')} viewmenu = '<div class="bibEditMenuSectionHeader">\n' \ ' %(imgCompressMenuSection)sView\n' \ ' </div>\n' \ ' <table>\n' \ ' <col width="68px">\n' \ ' <col width="68px">\n' \ ' <tr class="bibEditMenuMore">\n' \ ' <td>%(btnTagMARC)s</td>\n' \ ' <td>%(btnTagNames)s</td>\n' \ ' </tr>\n' \ ' </table>' % { 'imgCompressMenuSection': img('/img/bullet_toggle_minus.png', 'bibEditImgCompressMenuSection', id='ImgViewMenu'), 'btnTagMARC': button('button', 'MARC', id='btnMARCTags', disabled='disabled'), 'btnTagNames': button('button', 'Human', id='btnHumanTags', disabled='disabled') } historymenu = '<div class="bibEditMenuSectionHeader">\n' \ ' %(imgCompressMenuSection)sHistory\n' \ ' </div>\n' \ ' <div class="bibEditRevHistoryMenuSection">\n' \ ' <table>\n' \ ' <col width="136px">\n' \ ' <tr class="bibEditMenuMore">\n' \ ' <td id="bibEditRevisionsHistory"></td>'\ ' </tr>\n' \ ' </table>\n' \ ' </div>\n'% { 'imgCompressMenuSection': img('/img/bullet_toggle_minus.png', 'bibEditImgCompressMenuSection', id='ImgHistoryMenu') } undoredosection = '<div class="bibEditMenuSectionHeader">\n' \ ' %(imgCompressMenuSection)sUndo/Redo\n' \ ' </div>\n<table>' \ ' <tr class="bibEditMenuMore"><td>' \ ' <div class="bibEditURMenuSection">\n' \ ' <div class="bibEditURDetailsSection" id="bibEditURUndoListLayer">\n' \ ' <div class="bibEditURButtonLayer"><button id="btnUndo" class="menu-btn">&lt;</button></div>\n' \ ' <div id="undoOperationVisualisationField" class="bibEditHiddenElement bibEditURPreviewBox">\n' \ ' <div id="undoOperationVisualisationFieldContent"></div>\n' \ ' </div>\n' \ ' </div>' \ ' <div class="bibEditURDetailsSection" id="bibEditURRedoListLayer">\n' \ ' <div class="bibEditURButtonLayer"><button id="btnRedo" class="menu-btn">&gt;</button></div>' \ ' <div id="redoOperationVisualisationField" class="bibEditHiddenElement bibEditURPreviewBox">\n' \ ' <div id="redoOperationVisualisationFieldContent"></div>' \ ' </div>\n' \ ' </div>\n' \ ' </div></td></tr></table>\n' % { \ 'imgCompressMenuSection': img('/img/bullet_toggle_minus.png', 'bibEditImgCompressMenuSection', id='ImgUndoRedoMenu') } statusarea = '<table>\n' \ ' <tr>\n' \ ' <td id="cellIndicator">%(imgIndicator)s</td>\n' \ ' <td id="cellStatus">%(lblChecking)s</td>\n' \ ' </table>' % { 'imgIndicator': img('/img/indicator.gif'), 'lblChecking': 'Checking status' + '...' } holdingpenpanel = '<div class="bibEditMenuSectionHeader">\n' \ ' %(imgCompressMenuSection)sHolding Pen\n' \ '<table class="bibEditMenuMore">\n<tr><td>' \ ' <div id="bibEditHoldingPenToolbar"> ' \ ' <div id="bibeditHPChanges"></div>' \ ' </div> </td></tr></table>' \ ' </div>\n' % \ { 'imgCompressMenuSection': img('/img/bullet_toggle_minus.png', 'bibEditImgCompressMenuSection', id='ImgHoldingPenMenu') } bibcirculationpanel = \ ' <div class="bibEditMenuSection" ' \ ' id="bibEditBibCircConnection">\n' \ '<div class="bibEditMenuSectionHeader">\n' \ ' %(imgCompressMenuSection)sPhysical Copies\n' \ ' <table class="bibEditMenuMore">\n<tr><td ' \ ' class="bibEditBibCircPanel">' \ ' Number of copies: ' \ ' <div id="bibEditBibCirculationCopies">0</div><br/>' \ ' <button id="bibEditBibCirculationBtn" class="menu-btn">' \ 'Edit physical copies</button>' \ ' </td></tr></table></div></div>' \ % { 'imgCompressMenuSection': img('/img/bullet_toggle_minus.png', 'bibEditImgCompressMenuSection', id='ImgBibCirculationMenu') } lnkSpecialChar = link('Special symbols', href='#', id='lnkSpecSymbols') lnkhelp = img('/img/help.png', '', style='vertical-align: bottom') + \ link('Help', href='#', onclick='window.open(' \ '\'%s/help/admin/bibedit-admin-guide#2\', \'\', \'width=640,' \ 'height=600,left=150,top=150,resizable=yes,scrollbars=yes\');' \ 'return false;' % CFG_SITE_URL) return ' <div id="bibEditMenu">\n' \ ' <div class="bibEditMenuSection">\n' \ ' %(recordmenu)s\n' \ ' </div>\n' \ ' <div class="bibEditMenuSection">\n' \ ' %(fieldmenu)s\n' \ ' </div>\n' \ ' <div class="bibEditMenuSection">\n' \ ' %(viewmenu)s\n' \ ' </div>\n' \ ' <div class="bibEditMenuSection">\n' \ ' %(holdingpenpanel)s\n'\ ' </div>'\ ' <div class="bibEditMenuSection">\n' \ ' %(undoredosection)s\n' \ ' </div>\n' \ ' <div class="bibEditMenuSection">\n' \ ' %(historymenu)s\n' \ ' </div>\n' \ ' %(circulationmenu)s\n' \ ' <div id="bibEditMenuSection">\n' \ ' %(statusarea)s\n' \ ' </div>\n' \ ' <div class="bibEditMenuSection" align="right">\n' \ ' %(lnkSpecialChar)s %(lnkhelp)s\n' \ ' </div>\n' \ ' </div>\n' % { 'recordmenu': recordmenu, 'viewmenu': viewmenu, 'fieldmenu': fieldmenu, 'statusarea': statusarea, 'lnkhelp': lnkhelp, 'lnkSpecialChar': lnkSpecialChar, 'holdingpenpanel': holdingpenpanel, 'historymenu': historymenu, 'undoredosection': undoredosection, 'circulationmenu': bibcirculationpanel } def history_comparebox(self, ln, revdate, revdate_cmp, comparison): """ Display the bibedit history comparison box. """ _ = gettext_set_language(ln) title = '<b>%(comp)s</b><br /><span class="diff_field_added">%(rev)s %(revdate)s</span>\ <br /><span class="diff_field_deleted">%(rev)s %(revdate_cmp)s</span>' % { 'comp': _('Comparison of:'), 'rev': _('Revision'), 'revdate': revdate, 'revdate_cmp': revdate_cmp} return ''' <div class="bibEditHistCompare"> <p>%s</p> <p> %s </p> </div>''' % (title, comparison) def clean_value(self, value, format): """ This function clean value for HTML interface and inverse. """ if format != "html": value = value.replace('"', '&quot;') value = value.replace('<', '&lt;') value = value.replace('>', '&gt;') else: value = value.replace('&quot;', '"') value = value.replace('&lt;', '<') value = value.replace('&gt;', '>') return value def focuson(self): html = """ <div id='display_div'> <strong>Display</strong> <br /> <ul id='focuson_list' class='list-plain'> <li> <input type="checkbox" name="references" id="focuson_references" value="references" checked/> <label for="focuson_references">References</label> </li> <li> <input type="checkbox" name="authors" id="focuson_authors" value="authors" checked/> <label for="focuson_authors">Authors</label> </li> <li> <input type="checkbox" name="others" id="focuson_others" value="others" checked/> <label for="focuson_others">Others</label> </li> </ul> </div> """ return html def img(src, _class='', **kargs): """Create an HTML <img> element.""" src = 'src="%s" ' % src if _class: _class = 'class="%s" ' % _class args = '' for karg in kargs: args += '%s="%s" ' % (karg, kargs[karg]) return '<img %s%s%s/>' % (src, _class, args) def inp(_type, _class='', **kargs): """Create an HTML <input> element.""" _type = 'type="%s" ' % _type if _class: _class = 'class="%s" ' % _class args = '' for karg in kargs: args += '%s="%s" ' % (karg, kargs[karg]) return '<input %s%s%s/>' % (_type, _class, args) def button(_type, value, _class="", **kargs): """Create an HTML <button> element.""" _type = 'type="%s" ' % _type class_result = "class='menu-btn " if _class: class_result += "%s' " % _class else: class_result += "'" args = '' for karg in kargs: args += '%s="%s" ' % (karg, kargs[karg]) return '<button %s%s%s>%s</button>' % (_type, class_result, args, value) def link(value, _class='', **kargs): """Create an HTML <a> (link) element.""" if _class: _class = 'class="%s" ' % _class args = '' for karg in kargs: args += '%s="%s" ' % (karg, kargs[karg]) return '<a %s%s>%s</a>' % (_class, args, value)<|fim▁end|>
' <tr>\n' \ ' <td id="tickets" colspan="4"><!--filled by bibedit_menu.js--></td>\n' \ ' </tr>\n' \
<|file_name|>sq-sortable-list.js<|end_file_name|><|fim▁begin|>import SqSortableList from 'sq-ember-inputs/components/sq-sortable-list'; <|fim▁hole|><|fim▁end|>
export default SqSortableList;
<|file_name|>demandmodel.cpp<|end_file_name|><|fim▁begin|>/* EPANET 3 * * Copyright (c) 2016 Open Water Analytics * Distributed under the MIT License (see the LICENSE file for details). * */ #include "demandmodel.h" #include "Elements/junction.h" #include <cmath> #include <algorithm> using namespace std; //----------------------------------------------------------------------------- // Parent constructor and destructor //----------------------------------------------------------------------------- DemandModel::DemandModel() : expon(0.0) {} DemandModel::DemandModel(double expon_) : expon(expon_) {} DemandModel::~DemandModel() {} //----------------------------------------------------------------------------- // Demand model factory //----------------------------------------------------------------------------- DemandModel* DemandModel::factory(const string model, const double expon_) { if ( model == "FIXED" ) return new FixedDemandModel(); else if ( model == "CONSTRAINED" ) return new ConstrainedDemandModel(); else if ( model == "POWER" ) return new PowerDemandModel(expon_); else if ( model == "LOGISTIC" ) return new LogisticDemandModel(expon_); else return nullptr; } //----------------------------------------------------------------------------- // Default functions //----------------------------------------------------------------------------- double DemandModel::findDemand(Junction* junc, double p, double& dqdh) { dqdh = 0.0; return junc->fullDemand; } //----------------------------------------------------------------------------- /// Fixed Demand Model //----------------------------------------------------------------------------- FixedDemandModel::FixedDemandModel() {} //----------------------------------------------------------------------------- /// Constrained Demand Model //----------------------------------------------------------------------------- ConstrainedDemandModel::ConstrainedDemandModel() {} bool ConstrainedDemandModel::isPressureDeficient(Junction* junc) { //if ( junc->fixedGrade || // ... return false if normal full demand is non-positive if (junc->fullDemand <= 0.0 ) return false; double hMin = junc->elev + junc->pMin; if ( junc->head < hMin ) { junc->fixedGrade = true; junc->head = hMin; return true; } return false; } double ConstrainedDemandModel::findDemand(Junction* junc, double p, double& dqdh)<|fim▁hole|> dqdh = 0.0; return junc->actualDemand; } //----------------------------------------------------------------------------- /// Power Demand Model //----------------------------------------------------------------------------- PowerDemandModel::PowerDemandModel(double expon_) : DemandModel(expon_) {} double PowerDemandModel::findDemand(Junction* junc, double p, double& dqdh) { // ... initialize demand and demand derivative double qFull = junc->fullDemand; double q = qFull; dqdh = 0.0; // ... check for positive demand and pressure range double pRange = junc->pFull - junc->pMin; if ( qFull > 0.0 && pRange > 0.0) { // ... find fraction of full pressure met (f) double factor = 0.0; double f = (p - junc->pMin) / pRange; // ... apply power function if (f <= 0.0) factor = 0.0; else if (f >= 1.0) factor = 1.0; else { factor = pow(f, expon); dqdh = expon / pRange * factor / f; } // ... update total demand and its derivative q = qFull * factor; dqdh = qFull * dqdh; } return q; } //----------------------------------------------------------------------------- /// Logistic Demand Model //----------------------------------------------------------------------------- LogisticDemandModel::LogisticDemandModel(double expon_) : DemandModel(expon_), a(0.0), b(0.0) {} double LogisticDemandModel::findDemand(Junction* junc, double p, double& dqdh) { double f = 1.0; // fraction of full demand double q = junc->fullDemand; // demand flow (cfs) double arg; // argument of exponential term double dfdh; // gradient of f w.r.t. pressure head // ... initialize derivative dqdh = 0.0; // ... check for positive demand and pressure range if ( junc->fullDemand > 0.0 && junc->pFull > junc->pMin ) { // ... find logistic function coeffs. a & b setCoeffs(junc->pMin, junc->pFull); // ... prevent against numerical over/underflow arg = a + b*p; if (arg < -100.) arg = -100.0; else if (arg > 100.0) arg = 100.0; // ... find fraction of full demand (f) and its derivative (dfdh) f = exp(arg); f = f / (1.0 + f); f = max(0.0, min(1.0, f)); dfdh = b * f * (1.0 - f); // ... evaluate demand and its derivative q = junc->fullDemand * f; dqdh = junc->fullDemand * dfdh; } return q; } void LogisticDemandModel::setCoeffs(double pMin, double pFull) { // ... computes logistic function coefficients // assuming 99.9% of full demand at full pressure // and 1% of full demand at minimum pressure. double pRange = pFull - pMin; a = (-4.595 * pFull - 6.907 * pMin) / pRange; b = 11.502 / pRange; }<|fim▁end|>
{
<|file_name|>search.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python<|fim▁hole|># Peteris Krumins ([email protected]) # http://www.catonmat.net -- good coders code, great reuse # # http://www.catonmat.net/blog/python-library-for-google-search/ # # Code is licensed under MIT license. # import re import urllib from htmlentitydefs import name2codepoint from BeautifulSoup import BeautifulSoup from browser import Browser, BrowserError class SearchError(Exception): """ Base class for Google Search exceptions. """ pass class ParseError(SearchError): """ Parse error in Google results. self.msg attribute contains explanation why parsing failed self.tag attribute contains BeautifulSoup object with the most relevant tag that failed to parse Thrown only in debug mode """ def __init__(self, msg, tag): self.msg = msg self.tag = tag def __str__(self): return self.msg def html(self): return self.tag.prettify() class SearchResult: def __init__(self, title, url, desc): self.title = title self.url = url self.desc = desc def __str__(self): return 'Google Search Result: "%s"' % self.title class GoogleSearch(object): SEARCH_URL_0 = "http://www.google.com/search?q=%(query)s&btnG=Google+Search" NEXT_PAGE_0 = "http://www.google.com/search?q=%(query)s&start=%(start)d" SEARCH_URL_1 = "http://www.google.com/search?q=%(query)s&num=%(num)d&btnG=Google+Search" NEXT_PAGE_1 = "http://www.google.com/search?q=%(query)s&num=%(num)d&start=%(start)d" def __init__(self, query, random_agent=False, debug=False, page=0): self.query = query self.debug = debug self.browser = Browser(debug=debug) self.results_info = None self.eor = False # end of results self._page = page self._results_per_page = 10 self._last_from = 0 if random_agent: self.browser.set_random_user_agent() @property def num_results(self): if not self.results_info: page = self._get_results_page() self.results_info = self._extract_info(page) if self.results_info['total'] == 0: self.eor = True return self.results_info['total'] def _get_page(self): return self._page def _set_page(self, page): self._page = page page = property(_get_page, _set_page) def _get_results_per_page(self): return self._results_per_page def _set_results_par_page(self, rpp): self._results_per_page = rpp results_per_page = property(_get_results_per_page, _set_results_par_page) def get_results(self): """ Gets a page of results """ if self.eor: return [] MAX_VALUE = 1000000 page = self._get_results_page() #search_info = self._extract_info(page) results = self._extract_results(page) search_info = {'from': self.results_per_page*self._page, 'to': self.results_per_page*self._page + len(results), 'total': MAX_VALUE} if not self.results_info: self.results_info = search_info if self.num_results == 0: self.eor = True return [] if not results: self.eor = True return [] if self._page > 0 and search_info['from'] == self._last_from: self.eor = True return [] if search_info['to'] == search_info['total']: self.eor = True self._page += 1 self._last_from = search_info['from'] return results def _maybe_raise(self, cls, *arg): if self.debug: raise cls(*arg) def _get_results_page(self): if self._page == 0: if self._results_per_page == 10: url = GoogleSearch.SEARCH_URL_0 else: url = GoogleSearch.SEARCH_URL_1 else: if self._results_per_page == 10: url = GoogleSearch.NEXT_PAGE_0 else: url = GoogleSearch.NEXT_PAGE_1 safe_url = url % { 'query': urllib.quote_plus(self.query), 'start': self._page * self._results_per_page, 'num': self._results_per_page } try: page = self.browser.get_page(safe_url) except BrowserError, e: raise SearchError, "Failed getting %s: %s" % (e.url, e.error) return BeautifulSoup(page) def _extract_info(self, soup): empty_info = {'from': 0, 'to': 0, 'total': 0} div_ssb = soup.find('div', id='ssb') if not div_ssb: self._maybe_raise(ParseError, "Div with number of results was not found on Google search page", soup) return empty_info p = div_ssb.find('p') if not p: self._maybe_raise(ParseError, """<p> tag within <div id="ssb"> was not found on Google search page""", soup) return empty_info txt = ''.join(p.findAll(text=True)) txt = txt.replace(',', '') matches = re.search(r'Results (\d+) - (\d+) of (?:about )?(\d+)', txt, re.U) if not matches: return empty_info return {'from': int(matches.group(1)), 'to': int(matches.group(2)), 'total': int(matches.group(3))} def _extract_results(self, soup): results = soup.findAll('li', {'class': 'g'}) ret_res = [] for result in results: eres = self._extract_result(result) if eres: ret_res.append(eres) return ret_res def _extract_result(self, result): title, url = self._extract_title_url(result) desc = self._extract_description(result) if not title or not url or not desc: return None return SearchResult(title, url, desc) def _extract_title_url(self, result): #title_a = result.find('a', {'class': re.compile(r'\bl\b')}) title_a = result.find('a') if not title_a: self._maybe_raise(ParseError, "Title tag in Google search result was not found", result) return None, None title = ''.join(title_a.findAll(text=True)) title = self._html_unescape(title) url = title_a['href'] match = re.match(r'/url\?q=(http[^&]+)&', url) if match: url = urllib.unquote(match.group(1)) return title, url def _extract_description(self, result): desc_div = result.find('div', {'class': re.compile(r'\bs\b')}) if not desc_div: self._maybe_raise(ParseError, "Description tag in Google search result was not found", result) return None desc_strs = [] def looper(tag): if not tag: return for t in tag: try: if t.name == 'br': break except AttributeError: pass try: desc_strs.append(t.string) except AttributeError: desc_strs.append(t) looper(desc_div) looper(desc_div.find('wbr')) # BeautifulSoup does not self-close <wbr> desc = ''.join(s for s in desc_strs if s) return self._html_unescape(desc) def _html_unescape(self, str): def entity_replacer(m): entity = m.group(1) if entity in name2codepoint: return unichr(name2codepoint[entity]) else: return m.group(0) def ascii_replacer(m): cp = int(m.group(1)) if cp <= 255: return unichr(cp) else: return m.group(0) s = re.sub(r'&#(\d+);', ascii_replacer, str, re.U) return re.sub(r'&([^;]+);', entity_replacer, s, re.U)<|fim▁end|>
#
<|file_name|>popup.js<|end_file_name|><|fim▁begin|>// Table row template with placeholders var ordersRowTemplate = '<tr><td><img class="order-status-icon" title="order_status_title" src="order_status_icon"></td><td><p class="order-number">Narudžba <strong>#order_number</strong> by</p><p class="first-last-name">order_name</p><p><a class="email" href="mailto:order_email">order_email</a></p></td><td><p class="date">order_date</p></td><td><p class="total">order_total</p><p class="payment-method">order_payment_method</p></td><td><div><button class="processing-order-button update-order-button" id="order_number-processing" title="Processing"></button><button class="complete-order-button update-order-button" id="order_number-complete" title="Complete"></button><button class="view-order-button update-order-button" id="order_number-view" title="View"></button></div></td></tr>'; //------------------------------------------------------ // LOAD ORDERS FROM STORAGE AND INSERT INTO POPUP TABLE //------------------------------------------------------ // For replacing all string instances in the template String.prototype.replaceAll = function(search, replacement) { var target = this; return target.replace(new RegExp(search, 'g'), replacement); }; // Loads saved data from chrome storage function loadOrdersFromStorage() { chrome.storage.local.get( 'allOrders', function (result) { insertData(result); }); } // Manipulate loaded data and insert it into template/HTML function insertData(result) { let orderRow = ""; console.log(result); // Remove old data $("#order-table-body tr").remove(); for (let i = 0; i < result.allOrders.length; i++) { // Dont display order if completed if (result.allOrders[i].status === "completed" || result.allOrders[i].status === "canceled" || result.allOrders[i].status === "refunded" || result.allOrders[i].status === "failed") continue; // Insert data into template by replacing placeholders with actual data orderRow = ordersRowTemplate .replaceAll("order_number", result.allOrders[i].number) .replaceAll("order_name", result.allOrders[i].billing.first_name + " " + result.allOrders[i].billing.last_name) .replaceAll("order_email", result.allOrders[i].billing.email) <|fim▁hole|> .replaceAll("order_payment_method", result.allOrders[i].payment_method); // Insert images into template switch (result.allOrders[i].status) { case "processing": orderRow = orderRow .replaceAll("order_status_icon", "/icons/icon-processed.png") .replaceAll("order_status_title", "Processing"); break; case "completed": orderRow = orderRow .replaceAll("order_status_icon", "/icons/icon-completed.png") .replaceAll("order_status_title", "Completed"); break; case "pending": orderRow = orderRow .replaceAll("order_status_icon", "/icons/icon-pending-payment.png") .replaceAll("order_status_title", "Pending Payment"); break; case "on-hold": orderRow = orderRow .replaceAll("order_status_icon", "/icons/icon-on-hold.png") .replaceAll("order_status_title", "On hold"); break; default: break; } // Insert row into HTML $("#order-table-body").append(orderRow); // Add listeners to update buttons $( "#" + result.allOrders[i].number + "-view" ).bind("click", function() { initializeChangeOrder("vieworder", result.allOrders[i].number); }); $( "#" + result.allOrders[i].number + "-complete" ).bind("click", function() { initializeChangeOrder("completeorder", result.allOrders[i].number); }); $( "#" + result.allOrders[i].number + "-processing" ).bind("click", function() { initializeChangeOrder("processorder", result.allOrders[i].number); }); // Hide unnecessary update buttons switch (result.allOrders[i].status) { case "processing": $("#" + result.allOrders[i].number + "-processing").css("visibility", "hidden"); break; case "completed": $("#" + result.allOrders[i].number + "-complete").css("visibility", "hidden"); break; default: break; } } } //------------------------------------- // //------------------------------------- function initializeChangeOrder(action, id) { $(".popup-notification").append("<span>Loading. Please wait.</span>"); chrome.storage.sync.get( 'options' , function(items) { let updateURL = "https://" + items.options.siteURL + "/wp-json/wc/v2/orders/" + id + "?consumer_key=" + items.options.consumerKey + "&consumer_secret=" + items.options.consumerSecret; let viewURL = "https://" + items.options.siteURL + "/wp-admin/post.php?post=" + id + "&action=edit"; if (action === "processorder"){processingOrder(updateURL, id);} else if (action === "completeorder"){completeOrder(updateURL, id);} else if (action === "vieworder") { viewOrder(viewURL, id); } }); } function changeOrderStatus(path, url, newStatus) { var xhr = new XMLHttpRequest (); xhr.onreadystatechange = function () { if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == "200") { reloadItems(); } }; xhr.open("PUT", url, true); xhr.setRequestHeader('Content-type','application/json; charset=utf-8'); xhr.send(JSON.stringify(newStatus)); return xhr.onreadystatechange(); } function completeOrder(url, id) { changeOrderStatus('jconfig.json', url, {status: "completed"}); } function processingOrder(url, id){ changeOrderStatus('jconfig.json', url, {status: "processing"}); } function viewOrder(viewURL, id){ var win = window.open(viewURL, '_blank'); win.focus(); } //-------------------------------------------------------------------- // GET REQUEST TO SERVER //-------------------------------------------------------------------- function reloadItems() { chrome.storage.sync.get( 'options', function (items) { let URL = "https://" + items.options.siteURL + "/wp-json/wc/v2/orders/?consumer_key=" + items.options.consumerKey + "&consumer_secret=" + items.options.consumerSecret; loadJSON('jconfig.json', URL, function saveJSON(result) { saveOrdersToStorage(result, function call() { location.reload(); notify(); }); }); } ); } function saveOrdersToStorage(allOrders, callback) { chrome.storage.local.clear(); chrome.storage.local.set({ 'allOrders': allOrders }, function () { }); callback(); } function loadJSON(path, url, callback) { var result; var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == "200") { result = JSON.parse(xhr.responseText); callback(result); } }; xhr.open("GET", url, true); xhr.send(); return xhr.onreadystatechange(); } //-------------------------------------------------------------------- // MISC WORK //-------------------------------------------------------------------- // Add href attr to link chrome.storage.sync.get( 'options' , function (items) { let URL = "https://" + items.options.siteURL + "/wp-admin/edit.php?post_type=shop_order"; $("#popup-see-all-orders").attr("href", URL); }); //---------------------------------------------------------------------- (function initialize() { chrome.browserAction.setBadgeText({ text: '' }); chrome.storage.sync.get( 'options' , function (items) { let URL = "https://" + items.options.siteURL + "/wp-json/wc/v2/orders/?consumer_key=" + items.options.consumerKey + "&consumer_secret=" + items.options.consumerSecret; loadJSON('jconfig.json', URL, function saveJSON(result) { saveOrdersToStorage(result, function callback(){}); }); }); loadOrdersFromStorage(); })(); // periodically check for new data (function loop() { setTimeout(function () { loadOrdersFromStorage(); loop(); }, 60000); }());<|fim▁end|>
.replaceAll("order_date", result.allOrders[i].date_created.slice(0, 10) + "<br>" + result.allOrders[i].date_created.slice(11, 19)) .replaceAll("order_total", result.allOrders[i].total + " " + result.allOrders[i].currency)
<|file_name|>datalake_samples_access_control_recursive_async.py<|end_file_name|><|fim▁begin|># coding: utf-8 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """ FILE: datalake_samples_access_control_recursive_async.py DESCRIPTION: This sample demonstrates recursive set/get access control on directories. USAGE: python datalake_samples_access_control_recursive_async.py Set the environment variables with your own values before running the sample: 1) STORAGE_ACCOUNT_NAME - the storage account name 2) STORAGE_ACCOUNT_KEY - the storage account key """ import os import random import uuid import asyncio from azure.core.exceptions import AzureError from azure.storage.filedatalake.aio import ( DataLakeServiceClient, ) # TODO: rerun after test account is fixed async def recursive_access_control_sample(filesystem_client): # create a parent directory dir_name = "testdir" print("Creating a directory named '{}'.".format(dir_name)) directory_client = await filesystem_client.create_directory(dir_name) # populate the directory with some child files await create_child_files(directory_client, 35) # get and display the permissions of the parent directory acl_props = await directory_client.get_access_control() print("Permissions of directory '{}' are {}.".format(dir_name, acl_props['permissions'])) # set the permissions of the entire directory tree recursively # update/remove acl operations are performed the same way acl = 'user::rwx,group::r-x,other::rwx' failed_entries = [] # the progress callback is invoked each time a batch is completed async def progress_callback(acl_changes): print(("In this batch: {} directories and {} files were processed successfully, {} failures were counted. " + "In total, {} directories and {} files were processed successfully, {} failures were counted.") .format(acl_changes.batch_counters.directories_successful, acl_changes.batch_counters.files_successful, acl_changes.batch_counters.failure_count, acl_changes.aggregate_counters.directories_successful, acl_changes.aggregate_counters.files_successful, acl_changes.aggregate_counters.failure_count)) # keep track of failed entries if there are any failed_entries.append(acl_changes.batch_failures) # illustrate the operation by using a small batch_size try: acl_change_result = await directory_client.set_access_control_recursive(acl=acl, progress_hook=progress_callback, batch_size=5) except AzureError as error: # if the error has continuation_token, you can restart the operation using that continuation_token if error.continuation_token: acl_change_result = \ await directory_client.set_access_control_recursive(acl=acl, continuation_token=error.continuation_token, progress_hook=progress_callback, batch_size=5) print("Summary: {} directories and {} files were updated successfully, {} failures were counted." .format(acl_change_result.counters.directories_successful, acl_change_result.counters.files_successful, acl_change_result.counters.failure_count)) # if an error was encountered, a continuation token would be returned if the operation can be resumed if acl_change_result.continuation is not None: print("The operation can be resumed by passing the continuation token {} again into the access control method." .format(acl_change_result.continuation)) # get and display the permissions of the parent directory again acl_props = await directory_client.get_access_control() print("New permissions of directory '{}' and its children are {}.".format(dir_name, acl_props['permissions'])) async def create_child_files(directory_client, num_child_files): import itertools async def create_file(): # generate a random name file_name = str(uuid.uuid4()).replace('-', '') file_client = directory_client.get_file_client(file_name) await file_client.create_file() futures = [asyncio.ensure_future(create_file()) for _ in itertools.repeat(None, num_child_files)] await asyncio.wait(futures) print("Created {} files under the directory '{}'.".format(num_child_files, directory_client.path_name)) async def run(): account_name = os.getenv('STORAGE_ACCOUNT_NAME', "") account_key = os.getenv('STORAGE_ACCOUNT_KEY', "") # set up the service client with the credentials from the environment variables service_client = DataLakeServiceClient(account_url="{}://{}.dfs.core.windows.net".format( "https", account_name ), credential=account_key) async with service_client: # generate a random name for testing purpose fs_name = "testfs{}".format(random.randint(1, 1000)) print("Generating a test filesystem named '{}'.".format(fs_name)) # create the filesystem filesystem_client = await service_client.create_file_system(file_system=fs_name) # invoke the sample code try: await recursive_access_control_sample(filesystem_client) finally:<|fim▁hole|> if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(run())<|fim▁end|>
# clean up the demo filesystem await filesystem_client.delete_file_system()
<|file_name|>caffe_tool.py<|end_file_name|><|fim▁begin|># Copyright 2017 The UAI-SDK 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. # ============================================================================== import argparse from uaitrain.operation.pack_docker_image.caffe_pack_op import CaffeUAITrainDockerImagePackOp from uaitrain.operation.create_train_job.base_create_op import BaseUAITrainCreateTrainJobOp from uaitrain.operation.stop_train_job.base_stop_op import BaseUAITrainStopTrainJobOp from uaitrain.operation.delete_train_job.base_delete_op import BaseUAITrainDeleteTrainJobOp from uaitrain.operation.list_train_job.base_list_job_op import BaseUAITrainListTrainJobOp from uaitrain.operation.info_train_job.info_train_op import BaseUAITrainRunningInfoOp from uaitrain.operation.get_realtime_log.base_log_op import BaseUAITrainGetRealtimeLogOp from uaitrain.operation.list_bill_info.base_bill_op import BaseUAITrainListBillInfoOp from uaitrain.operation.rename_train_job.base_rename_op import BaseUAITrainRenameTrainJobOp from uaitrain.operation.get_train_job_conf.base_conf_op import BaseUAITrainTrainJobConfOp from uaitrain.operation.get_log_topic.get_log_topic import BaseUAITrainGetLogTopicOp if __name__ == '__main__': parser = argparse.ArgumentParser( description='AI Caffe Arch Deployer', formatter_class=argparse.ArgumentDefaultsHelpFormatter) subparsers = parser.add_subparsers(dest='commands', help='commands') pack_op = CaffeUAITrainDockerImagePackOp(subparsers) create_op = BaseUAITrainCreateTrainJobOp(subparsers) stop_op = BaseUAITrainStopTrainJobOp(subparsers) delete_op = BaseUAITrainDeleteTrainJobOp(subparsers) list_op = BaseUAITrainListTrainJobOp(subparsers) info_op = BaseUAITrainRunningInfoOp(subparsers) log_op = BaseUAITrainGetRealtimeLogOp(subparsers) bill_op = BaseUAITrainListBillInfoOp(subparsers) rename_op = BaseUAITrainRenameTrainJobOp(subparsers) conf_op = BaseUAITrainTrainJobConfOp(subparsers) topic_op = BaseUAITrainGetLogTopicOp(subparsers)<|fim▁hole|> pack_op.cmd_run(cmd_args) elif cmd_args['commands'] == 'create': create_op.cmd_run(cmd_args) elif cmd_args['commands'] == 'stop': stop_op.cmd_run(cmd_args) elif cmd_args['commands'] == 'delete': delete_op.cmd_run(cmd_args) elif cmd_args['commands'] == 'list': list_op.cmd_run(cmd_args) elif cmd_args['commands'] == 'info': info_op.cmd_run(cmd_args) elif cmd_args['commands'] == 'log': log_op.cmd_run(cmd_args) elif cmd_args['commands'] == 'bill': bill_op.cmd_run(cmd_args) elif cmd_args['commands'] == 'rename': rename_op.cmd_run(cmd_args) elif cmd_args['commands'] == 'conf': conf_op.cmd_run(cmd_args) elif cmd_args['commands'] == 'topic': topic_op.cmd_run(cmd_args) else: print("Unknown CMD, please use python caffe_tool.py -h to check")<|fim▁end|>
cmd_args = vars(parser.parse_args()) if cmd_args['commands'] == 'pack':
<|file_name|>qmisc_test.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python # -*- coding: utf-8 -*- # import funkcí z jiného adresáře import os.path path_to_script = os.path.dirname(os.path.abspath(__file__)) # sys.path.append(os.path.join(path_to_script, "../extern/pyseg_base/src/")) import unittest import numpy as np import os <|fim▁hole|> # class QmiscTest(unittest.TestCase): interactivetTest = False # interactivetTest = True # @unittest.skip("waiting for implementation") def test_suggest_filename(self): """ Testing some files. Not testing recursion in filenames. It is situation if there exist file0, file1, file2 and input file is file """ filename = "mujsoubor" # import ipdb; ipdb.set_trace() # BREAKPOINT new_filename = misc.suggest_filename(filename, exists=True) # self.assertTrue(new_filename == "mujsoubor2") self.assertEqual(new_filename, "mujsoubor_2") filename = "mujsoubor_112" new_filename = misc.suggest_filename(filename, exists=True) self.assertTrue(new_filename == "mujsoubor_113") filename = "mujsoubor_2.txt" new_filename = misc.suggest_filename(filename, exists=True) self.assertTrue(new_filename == "mujsoubor_3.txt") filename = "mujsoubor27.txt" new_filename = misc.suggest_filename(filename, exists=True) self.assertTrue(new_filename == "mujsoubor27_2.txt") filename = "mujsoubor-a24.txt" new_filename = misc.suggest_filename(filename, exists=False) self.assertEqual(new_filename, "mujsoubor-a24.txt", "Rewrite") @unittest.skip("getVersionString is not used anymore") def test_getVersionString(self): """ getVersionString is not used anymore """ vfn = "../__VERSION__" existed = False if not os.path.exists(vfn): with open(vfn, 'a') as the_file: the_file.write('1.1.1\n') existed = False verstr = qmisc.getVersionString() self.assertTrue(type(verstr) == str) if existed: os.remove(vfn) def test_obj_to_and_from_file_yaml(self): testdata = np.random.random([4, 4, 3]) test_object = {'a': 1, 'data': testdata} filename = 'test_obj_to_and_from_file.yaml' misc.obj_to_file(test_object, filename, 'yaml') saved_object = misc.obj_from_file(filename, 'yaml') self.assertTrue(saved_object['a'] == 1) self.assertTrue(saved_object['data'][1, 1, 1] == testdata[1, 1, 1]) os.remove(filename) def test_obj_to_and_from_file_pickle(self): testdata = np.random.random([4, 4, 3]) test_object = {'a': 1, 'data': testdata} filename = 'test_obj_to_and_from_file.pkl' misc.obj_to_file(test_object, filename, 'pickle') saved_object = misc.obj_from_file(filename, 'pickle') self.assertTrue(saved_object['a'] == 1) self.assertTrue(saved_object['data'][1, 1, 1] == testdata[1, 1, 1]) os.remove(filename) # def test_obj_to_and_from_file_exeption(self): # test_object = [1] # filename = 'test_obj_to_and_from_file_exeption' # self.assertRaises(misc.obj_to_file(test_object, filename ,'yaml')) def test_obj_to_and_from_file_with_directories(self): import shutil testdata = np.random.random([4, 4, 3]) test_object = {'a': 1, 'data': testdata} dirname = '__test_write_and_read' filename = '__test_write_and_read/test_obj_to_and_from_file.pkl' misc.obj_to_file(test_object, filename, 'pickle') saved_object = misc.obj_from_file(filename, 'pickle') self.assertTrue(saved_object['a'] == 1) self.assertTrue(saved_object['data'][1, 1, 1] == testdata[1, 1, 1]) shutil.rmtree(dirname) if __name__ == "__main__": unittest.main()<|fim▁end|>
from imtools import qmisc from imtools import misc
<|file_name|>global.js<|end_file_name|><|fim▁begin|>// This file contains javascript that is global to the entire Garden application // Global vanilla library function. (function(window, $) { var Vanilla = function() { }; Vanilla.fn = Vanilla.prototype; if (!window.console) window.console = { log: function() { } }; Vanilla.scrollTo = function(q) { var top = $(q).offset().top; window.scrollTo(0, top); return false; }; // Add a stub for embedding. Vanilla.parent = function() { }; Vanilla.parent.callRemote = function(func, args, success, failure) { console.log("callRemote stub: " + func, args); }; window.gdn = window.gdn || {}; window.Vanilla = Vanilla; gdn.getMeta = function(key, defaultValue) { if (gdn.meta[key] === undefined) { return defaultValue; } else { return gdn.meta[key]; } }; gdn.setMeta = function(key, value) { gdn.meta[key] = value; }; var keyString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // See http://ecmanaut.blogspot.de/2006/07/encoding-decoding-utf8-in-javascript.html var uTF8Encode = function(string) { return decodeURI(encodeURIComponent(string)); }; // See http://ecmanaut.blogspot.de/2006/07/encoding-decoding-utf8-in-javascript.html var uTF8Decode = function(string) { return decodeURIComponent(escape(string)); }; $.extend({ // private property keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", base64Encode: function(input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = uTF8Encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyString.charAt(enc1) + keyString.charAt(enc2) + keyString.charAt(enc3) + keyString.charAt(enc4); } return output; }, base64Decode: function(input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = keyString.indexOf(input.charAt(i++)); enc2 = keyString.indexOf(input.charAt(i++)); enc3 = keyString.indexOf(input.charAt(i++)); enc4 = keyString.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } output = uTF8Decode(output); return output; } }); /** * Takes a jQuery function that updates the DOM and the HTML to add. Converts the html to a jQuery object * and then adds it to the DOM. Triggers 'contentLoad' to allow javascript manipulation of the new DOM elements. * * @param func The jQuery function name. * @param html The html to add. */ var funcTrigger = function(func, html) { this.each(function() { var $elem = $($.parseHTML(html + '')); // Typecast html to a string and create a DOM node $(this)[func]($elem); $elem.trigger('contentLoad'); }); return this; }; $.fn.extend({ appendTrigger: function(html) { return funcTrigger.call(this, 'append', html); }, beforeTrigger: function(html) { return funcTrigger.call(this, 'before', html); }, afterTrigger: function(html) { return funcTrigger.call(this, 'after', html); }, prependTrigger: function(html) { return funcTrigger.call(this, 'prepend', html); }, htmlTrigger: function(html) { funcTrigger.call(this, 'html', html); }, replaceWithTrigger: function(html) { return funcTrigger.call(this, 'replaceWith', html); } }); $(document).ajaxComplete(function(event, jqXHR, ajaxOptions) { var csrfToken = jqXHR.getResponseHeader("X-CSRF-Token"); if (csrfToken) { gdn.setMeta("TransientKey", csrfToken); $("input[name=TransientKey]").val(csrfToken); } }); // Hook into form submissions. Replace element body with server response when we're in a .js-form. $(document).on("contentLoad", function (e) { $("form", e.target).submit(function (e) { var $form = $(this); // Traverse up the DOM, starting from the form that triggered the event, looking for the first .js-form. var $parent = $form.closest(".js-form"); // Bail if we aren't in a .js-form. if ($parent.length === 0) { return; } // Hijack this submission. e.preventDefault(); // An object containing extra data that should be submitted along with the form. var data = { DeliveryType: "VIEW" }; var submitButton = $form.find("input[type=submit]:focus").get(0); if (submitButton) { data[submitButton.name] = submitButton.name; } // Send the request, expect HTML and hope for the best. $form.ajaxSubmit({ data: data, dataType: "html", success: function (data, textStatus, jqXHR) { $parent.html(data).trigger('contentLoad'); } }); }); }); function accessibleButtonsInit() { $(document).delegate("[role=button]", 'keydown', function(event) { var $button = $(this); var ENTER_KEY = 13; var SPACE_KEY = 32; var isActiveElement = document.activeElement === $button[0]; var isSpaceOrEnter = event.keyCode === ENTER_KEY || event.keyCode === SPACE_KEY; if (isActiveElement && isSpaceOrEnter) { event.preventDefault(); $button.click(); } }); } $(document).on("contentLoad", function(e) { // Setup AJAX filtering for flat category module. // Find each flat category module container, if any. $(".BoxFlatCategory", e.target).each(function(index, value){ // Setup the constants we'll need to perform the lookup for this module instance. var container = value; var categoryID = $("input[name=CategoryID]", container).val(); var limit = parseInt($("input[name=Limit]", container).val()); // If we don't even have a category, don't bother setting up filtering. if (typeof categoryID === "undefined") { return; } // limit was parsed as an int when originally defined. If it isn't a valid value now, default to 10. if (isNaN(limit) || limit < 1) { limit = 10; } // Anytime someone types something into the search box in this instance's container... $(container).on("keyup", ".SearchForm .InputBox", function(filterEvent) { var url = gdn.url("module/flatcategorymodule/vanilla"); // ...perform an AJAX request, replacing the current category data with the result's data. jQuery.get( gdn.url("module/flatcategorymodule/vanilla"), { categoryID: categoryID, filter: filterEvent.target.value, limit: limit }, function(data, textStatus, jqXHR) { $(".FlatCategoryResult", container).replaceWith($(".FlatCategoryResult", data)); } ) }); }); // A vanilla JS event wrapper for the contentLoad event so that the new framework can handle it. $(document).on("contentLoad", function(e) { // Don't fire on initial document ready. if (e.target === document) { return; } var event = document.createEvent('CustomEvent'); event.initCustomEvent('X-DOMContentReady', true, false, {}); e.target.dispatchEvent(event); }); // Set up accessible flyouts $('.ToggleFlyout, .editor-dropdown, .ButtonGroup').accessibleFlyoutsInit(); accessibleButtonsInit(); }); })(window, jQuery); // Stuff to fire on document.ready(). jQuery(document).ready(function($) { /** * @deprecated since Vanilla 2.2 */ $.postParseJson = function(json) { return json; }; gdn.focused = true; gdn.Libraries = {}; $(window).blur(function() { gdn.focused = false; }); $(window).focus(function() { gdn.focused = true; }); // Grab a definition from object in the page gdn.definition = function(definition, defaultVal, set) { if (defaultVal === undefined) defaultVal = definition; if (!(definition in gdn.meta)) { return defaultVal; } if (set) { gdn.meta[definition] = defaultVal; } return gdn.meta[definition]; }; gdn.disable = function(e, progressClass) { var href = $(e).attr('href'); if (href) { $.data(e, 'hrefBak', href); } $(e).addClass(progressClass ? progressClass : 'InProgress').removeAttr('href').attr('disabled', true); }; gdn.enable = function(e) { $(e).attr('disabled', false).removeClass('InProgress'); var href = $.data(e, 'hrefBak'); if (href) { $(e).attr('href', href); $.removeData(e, 'hrefBak'); } }; gdn.elementSupports = function(element, attribute) { var test = document.createElement(element); if (attribute in test) return true; else return false; }; gdn.querySep = function(url) { return url.indexOf('?') == -1 ? '?' : '&'; }; // password strength check gdn.password = function(password, username) { var translations = gdn.definition('PasswordTranslations', 'Too Short,Contains Username,Very Weak,Weak,Ok,Good,Strong').split(','); // calculate entropy var alphabet = 0; if (password.match(/[0-9]/)) alphabet += 10; if (password.match(/[a-z]/)) alphabet += 26; if (password.match(/[A-Z]/)) alphabet += 26; if (password.match(/[^a-zA-Z0-9]/)) alphabet += 31; var natLog = Math.log(Math.pow(alphabet, password.length)); var entropy = natLog / Math.LN2; var response = { pass: false, symbols: alphabet, entropy: entropy, score: 0 }; // reject on length var length = password.length; response.length = length; var requiredLength = gdn.definition('MinPassLength', 6); var requiredScore = gdn.definition('MinPassScore', 2); response.required = requiredLength; if (length < requiredLength) { response.reason = translations[0]; return response; } // password1 == username if (username) { if (password.toLowerCase().indexOf(username.toLowerCase()) >= 0) { response.reason = translations[1]; return response; } } if (entropy < 30) { response.score = 1; response.reason = translations[2]; // very weak } else if (entropy < 40) { response.score = 2; response.reason = translations[3]; // weak } else if (entropy < 55) { response.score = 3; response.reason = translations[4]; // ok } else if (entropy < 70) { response.score = 4; response.reason = translations[5]; // good } else { response.score = 5; response.reason = translations[6]; // strong } return response; }; // Go to notifications if clicking on a user's notification count $('li.UserNotifications a span').click(function() { document.location = gdn.url('/profile/notifications'); return false; }); /** * Add `rel='noopener'` to everything on the page. * * If you really need the linked page to have window.opener, set the `data-allow-opener='true'` on your link. */ $("a[target='_blank']") .filter(":not([rel*='noopener']):not([data-allow-opener='true'])") .each(function() { var $this = $(this); var rel = $this.attr("rel"); if (rel) { $this.attr("rel", rel + " noopener"); } else { $this.attr("rel", "noopener"); } }); // This turns any anchor with the "Popup" class into an in-page pop-up (the // view of the requested in-garden link will be displayed in a popup on the // current screen). if ($.fn.popup) { // Previously, jquery.popup used live() to attach events, even to elements // that do not yet exist. live() has been deprecated. Vanilla upgraded // jQuery to version 1.10.2, which removed a lot of code. Instead, event // delegation will need to be used, which means everywhere that Popup // is called, will need to have a very high up parent delegate to it. //$('a.Popup').popup(); //$('a.PopConfirm').popup({'confirm' : true, 'followConfirm' : true}); $('a.Popup:not(.dashboard a.Popup):not(.Section-Dashboard a.Popup)').popup(); $('a.PopConfirm').popup({'confirm': true, 'followConfirm': true}); } $(document).delegate(".PopupWindow:not(.Message .PopupWindow)", 'click', function() { var $this = $(this); if ($this.hasClass('NoMSIE') && /msie/.test(navigator.userAgent.toLowerCase())) { return; } var width = $this.attr('popupWidth'); width = width ? width : 960; var height = $this.attr('popupHeight'); height = height ? height : 600; var left = (screen.width - width) / 2; var top = (screen.height - height) / 2; var id = $this.attr('id'); var href = $this.attr('href'); if ($this.attr('popupHref')) href = $this.attr('popupHref'); else href += gdn.querySep(href) + 'display=popup'; var win = window.open(href, 'Window_' + id, "left=" + left + ",top=" + top + ",width=" + width + ",height=" + height + ",status=0,scrollbars=0"); if (win) win.focus(); return false; }); // This turns any anchor with the "Popdown" class into an in-page pop-up, but // it does not hijack forms in the popup. if ($.fn.popup) $('a.Popdown').popup({hijackForms: false}); // This turns SignInPopup anchors into in-page popups if ($.fn.popup) $('a.SignInPopup').popup({containerCssClass: 'SignInPopup'}); if ($.fn.popup) $(document).delegate('.PopupClose', 'click', function(event) { var Popup = $(event.target).parents('.Popup'); if (Popup.length) { var PopupID = Popup.prop('id'); $.popup.close({popupId: PopupID}); } }); // Make sure that message dismissalls are ajax'd $(document).delegate('a.Dismiss', 'click', function() { var anchor = this; var container = $(anchor).parent(); var transientKey = gdn.definition('TransientKey'); var data = 'DeliveryType=BOOL&TransientKey=' + transientKey; $.post($(anchor).attr('href'), data, function(response) { if (response == 'TRUE') $(container).fadeOut('fast', function() { $(this).remove(); }); }); return false; }); // This turns any form into a "post-in-place" form so it is ajaxed to save // without a refresh. The form must be within an element with the "AjaxForm" // class. if ($.fn.handleAjaxForm) $('.AjaxForm').handleAjaxForm(); // Handle ToggleMenu toggling and set up default state $('[class^="Toggle-"]').hide(); // hide all toggle containers $('.ToggleMenu a').click(function() { // Make all toggle buttons and toggle containers inactive $(this).parents('.ToggleMenu').find('li').removeClass('Active'); $('[class^="Toggle-"]').hide(); var item = $(this).parents('li'); // Identify the clicked container // The selector of the container that should be revealed. var containerSelector = '.Toggle-' + item.attr('class'); containerSelector = containerSelector.replace(/Handle-/gi, ''); // Reveal the container & make the button active item.addClass('Active'); // Make the clicked form button active $(containerSelector).show(); return false; }); $('.ToggleMenu .Active a').click(); // reveal the currently active item. // Show hoverhelp on hover $('.HoverHelp').hover( function() { $(this).find('.Help').show(); }, function() { $(this).find('.Help').hide(); } ); // If a page loads with a hidden redirect url, go there after a few moments. var redirectTo = gdn.getMeta('RedirectTo', ''); var checkPopup = gdn.getMeta('CheckPopup', false); if (redirectTo !== '') { if (checkPopup && window.opener) { window.opener.location = redirectTo; window.close(); } else { document.location = redirectTo; } } // Make tables sortable if the tableDnD plugin is present. if ($.tableDnD) $("table.Sortable").tableDnD({ onDrop: function(table, row) { var tableId = $($.tableDnD.currentTable).attr('id'); // Add in the transient key for postback authentication var transientKey = gdn.definition('TransientKey'); var data = $.tableDnD.serialize() + '&TableID=' + tableId + '&TransientKey=' + transientKey; var webRoot = gdn.definition('WebRoot', ''); $.post( gdn.url('/utility/sort.json'), data, function(response) { if (response.Result) { $('#' + tableId + ' tbody tr td').effect("highlight", {}, 1000); } } ); } }); // Make sure that the commentbox & aboutbox do not allow more than 1000 characters $.fn.setMaxChars = function(iMaxChars) { $(this).bind('keyup', function() { var txt = $(this).val(); if (txt.length > iMaxChars) $(this).val(txt.substr(0, iMaxChars)); }); }; // Generate a random string of specified length gdn.generateString = function(length) { if (length === undefined) length = 5; var chars = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789!@#$%*'; var string = ''; var pos = 0; for (var i = 0; i < length; i++) { pos = Math.floor(Math.random() * chars.length); string += chars.substring(pos, pos + 1); } return string; }; // Combine two paths and make sure that there is only a single directory concatenator gdn.combinePaths = function(path1, path2) { if (path1.substr(-1, 1) == '/') path1 = path1.substr(0, path1.length - 1); if (path2.substring(0, 1) == '/') path2 = path2.substring(1); return path1 + '/' + path2; }; gdn.processTargets = function(targets, $elem, $parent) { if (!targets || !targets.length) return; var tar = function(q) { switch (q) { case '!element': return $elem; case '!parent': return $parent; default: return q; } }, item, $target; for (var i = 0; i < targets.length; i++) { item = targets[i]; if (jQuery.isArray(item.Target)) { $target = $(tar(item.Target[0]), tar(item.Target[1])); } else { $target = $(tar(item.Target)); } switch (item.Type) { case 'AddClass': $target.addClass(item.Data); break; case 'Ajax': $.ajax({ type: "POST", url: item.Data }); break; case 'Append': $target.appendTrigger(item.Data); break; case 'Before': $target.beforeTrigger(item.Data); break; case 'After': $target.afterTrigger(item.Data); break; case 'Highlight': $target.effect("highlight", {}, "slow"); break; case 'Prepend': $target.prependTrigger(item.Data); break; case 'Redirect': window.location.replace(item.Data); break; case 'Refresh': window.location.reload(); break; case 'Remove': $target.remove(); break; case 'RemoveClass': $target.removeClass(item.Data); break; case 'ReplaceWith': $target.replaceWithTrigger(item.Data); break; case 'SlideUp': $target.slideUp('fast'); break; case 'SlideDown': $target.slideDown('fast'); break; case 'Text': $target.text(item.Data); break; case 'Trigger': $target.trigger(item.Data); break; case 'Html': $target.htmlTrigger(item.Data); break; case 'Callback': jQuery.proxy(window[item.Data], $target)(); break; } } }; gdn.requires = function(Library) { if (!(Library instanceof Array)) Library = [Library]; var Response = true; $(Library).each(function(i, Lib) { // First check if we already have this library var LibAvailable = gdn.available(Lib); if (!LibAvailable) Response = false; // Skip any libs that are ready or processing if (gdn.Libraries[Lib] === false || gdn.Libraries[Lib] === true) return; // As yet unseen. Try to load gdn.Libraries[Lib] = false; var Src = '/js/' + Lib + '.js'; var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = Src; head.appendChild(script); }); if (Response) gdn.loaded(null); return Response; }; gdn.loaded = function(Library) { if (Library) gdn.Libraries[Library] = true; $(document).trigger('libraryloaded', [Library]); }; gdn.available = function(Library) { if (!(Library instanceof Array)) Library = [Library]; for (var i = 0; i < Library.length; i++) { var Lib = Library[i]; if (gdn.Libraries[Lib] !== true) return false; } return true; }; gdn.url = function(path) { if (path.indexOf("//") >= 0) return path; // this is an absolute path. var urlFormat = gdn.definition("UrlFormat", "/{Path}"); if (path.substr(0, 1) == "/") path = path.substr(1); if (urlFormat.indexOf("?") >= 0) path = path.replace("?", "&"); return urlFormat.replace("{Path}", path); }; // Fill in placeholders. if (!gdn.elementSupports('input', 'placeholder')) { $('input:text,textarea').not('.NoIE').each(function() { var $this = $(this); var placeholder = $this.attr('placeholder'); if (!$this.val() && placeholder) { $this.val(placeholder); $this.blur(function() { if ($this.val() === '') $this.val(placeholder); }); $this.focus(function() { if ($this.val() == placeholder) $this.val(''); }); $this.closest('form').bind('submit', function() { if ($this.val() == placeholder) $this.val(''); }); } }); } // var searchText = gdn.definition('Search', 'Search'); // if (!$('div.Search input.InputBox').val()) // $('div.Search input.InputBox').val(searchText); // $('div.Search input.InputBox').blur(function() { // if (typeof $(this).val() == 'undefined' || $(this).val() == '') // $(this).val(searchText); // }); // $('div.Search input.InputBox').focus(function() { // if ($(this).val() == searchText) // $(this).val(''); // }); $.fn.popin = function(options) { var settings = $.extend({}, options); this.each(function(i, elem) { var url = $(elem).attr('rel'); var $elem = $(elem); $.ajax({ url: gdn.url(url), data: {DeliveryType: 'VIEW'}, success: function(data) { $elem.html($.parseHTML(data + '')).trigger('contentLoad'); }, complete: function() { $elem.removeClass('Progress TinyProgress InProgress'); if (settings.complete !== undefined) { settings.complete($elem); } } }); }); }; $('.Popin, .js-popin').popin(); // Make poplist items with a rel attribute clickable. $(document).on('click', '.PopList .Item[rel]', function() { window.location.href = $(this).attr('rel'); }); var hijackClick = function(e) { var $elem = $(this); var $parent = $(this).closest('.Item'); var $toggleFlyout = $elem.closest('.ToggleFlyout'); var href = $elem.attr('href'); var progressClass = $elem.hasClass('Bookmark') ? 'Bookmarking' : 'InProgress'; // If empty, or starts with a fragment identifier, do not send // an async request. if (!href || href.trim().indexOf('#') === 0) return; gdn.disable(this, progressClass); e.stopPropagation(); $.ajax({ type: "POST", url: href, data: {DeliveryType: 'VIEW', DeliveryMethod: 'JSON', TransientKey: gdn.definition('TransientKey')}, dataType: 'json', complete: function() { gdn.enable($elem.get(0)); $elem.removeClass(progressClass); $elem.attr('href', href); // If we are in a flyout, close it. $toggleFlyout .removeClass('Open') .find('.Flyout') .hide() .setFlyoutAttributes(); }, error: function(xhr) { gdn.informError(xhr); }, success: function(json) { if (json === null) json = {}; var informed = gdn.inform(json); gdn.processTargets(json.Targets, $elem, $parent); // If there is a redirect url, go to it. if (json.RedirectTo) { setTimeout(function() { window.location.replace(json.RedirectTo); }, informed ? 3000 : 0); } } }); return false; }; $(document).delegate('.Hijack, .js-hijack', 'click', hijackClick); // Activate ToggleFlyout and ButtonGroup menus $(document).delegate('.ButtonGroup > .Handle', 'click', function() { var $buttonGroup = $(this).closest('.ButtonGroup'); if (!$buttonGroup.hasClass('Open')) { $('.ButtonGroup') .removeClass('Open') .setFlyoutAttributes(); // Open this one $buttonGroup .addClass('Open') .setFlyoutAttributes(); } else { $('.ButtonGroup') .removeClass('Open') .setFlyoutAttributes(); } return false; }); var lastOpen = null; $(document).delegate('.ToggleFlyout', 'click', function(e) { var $toggleFlyout = $(this); var $flyout = $('.Flyout', this); var isHandle = false; if ($(e.target).closest('.Flyout').length === 0) { e.stopPropagation(); isHandle = true; } else if ($(e.target).hasClass('Hijack') || $(e.target).closest('a').hasClass('Hijack')) { return; } e.stopPropagation(); // Dynamically fill the flyout. var rel = $(this).attr('rel'); if (rel) { $(this).attr('rel', ''); $flyout.html('<div class="InProgress" style="height: 30px"></div>'); $.ajax({ url: gdn.url(rel), data: {DeliveryType: 'VIEW'}, success: function(data) { $flyout.html(data); }, error: function(xhr) { $flyout.html(''); gdn.informError(xhr, true); } }); } if ($flyout.css('display') == 'none') { if (lastOpen !== null) { $('.Flyout', lastOpen).hide(); $(lastOpen).removeClass('Open').closest('.Item').removeClass('Open'); $toggleFlyout.setFlyoutAttributes(); } $(this).addClass('Open').closest('.Item').addClass('Open'); $flyout.show(); lastOpen = this; $toggleFlyout.setFlyoutAttributes(); } else { $flyout.hide(); $(this).removeClass('Open').closest('.Item').removeClass('Open'); $toggleFlyout.setFlyoutAttributes(); } if (isHandle) return false; }); // Close ToggleFlyout menu even if their links are hijacked $(document).delegate('.ToggleFlyout a', 'mouseup', function() { if ($(this).hasClass('FlyoutButton')) return; $('.ToggleFlyout').removeClass('Open').closest('.Item').removeClass('Open'); $('.Flyout').hide(); $(this).closest('.ToggleFlyout').setFlyoutAttributes(); }); $(document).delegate(document, 'click', function() { if (lastOpen) { $('.Flyout', lastOpen).hide(); $(lastOpen).removeClass('Open').closest('.Item').removeClass('Open'); } $('.ButtonGroup') .removeClass('Open') .setFlyoutAttributes(); }); <|fim▁hole|> $(this).before('<span class="AfterButtonLoading">&#160;</span>').removeClass('SpinOnClick'); }); // Confirmation for item removals $('a.RemoveItem').click(function() { if (!confirm('Are you sure you would like to remove this item?')) { return false; } }); if (window.location.hash === '') { // Jump to the hash if desired. if (gdn.definition('LocationHash', 0) !== 0) { $(window).load(function() { window.location.hash = gdn.definition('LocationHash'); }); } if (gdn.definition('ScrollTo', 0) !== 0) { var scrollTo = $(gdn.definition('ScrollTo')); if (scrollTo.length > 0) { $('html').animate({ scrollTop: scrollTo.offset().top - 10 }); } } } gdn.stats = function() { // Call directly back to the deployment and invoke the stats handler var StatsURL = gdn.url('settings/analyticstick.json'); var SendData = { 'TransientKey': gdn.definition('TransientKey'), 'Path': gdn.definition('Path'), 'Args': gdn.definition('Args'), 'ResolvedPath': gdn.definition('ResolvedPath'), 'ResolvedArgs': gdn.definition('ResolvedArgs') }; if (gdn.definition('TickExtra', null) !== null) SendData.TickExtra = gdn.definition('TickExtra'); jQuery.ajax({ dataType: 'json', type: 'post', url: StatsURL, data: SendData, success: function(json) { gdn.inform(json); }, complete: function(jqXHR, textStatus) { jQuery(document).triggerHandler('analyticsTick', [SendData, jqXHR, textStatus]); } }); }; // Ping back to the deployment server to track views, and trigger // conditional stats tasks var AnalyticsTask = gdn.definition('AnalyticsTask', false); if (AnalyticsTask == 'tick') gdn.stats(); // If a dismissable InformMessage close button is clicked, hide it. $(document).delegate('div.InformWrapper.Dismissable a.Close, div.InformWrapper .js-inform-close', 'click', function() { $(this).parents('div.InformWrapper').fadeOut('fast', function() { $(this).remove(); }); }); gdn.setAutoDismiss = function() { var timerId = $('div.InformMessages').attr('autodismisstimerid'); if (!timerId) { timerId = setTimeout(function() { $('div.InformWrapper.AutoDismiss').fadeOut('fast', function() { $(this).remove(); }); $('div.InformMessages').removeAttr('autodismisstimerid'); }, 7000); $('div.InformMessages').attr('autodismisstimerid', timerId); } }; // Handle autodismissals $(document).on('informMessage', function() { gdn.setAutoDismiss(); }); // Prevent autodismiss if hovering any inform messages $(document).delegate('div.InformWrapper', 'mouseover mouseout', function(e) { if (e.type == 'mouseover') { var timerId = $('div.InformMessages').attr('autodismisstimerid'); if (timerId) { clearTimeout(timerId); $('div.InformMessages').removeAttr('autodismisstimerid'); } } else { gdn.setAutoDismiss(); } }); // Take any "inform" messages out of an ajax response and display them on the screen. gdn.inform = function(response) { if (!response) return false; if (!response.InformMessages || response.InformMessages.length === 0) return false; // If there is no message container in the page, add one var informMessages = $('div.InformMessages'); if (informMessages.length === 0) { $('<div class="InformMessages"></div>').appendTo('body'); informMessages = $('div.InformMessages'); } var wrappers = $('div.InformMessages div.InformWrapper'), css, elementId, sprite, dismissCallback, dismissCallbackUrl; // Loop through the inform messages and add them to the container for (var i = 0; i < response.InformMessages.length; i++) { css = 'InformWrapper'; if (response.InformMessages[i].CssClass) css += ' ' + response.InformMessages[i].CssClass; elementId = ''; if (response.InformMessages[i].id) elementId = response.InformMessages[i].id; sprite = ''; if (response.InformMessages[i].Sprite) { css += ' HasSprite'; sprite = response.InformMessages[i].Sprite; } dismissCallback = response.InformMessages[i].DismissCallback; dismissCallbackUrl = response.InformMessages[i].DismissCallbackUrl; if (dismissCallbackUrl) dismissCallbackUrl = gdn.url(dismissCallbackUrl); try { var message = response.InformMessages[i].Message; var emptyMessage = message === ''; message = '<span class="InformMessageBody">' + message + '</span>'; // Is there a sprite? if (sprite !== '') message = '<span class="InformSprite ' + sprite + '"></span>'; // If the message is dismissable, add a close button if (css.indexOf('Dismissable') > 0) message = '<a href="#" onclick="return false;" tabindex="0" class="Close"><span>&times;</span></a>' + message; message = '<div class="InformMessage">' + message + '</div>'; // Insert any transient keys into the message (prevents csrf attacks in follow-on action urls). message = message.replace(/{TransientKey}/g, gdn.definition('TransientKey')); if (gdn.getMeta('SelfUrl')) { // If the url is explicitly defined (as in embed), use it. message = message.replace(/{SelfUrl}/g, gdn.getMeta('SelfUrl')); } else { // Insert the current url as a target for inform anchors message = message.replace(/{SelfUrl}/g, document.URL); } var skip = false; for (var j = 0; j < wrappers.length; j++) { if ($(wrappers[j]).text() == $(message).text()) { skip = true; } } if (!skip) { if (elementId !== '') { $('#' + elementId).remove(); elementId = ' id="' + elementId + '"'; } if (!emptyMessage) { informMessages.prependTrigger('<div class="' + css + '"' + elementId + '>' + message + '</div>'); // Is there a callback or callback url to request on dismiss of the inform message? if (dismissCallback) { $('div.InformWrapper:first').find('a.Close').click(eval(dismissCallback)); } else if (dismissCallbackUrl) { dismissCallbackUrl = dismissCallbackUrl.replace(/{TransientKey}/g, gdn.definition('TransientKey')); var closeAnchor = $('div.InformWrapper:first').find('a.Close'); closeAnchor.attr('callbackurl', dismissCallbackUrl); closeAnchor.click(function() { $.ajax({ type: "POST", url: $(this).attr('callbackurl'), data: 'TransientKey=' + gdn.definition('TransientKey'), dataType: 'json', error: function(XMLHttpRequest, textStatus, errorThrown) { gdn.informMessage(XMLHttpRequest.responseText, 'Dismissable AjaxError'); }, success: function(json) { gdn.inform(json); } }); }); } } } } catch (e) { } } informMessages.show(); $(document).trigger('informMessage'); return true; }; // Send an informMessage to the screen (same arguments as controller.InformMessage). gdn.informMessage = function(message, options) { if (!options) options = []; if (typeof(options) == 'string') { var css = options; options = []; options.CssClass = css; } options.Message = message; if (!options.CssClass) options.CssClass = 'Dismissable AutoDismiss'; gdn.inform({'InformMessages': new Array(options)}); }; // Inform an error returned from an ajax call. gdn.informError = function(xhr, silentAbort) { if (xhr === undefined || xhr === null) return; if (typeof(xhr) == 'string') xhr = {responseText: xhr, code: 500}; var message = xhr.responseText; var code = xhr.status; if (!message) { switch (xhr.statusText) { case 'error': if (silentAbort) return; message = 'There was an error performing your request. Please try again.'; break; case 'timeout': message = 'Your request timed out. Please try again.'; break; case 'abort': return; } } try { var data = $.parseJSON(message); if (typeof(data.Exception) == 'string') message = data.Exception; } catch (e) { } if (message === '') message = 'There was an error performing your request. Please try again.'; gdn.informMessage('<span class="InformSprite Lightbulb Error' + code + '"></span>' + message, 'HasSprite Dismissable'); }; // Pick up the inform message stack and display it on page load var informMessageStack = gdn.definition('InformMessageStack', false); if (informMessageStack) { var informMessages; try { informMessages = $.parseJSON(informMessageStack); informMessageStack = {'InformMessages': informMessages}; gdn.inform(informMessageStack); } catch (e) { console.log('informMessageStack contained invalid JSON'); } } // Ping for new notifications on pageload, and subsequently every 1 minute. var notificationsPinging = 0, pingCount = 0; var pingForNotifications = function() { if (notificationsPinging > 0 || !gdn.focused) return; notificationsPinging++; $.ajax({ type: "POST", url: gdn.url('/notifications/inform'), data: { 'TransientKey': gdn.definition('TransientKey'), 'Path': gdn.definition('Path'), 'DeliveryMethod': 'JSON', 'Count': pingCount++ }, dataType: 'json', error: function(XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest.responseText); }, success: function(json) { gdn.inform(json); }, complete: function() { notificationsPinging--; } }); }; gdn.pingForNotifications = pingForNotifications; if (gdn.definition('SignedIn', '0') != '0' && gdn.definition('DoInform', '1') != '0') { setTimeout(pingForNotifications, 3000); setInterval(pingForNotifications, 60000); } // Clear notifications alerts when they are accessed anywhere. $(document).on('click', '.js-clear-notifications', function() { $('.NotificationsAlert').remove(); }); $(document).on('change', '.js-nav-dropdown', function() { window.location = $(this).val(); }); // Stash something in the user's session (or unstash the value if it was not provided) var stash = function(name, value, callback) { $.ajax({ type: "POST", url: gdn.url('session/stash'), data: {'TransientKey': gdn.definition('TransientKey'), 'Name': name, 'Value': value}, dataType: 'json', error: function(XMLHttpRequest, textStatus, errorThrown) { gdn.informMessage(XMLHttpRequest.responseText, 'Dismissable AjaxError'); }, success: function(json) { gdn.inform(json); if (typeof(callback) === 'function') { callback(); } else { return json.Unstash; } } }); return ''; }; // When a stash anchor is clicked, look for inputs with values to stash $('a.Stash').click(function(e) { var comment = $('#Form_Comment textarea').val(), placeholder = $('#Form_Comment textarea').attr('placeholder'), stash_name; // Stash a comment: if (comment !== '' && comment !== placeholder) { var vanilla_identifier = gdn.definition('vanilla_identifier', false); if (vanilla_identifier) { // Embedded comment: stash_name = 'CommentForForeignID_' + vanilla_identifier; } else { // Non-embedded comment: stash_name = 'CommentForDiscussionID_' + gdn.definition('DiscussionID'); } var href = $(this).attr('href'); e.preventDefault(); stash(stash_name, comment, function() { window.top.location = href; }); } }); String.prototype.addCommas = function() { var nStr = this, x = nStr.split('.'), x1 = x[0], x2 = x.length > 1 ? '.' + x[1] : '', rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; }; Array.prototype.sum = function() { for (var i = 0, sum = 0; i < this.length; sum += this[i++]); return sum; }; Array.prototype.max = function() { return Math.max.apply({}, this); }; Array.prototype.min = function() { return Math.min.apply({}, this); }; if (/msie/.test(navigator.userAgent.toLowerCase())) { $('body').addClass('MSIE'); } var d = new Date(); var hourOffset = -Math.round(d.getTimezoneOffset() / 60); var tz = false; /** * ECMAScript Internationalization API is supported by all modern browsers, with the exception of Safari. We use * it here, with lots of careful checking, to attempt to fetch the user's current IANA time zone string. */ if (typeof Intl === 'object' && typeof Intl.DateTimeFormat === 'function') { var dateTimeFormat = Intl.DateTimeFormat(); if (typeof dateTimeFormat.resolvedOptions === 'function') { var resolvedOptions = dateTimeFormat.resolvedOptions(); if (typeof resolvedOptions === 'object' && typeof resolvedOptions.timeZone === 'string') { tz = resolvedOptions.timeZone; } } } // Ajax/Save the ClientHour if it is different from the value in the db. var setHourOffset = parseInt(gdn.definition('SetHourOffset', hourOffset)); var setTimeZone = gdn.definition('SetTimeZone', tz); if (hourOffset !== setHourOffset || (tz && tz !== setTimeZone)) { $.post( gdn.url('/utility/sethouroffset.json'), {HourOffset: hourOffset, TimeZone: tz, TransientKey: gdn.definition('TransientKey')} ); } // Add "checked" class to item rows if checkboxes are checked within. var checkItems = function() { var container = $(this).parents('.Item'); if ($(this).prop('checked')) $(container).addClass('Checked'); else $(container).removeClass('Checked'); }; $('.Item :checkbox').each(checkItems); $('.Item :checkbox').change(checkItems); // Hide/Reveal the "forgot your password" form if the ForgotPassword button is clicked. $(document).delegate('a.ForgotPassword', 'click', function() { // Make sure we have both forms if ($('#Form_User_SignIn').length) { $('.Methods').toggle(); $('#Form_User_Password').toggle(); $('#Form_User_SignIn').toggle(); return false; } }); // If we are not inside an iframe, focus the email input on the signin page. if ($('#Form_User_SignIn').length && window.top.location === window.location) { $('#Form_Email').focus(); } // Convert date fields to datepickers if ($.fn.datepicker) { $('input.DatePicker').datepicker({ showOn: "focus", dateFormat: 'mm/dd/yy' }); } /** * Youtube preview revealing * */ // Reveal youtube player when preview clicked. function Youtube($container) { var $preview = $container.find('.VideoPreview'); var $player = $container.find('.VideoPlayer'); $container.addClass('Open').closest('.ImgExt').addClass('Open'); var width = $preview.width(), height = $preview.height(), videoid = ''; try { videoid = $container.attr('data-youtube').replace('youtube-', ''); } catch (e) { console.log("YouTube parser found invalid id attribute: " + videoid); } // Verify we have a valid videoid var pattern = /^[\w-]+(\?autoplay\=1)(\&start=[\w-]+)?(\&rel=.)?$/; if (!pattern.test(videoid)) { return false; } var html = '<iframe width="' + width + '" height="' + height + '" src="https://www.youtube.com/embed/' + videoid + '" frameborder="0" allowfullscreen></iframe>'; $player.html(html); $preview.hide(); $player.show(); return false; } $(document).delegate('.Video.YouTube .VideoPreview', 'click', function(e) { var $target = $(e.target); var $container = $target.closest('.Video.YouTube'); return Youtube($container); }); /** * GitHub commit embedding * */ // @tim : 2013-08-24 // Experiment on hold. // if ($('div.github-commit').length) { // // Github embed library // window.GitHubCommit = (function (d,s,id) { // var t, js, fjs = d.getElementsByTagName(s)[0]; // if (d.getElementById(id)) return; js=d.createElement(s); js.id=id; // js.src=gdn.url('js/library/github.embed.js'); fjs.parentNode.insertBefore(js, fjs); // return window.GitHubCommit || (t = { _e: [], ready: function(f){ t._e.push(f) } }); // }(document, "script", "github-embd")); // // GitHubCommit.ready(function(GitHubCommit){ // setTimeout(commits, 300); // }); // } // // function commits(GitHubCommit) { // $('div.github-commit').each(function(i, el){ // var commit = $(el); // var commiturl = commit.attr('data-commiturl'); // var commituser = commit.attr('data-commituser'); // var commitrepo = commit.attr('data-commitrepo'); // var commithash = commit.attr('data-commithash'); // console.log(el); // }); // } /** * Vine image embedding * */ // Automatic, requires no JS /** * Pintrest pin embedding * */ if ($('a.pintrest-pin').length) { (function(d) { var f = d.getElementsByTagName('SCRIPT')[0], p = d.createElement('SCRIPT'); p.type = 'text/javascript'; p.async = true; p.src = '//assets.pinterest.com/js/pinit.js'; f.parentNode.insertBefore(p, f); }(document)); } /** * Textarea autosize. * * Create wrapper for autosize library, so that the custom * arguments passed do not need to be repeated for every call, if for some * reason it needs to be binded elsewhere and the UX should be identical, * otherwise just use autosize directly, passing arguments or none. * * Note: there should be no other calls to autosize, except for in this file. * All previous calls to the old jquery.autogrow were called in their * own files, which made managing this functionality less than optimal. Now * all textareas will have autosize binded to them by default. * * @depends js/library/jquery.autosize.min.js */ gdn.autosize = function(textarea) { // Check if library available. if ($.fn.autosize) { // Check if not already active on node. if (!$(textarea).hasClass('textarea-autosize')) { $(textarea).autosize({ append: '\n', resizeDelay: 20, // Keep higher than CSS transition, else creep. callback: function(el) { // This class adds the transition, and removes manual resize. $(el).addClass('textarea-autosize'); } }); // Otherwise just trigger a resize refresh. } else { $(textarea).trigger('autosize.resize'); } } }; /** * Bind autosize to relevant nodes. * * Attach autosize to all textareas. Previously this existed across multiple * files, probably as it was slowly incorporated into different areas, but * at this point it's safe to call it once here. The wrapper above makes * sure that it will not throw any errors if the library is unavailable. * * Note: if there is a textarea not autosizing, it would be good to find out * if there is another event for that exception, and if all fails, there * is the livequery fallback, which is not recommended. */ gdn.initAutosizeEvents = (function() { $('textarea').each(function(i, el) { // Attach to all immediately available textareas. gdn.autosize(el); // Also, make sure that focus on the textarea will trigger a resize, // just to cover all possibilities. $(el).on('focus', function(e) { gdn.autosize(this); }); }); // For any dynamically loaded textareas that are inserted and have an // event triggered to grab their node, or just events that should call // a resize on the textarea. Attempted to bind to `appendHtml` event, // but it required a (0ms) timeout, so it's being kept in Quotes plugin, // where it's actually triggered. var autosizeTriggers = [ 'clearCommentForm', 'popupReveal', 'contentLoad' ]; $(document).on(autosizeTriggers.join(' '), function(e, data) { data = (typeof data == 'object') ? data : ''; $(data || e.target || this).parent().find('textarea').each(function(i, el) { gdn.autosize(el); }); }); }()); // http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript String.prototype.width = function(font) { var f = font || "15px 'lucida grande','Lucida Sans Unicode',tahoma,sans-serif'", o = $('<div>' + this + '</div>') .css({ 'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f }) .appendTo($('body')), w = o.width(); o.remove(); return w; }; /** * Running magnific-popup. Image tag or text must be wrapped with an anchor * tag. This will render the content of the anchor tag's href. If using an * image tag, the anchor tag's href can point to either the same location * as the image tag, or a higher quality version of the image. If zoom is * not wanted, remove the zoom and mainClass properties, and it will just * load the content of the anchor tag with no special effects. * * @documentation http://dimsemenov.com/plugins/magnific-popup/documentation.html * */ gdn.magnificPopup = (function() { if ($.fn.magnificPopup) { $('.mfp-image').each(function(i, el) { $(el).magnificPopup({ type: 'image', mainClass: 'mfp-with-zoom', zoom: { enabled: true, duration: 300, easing: 'ease', opener: function(openerElement) { return openerElement.is('img') ? openerElement : openerElement.find('img'); } } }); }); } }()); /** * A kludge to dodge Safari's back-forward cache (bfcache). Without this, Safari maintains * the a page's DOM during back/forward navigation and hinders our ability to invalidate * the cached state of content. */ if (/Apple Computer/.test(navigator.vendor) && /Safari/.test(navigator.userAgent)) { jQuery(window).on("pageshow", function(event) { if (event.originalEvent.persisted) { window.location.reload(); } }); } $(document).trigger('contentLoad'); }); // Shrink large images to fit into message space, and pop into new window when clicked. // This needs to happen in onload because otherwise the image sizes are not yet known. jQuery(window).load(function() { /* Adds .naturalWidth() and .naturalHeight() methods to jQuery for retreaving a normalized naturalWidth and naturalHeight. // Example usage: var nWidth = $('img#example').naturalWidth(), nHeight = $('img#example').naturalHeight(); */ (function($) { var props = ['Width', 'Height'], prop; while (prop = props.pop()) { (function(natural, prop) { $.fn[natural] = (natural in new Image()) ? function() { return this[0][natural]; } : function() { var node = this[0], img, value; if (node.tagName.toLowerCase() === 'img') { img = new Image(); img.src = node.src; value = img[prop]; } return value; }; }('natural' + prop, prop.toLowerCase())); } }(jQuery)); jQuery('div.Message img') .not(jQuery('div.Message a > img')) .not(jQuery('.js-embed img')) .not(jQuery('.embedImage-img')) .each(function (i, img){ img = jQuery(img); var container = img.closest('div.Message'); if (img.naturalWidth() > container.width() && container.width() > 0) { img.wrap('<a href="' + jQuery(img).attr('src') + '" target="_blank" rel="nofollow noopener"></a>'); } }); // Let the world know we're done here jQuery(window).trigger('ImagesResized'); }); if (typeof String.prototype.trim !== 'function') { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }; } (function ($) { $.fn.extend({ // jQuery UI .effect() replacement using CSS classes. effect: function(name) { var that = this; name = name + '-effect'; return this .addClass(name) .one('animationend webkitAnimationEnd', function () { that.removeClass(name); }); }, accessibleFlyoutHandle: function (isOpen) { $(this).attr('aria-expanded', isOpen.toString()); }, accessibleFlyout: function (isOpen) { $(this).attr('aria-hidden', (!isOpen).toString()); }, setFlyoutAttributes: function () { $(this).each(function(){ var $handle = $(this).find('.FlyoutButton, .Button-Options, .Handle, .editor-action:not(.editor-action-separator)'); var $flyout = $(this).find('.Flyout, .Dropdown'); var isOpen = $flyout.is(':visible'); $handle.accessibleFlyoutHandle(isOpen); $flyout.accessibleFlyout(isOpen); }); }, accessibleFlyoutsInit: function () { var $context = $(this); $context.each(function(){ $context.find('.FlyoutButton, .Button-Options, .Handle, .editor-action:not(.editor-action-separator)').each(function (){ $(this) .attr('tabindex', '0') .attr('role', 'button') .attr('aria-haspopup', 'true'); $(this).accessibleFlyoutHandle(false); }); $context.find('.Flyout, .Dropdown').each(function (){ $(this).accessibleFlyout(false); $(this).find('a').each(function() { $(this).attr('tabindex', '0'); }); }); }); }, }); })(jQuery);<|fim▁end|>
// Add a spinner onclick of buttons with this class $(document).delegate('input.SpinOnClick', 'click', function() {
<|file_name|>singledispatch.py<|end_file_name|><|fim▁begin|>import sys<|fim▁hole|>else: from functools import singledispatch, update_wrapper def singledispatchmethod(func): dispatcher = singledispatch(func) def wrapper(*args, **kw): return dispatcher.dispatch(args[1].__class__)(*args, **kw) wrapper.register = dispatcher.register update_wrapper(wrapper, func) return wrapper<|fim▁end|>
if sys.version_info >= (3, 8): from functools import singledispatchmethod
<|file_name|>trim.ts<|end_file_name|><|fim▁begin|>/// <reference path="./interface.ts" /> /// <reference path="../canvas.ts" /> /// <reference path="../../../controller/controller.ts" /> module Prisc { export class TrimTool implements Tool { private start: ICoordinates; private end: ICoordinates; private lineWidth: number = 0.5; private strokeStyle: string = '#AAA'; constructor(private canvas: Canvas) {} onStart(ev) { this.start = { x: ev.offsetX, y: ev.offsetY }; } onMove(ev) { this.rollback(); this.end = { x: ev.offsetX, y: ev.offsetY }; this.draw(); } onFinish(ev) { this.end = { x: ev.offsetX,<|fim▁hole|> this.rollback(); var imageURI = this.getTrimmedImageURI(); Controller.openCaptureViewByMessagingUrl(imageURI); } private rollback() { this.canvas.__context.putImageData( this.canvas.stashedImageData,0,0 ); } private draw() { // 切り取り描画のときだけ this.canvas.__context.lineWidth = this.lineWidth; this.canvas.__context.strokeStyle = this.strokeStyle; this.canvas.__context.strokeRect( this.start.x, this.start.y, this.end.x - this.start.x, this.end.y - this.start.y ); } private getTrimmedImageURI(): string { var partialData = this.canvas.__context.getImageData( this.start.x, this.start.y, this.end.x - this.start.x, this.end.y - this.start.y ); // 一時的にキャンバスを作る var _tmpCanvas = document.createElement('canvas'); _tmpCanvas.width = partialData.width; _tmpCanvas.height = partialData.height; var _tmpContext = _tmpCanvas.getContext('2d'); _tmpContext.putImageData(partialData, 0, 0); // FIXME: とりあえずハード var format = 'image/png'; var imageURI = _tmpCanvas.toDataURL(format); return imageURI; } } }<|fim▁end|>
y: ev.offsetY };
<|file_name|>DelegateCalendarAccountUserDetailsImpl.java<|end_file_name|><|fim▁begin|>/** * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a * copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jasig.schedassist.web.security; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.jasig.schedassist.impl.owner.NotRegisteredException; import org.jasig.schedassist.model.ICalendarAccount; import org.jasig.schedassist.model.IDelegateCalendarAccount; import org.jasig.schedassist.model.IScheduleOwner; import org.springframework.security.core.GrantedAuthority; /** <|fim▁hole|> * * @author Nicholas Blair, [email protected] * @version $Id: DelegateCalendarAccountUserDetailsImpl.java 2306 2010-07-28 17:20:12Z npblair $ */ public class DelegateCalendarAccountUserDetailsImpl implements CalendarAccountUserDetails { /** * */ private static final long serialVersionUID = 53706L; private static final String EMPTY = ""; private final IDelegateCalendarAccount delegateCalendarAccount; private IScheduleOwner scheduleOwner; /** * * @param delegateCalendarAccount */ public DelegateCalendarAccountUserDetailsImpl(IDelegateCalendarAccount delegateCalendarAccount) { this(delegateCalendarAccount, null); } /** * @param delegateCalendarAccount * @param delegateScheduleOwner */ public DelegateCalendarAccountUserDetailsImpl( IDelegateCalendarAccount delegateCalendarAccount, IScheduleOwner delegateScheduleOwner) { this.delegateCalendarAccount = delegateCalendarAccount; this.scheduleOwner = delegateScheduleOwner; } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#getAuthorities() */ public Collection<GrantedAuthority> getAuthorities() { List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); if(null != this.delegateCalendarAccount && this.delegateCalendarAccount.isEligible()) { authorities.add(SecurityConstants.DELEGATE_REGISTER); } if(null != this.scheduleOwner) { authorities.add(SecurityConstants.DELEGATE_OWNER); authorities.remove(SecurityConstants.DELEGATE_REGISTER); } return Collections.unmodifiableList(authorities); } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#getPassword() */ public String getPassword() { return EMPTY; } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#getUsername() */ public String getUsername() { return this.delegateCalendarAccount.getUsername(); } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#isAccountNonExpired() */ public boolean isAccountNonExpired() { return true; } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#isAccountNonLocked() */ public boolean isAccountNonLocked() { return true; } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#isCredentialsNonExpired() */ public boolean isCredentialsNonExpired() { return true; } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#isEnabled() */ public boolean isEnabled() { return null != this.delegateCalendarAccount ? this.delegateCalendarAccount.isEligible() : false; } /* * (non-Javadoc) * @see org.jasig.schedassist.web.security.CalendarAccountUserDetails#getActiveDisplayName() */ public String getActiveDisplayName() { StringBuilder display = new StringBuilder(); display.append(this.delegateCalendarAccount.getDisplayName()); display.append(" (managed by "); display.append(this.delegateCalendarAccount.getAccountOwner().getUsername()); display.append(")"); return display.toString(); } /* * (non-Javadoc) * @see org.jasig.schedassist.web.security.CalendarAccountUserDetails#getCalendarAccount() */ @Override public ICalendarAccount getCalendarAccount() { return getDelegateCalendarAccount(); } /** * * @return the {@link IDelegateCalendarAccount} */ public IDelegateCalendarAccount getDelegateCalendarAccount() { return this.delegateCalendarAccount; } /* * (non-Javadoc) * @see org.jasig.schedassist.web.security.CalendarAccountUserDetails#getScheduleOwner() */ @Override public IScheduleOwner getScheduleOwner() throws NotRegisteredException { if(null == this.scheduleOwner) { throw new NotRegisteredException(this.delegateCalendarAccount + " is not registered"); } else { return this.scheduleOwner; } } /* * (non-Javadoc) * @see org.jasig.schedassist.web.security.CalendarAccountUserDetails#isDelegate() */ @Override public final boolean isDelegate() { return true; } /* * (non-Javadoc) * @see org.jasig.schedassist.web.security.CalendarAccountUserDetails#updateScheduleOwner(org.jasig.schedassist.model.IScheduleOwner) */ @Override public void updateScheduleOwner(IScheduleOwner owner) { this.scheduleOwner = owner; } }<|fim▁end|>
* {@link CalendarAccountUserDetails} implementation for {@link IDelegateCalendarAccount}s.
<|file_name|>test_avg.py<|end_file_name|><|fim▁begin|>from .test_antivirus import AbstractTests import modules.antivirus.avg.avg as module import modules.antivirus.base as base from mock import patch from pathlib import Path class TestAvg(AbstractTests.TestAntivirus): name = "AVG AntiVirus Free (Linux)" scan_path = Path("/usr/bin/avgscan") scan_args = ('--heur', '--paranoid', '--arc', '--macrow', '--pwdw', '--pup') module = module.AVGAntiVirusFree scan_clean_stdout = """AVG command line Anti-Virus scanner Copyright (c) 2013 AVG Technologies CZ Virus database version: 4793/15678 Virus database release date: Mon, 21 May 2018 13:00:00 +0000 Files scanned : 1(1) Infections found : 0(0) PUPs found : 0 Files healed : 0 Warnings reported : 0 Errors reported : 0 """ scan_virus_retcode = 4 virusname = "EICAR_Test" scan_virus_stdout = """AVG command line Anti-Virus scanner Copyright (c) 2013 AVG Technologies CZ Virus database version: 4793/15678 Virus database release date: Mon, 21 May 2018 13:00:00 +0000 eicar.com.txt Virus identified EICAR_Test Files scanned : 1(1) Infections found : 1(1) PUPs found : 0 Files healed : 0 Warnings reported : 0 Errors reported : 0 """ version = "13.0.3118" virus_database_version = "4793/15678 (21 May 2018)" version_stdout = """AVG command line controller Copyright (c) 2013 AVG Technologies CZ ------ AVG status ------ AVG version : 13.0.3118 Components version : Aspam:3111, Cfg:3109, Cli:3115, Common:3110, Core:4793, Doc:3115, Ems:3111, Initd:3113, Lng:3112, Oad:3118, Other:3109, Scan:3115, Sched:3110, Update:3109 Last update : Tue, 22 May 2018 07:52:31 +0000 ------ License status ------ License number : LUOTY-674PL-VRWOV-APYEG-ZXHMA-E License version : 10 License type : FREE License expires on : Registered user : Registered company : ------ WD status ------ Component State Restarts UpTime Avid running 0 13 minute(s) Oad running 0 13 minute(s) Sched running 0 13 minute(s) Tcpd running 0 13 minute(s) Update stopped 0 - ------ Sched status ------ Task name Next runtime Last runtime Virus update Tue, 22 May 2018 18:04:00 +0000 Tue, 22 May 2018 07:46:29 +0000 Program update - - User counting Wed, 23 May 2018 07:46:29 +0000 Tue, 22 May 2018 07:46:29 +0000 ------ Tcpd status ------ E-mails checked : 0 SPAM messages : 0 Phishing messages : 0 E-mails infected : 0 E-mails dropped : 0 ------ Avid status ------ Virus database reload times : 0 Virus database version : 4793/15678 Virus database release date : Mon, 21 May 2018 13:00:00 +0000 Virus database shared in memory : yes ------ Oad status ------ Files scanned : 0(0) Infections found : 0(0) PUPs found : 0 Files healed : 0 Warnings reported : 0 Errors reported : 0 Operation successful. """ # nopep8 @patch.object(base.AntivirusUnix, "locate") @patch.object(base.AntivirusUnix, "locate_one") @patch.object(base.AntivirusUnix, "run_cmd") def setUp(self, m_run_cmd, m_locate_one, m_locate): m_run_cmd.return_value = 0, self.version_stdout, "" m_locate_one.return_value = self.scan_path m_locate.return_value = self.database super().setUp() @patch.object(module, "locate_one") @patch.object(base.AntivirusUnix, "run_cmd") def test_get_virus_db_error(self, m_run_cmd, m_locate_one): m_locate_one.return_value = self.scan_path m_run_cmd.return_value = -1, self.version_stdout, "" with self.assertRaises(RuntimeError): self.plugin.get_virus_database_version() @patch.object(module, "locate_one") @patch.object(base.AntivirusUnix, "run_cmd") def test_get_virus_db_no_version(self, m_run_cmd, m_locate_one): m_locate_one.return_value = self.scan_path wrong_stdout = "LOREM IPSUM" m_run_cmd.return_value = 0, wrong_stdout, "" with self.assertRaises(RuntimeError): self.plugin.get_virus_database_version() @patch.object(module, "locate_one") @patch.object(base.AntivirusUnix, "run_cmd") def test_get_virus_db_no_release(self, m_run_cmd, m_locate_one): m_locate_one.return_value = self.scan_path<|fim▁hole|> m_run_cmd.return_value = 0, wrong_stdout, "" version = self.plugin.get_virus_database_version() self.assertEquals(version, "4793/15678")<|fim▁end|>
wrong_stdout = "Virus database version : 4793/15678"
<|file_name|>index.js<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
console.log('Hello World!');
<|file_name|>keyboard.rs<|end_file_name|><|fim▁begin|>use std::collections::{HashMap, VecDeque}; use std::time::Duration; use libusb::{Result as UsbResult, Error as UsbError}; use nix::sys::signal::{SigAction, sigaction, SaFlags, SigSet, SigHandler, SIGINT, SIGTERM};<|fim▁hole|>use nix::Result as NixResult; use handle::{Handle, ControlPacket, ToControlPacket}; use color::*; use keys::*; use parser::*; use event::{GenericHandler, Handler}; pub trait Keyboard { fn set_key_colors(&mut self, key_colors: Vec<KeyColor>) -> UsbResult<()>; fn set_color(&mut self, key_color: KeyColor) -> UsbResult<()>; fn set_all_colors(&mut self, color: Color) -> UsbResult<()>; fn set_reconnect_interval(&mut self, interval: Duration); fn set_reconnect_attempts(&mut self, attempts: i32); fn set_auto_reconnect(&mut self, enabled: bool); fn reconnect(&mut self) -> UsbResult<()>; unsafe fn enable_signal_handling(&mut self) -> NixResult<()>; fn disable_signal_handling(&mut self) -> NixResult<()>; } pub struct KeyboardInternal { handle: Handle, control_packet_queue: VecDeque<ControlPacket>, sending_control: bool, reconnect_interval: Duration, reconnect_attempts: i32, auto_reconnect: bool, } impl KeyboardInternal { pub fn new() -> UsbResult<KeyboardInternal> { let handle = try!(Handle::new()); Ok(KeyboardInternal { handle: handle, control_packet_queue: VecDeque::new(), sending_control: false, reconnect_interval: Duration::from_secs(1), reconnect_attempts: 10, auto_reconnect: true, }) } pub fn queue_control_packet(&mut self, packet: ControlPacket) -> UsbResult<()> { self.control_packet_queue.push_back(packet); if !self.sending_control { self.send_next_control() } else { Ok(()) } } pub fn send_next_control(&mut self) -> UsbResult<()> { if self.control_packet_queue.len() == 0 { self.sending_control = false; return Ok(()); } if !self.sending_control { self.sending_control = true; } self.handle.send_control(self.control_packet_queue.pop_front().unwrap()) } fn send_color<T: KeyType>(&mut self, color_packet: ColorPacket<T>) -> UsbResult<()> { self.queue_control_packet(color_packet.to_control_packet()) } fn flush_color(&mut self) -> UsbResult<()> { self.queue_control_packet(FlushPacket::new().to_control_packet()) } } impl Keyboard for KeyboardInternal { fn set_key_colors(&mut self, key_colors: Vec<KeyColor>) -> UsbResult<()> { let mut standard_packet = ColorPacket::new(); let mut gaming_packet = ColorPacket::new(); let mut logo_packet = ColorPacket::new(); for key_color in key_colors { match key_color.key { Key::Standard(s) => { match standard_packet.add(s, key_color.color) { Some(p) => try!(self.send_color(p)), None => {} } }, Key::Gaming(g) => { match gaming_packet.add(g, key_color.color) { Some(p) => try!(self.send_color(p)), None => {} } }, Key::Logo(l) => { match logo_packet.add(l, key_color.color) { Some(p) => try!(self.send_color(p)), None => {} } }, Key::Media(_) => return Err(UsbError::InvalidParam) } } if standard_packet.len() > 0 { try!(self.send_color(standard_packet)); } if gaming_packet.len() > 0 { try!(self.send_color(gaming_packet)); } if logo_packet.len() > 0 { try!(self.send_color(logo_packet)); } self.flush_color() } fn set_color(&mut self, key_color: KeyColor) -> UsbResult<()> { let key_colors = vec![key_color]; self.set_key_colors(key_colors) } fn set_all_colors(&mut self, color: Color) -> UsbResult<()> { let mut values = Key::values(); let key_colors = values.drain(..) .filter(|k| match k { // we can't set the color of media keys &Key::Media(_) => false, _ => true }).map(|k| KeyColor::new(k, color.clone())) .collect(); self.set_key_colors(key_colors) } fn set_reconnect_interval(&mut self, interval: Duration) { self.reconnect_interval = interval; } fn set_reconnect_attempts(&mut self, attempts: i32) { self.reconnect_attempts = attempts; } fn set_auto_reconnect(&mut self, enabled: bool) { self.auto_reconnect = enabled; } fn reconnect(&mut self) -> UsbResult<()> { println!("Connection lost. Starting reconnect..."); let mut last_err = UsbError::NoDevice; for _ in 0..self.reconnect_attempts { match self.handle.reconnect() { Ok(_) => { println!("Reconnected"); return Ok(()); }, Err(e) => { println!("Reconnecting failed: {:?}", e); last_err = e; } } ::std::thread::sleep(self.reconnect_interval); } Err(last_err) } unsafe fn enable_signal_handling(&mut self) -> NixResult<()> { let sig_action = SigAction::new(SigHandler::Handler(panic_on_sig), SaFlags::empty(), SigSet::empty()); try!(sigaction(SIGINT, &sig_action).map(|_| ())); sigaction(SIGTERM, &sig_action).map(|_| ()) } fn disable_signal_handling(&mut self) -> NixResult<()> { let sig_action = SigAction::new(SigHandler::Handler(exit_on_sig), SaFlags::empty(), SigSet::empty()); unsafe { try!(sigaction(SIGINT, &sig_action).map(|_| ())); sigaction(SIGTERM, &sig_action).map(|_| ()) } } } extern fn panic_on_sig(_: i32) { panic!("Got Sigint: Panicking to drop UsbWrapper to reattach kernel driver"); } extern fn exit_on_sig(_: i32) { ::std::process::exit(1); } pub struct KeyboardImpl { keyboard_internal: KeyboardInternal, parser_index: u32, parsers: HashMap<u32, Parser>, handler_index: u32, handlers: HashMap<u32, Box<GenericHandler>>, } impl KeyboardImpl { pub fn new() -> UsbResult<KeyboardImpl> { let mut keyboard = KeyboardImpl { keyboard_internal: try!(KeyboardInternal::new()), parser_index: 0, parsers: HashMap::new(), handler_index: 0, handlers: HashMap::new(), }; keyboard.add_parser(KeyParser::new().into()); keyboard.add_parser(ControlParser::new().into()); Ok(keyboard) } pub fn add_handler(&mut self, handler: Handler) -> u32 { let index = self.handler_index; self.handlers.insert(index, handler.into()); self.handler_index += 1; index } pub fn remove_handler(&mut self, index: u32) -> Option<Box<GenericHandler>> { self.handlers.remove(&index) } fn add_parser(&mut self, parser: Parser) -> u32 { let index = self.parser_index; self.parsers.insert(index, parser); self.parser_index += 1; index } // FIXME: Currently unused, but maybe needed later //fn remove_parser(&mut self, index: u32) -> Option<Parser> { //self.parsers.remove(&index) //} fn handle(&mut self) -> UsbResult<()> { let &mut KeyboardImpl { ref mut keyboard_internal, parser_index: _, ref mut parsers, handler_index: _, ref mut handlers, } = self; let endpoint_direction; let buf; loop { let timeout = match handlers.iter().filter_map(|(_,h)| h.sleep_duration()).min() { Some(d) => d, None => Duration::from_secs(3600*24*365) }; let res = keyboard_internal.handle.recv(timeout); match res { Some(Ok((e, b))) => { endpoint_direction = e; buf = b; break }, Some(Err(err)) => return Err(err), None => { for handler in handlers.iter_mut().filter_map(|(_,h)| match h.sleep_duration() { Some(dur) if dur == Duration::from_secs(0) => Some(h), _ => None }) { try!(handler.handle_time(keyboard_internal)); } } } } let packet = Packet::new(endpoint_direction, &buf); let mut handled = false; let mut parsed = false; for (_, parser) in parsers.iter_mut() { match parser { &mut Parser::ParseKey(ref mut p) if p.accept(&packet) => { parsed = true; let key_events = try!(p.parse(&packet, keyboard_internal)); for key_event in key_events { for (_, handler) in handlers.iter_mut() { if handler.accept_key(&key_event) { handled = true; try!(handler.handle_key(&key_event, keyboard_internal)); } } } }, &mut Parser::ParseControl(ref mut p) if p.accept(&packet) => { parsed = true; handled = true; try!(p.parse(&packet, keyboard_internal)); }, _ => {} } } if !parsed { println!("Packet not parsed: {:?}", packet); } else if !handled { println!("Packet not handled: {:?}", packet); } Ok(()) } pub fn start_handle_loop(&mut self) -> UsbResult<()> { // init handlers { let &mut KeyboardImpl { ref mut keyboard_internal, parser_index: _, parsers: _, handler_index: _, ref mut handlers, } = self; for (_, handler) in handlers { try!(handler.init(keyboard_internal)); } } loop { match self.handle() { Ok(()) => {}, Err(UsbError::NoDevice) | Err(UsbError::Io) | Err(UsbError::Busy) => try!(self.reconnect()), Err(e) => return Err(e), } } } } impl Keyboard for KeyboardImpl { fn set_key_colors(&mut self, key_colors: Vec<KeyColor>) -> UsbResult<()> { self.keyboard_internal.set_key_colors(key_colors) } fn set_color(&mut self, key_color: KeyColor) -> UsbResult<()> { self.keyboard_internal.set_color(key_color) } fn set_all_colors(&mut self, color: Color) -> UsbResult<()> { self.keyboard_internal.set_all_colors(color) } fn set_reconnect_interval(&mut self, interval: Duration) { self.keyboard_internal.set_reconnect_interval(interval) } fn set_reconnect_attempts(&mut self, attempts: i32) { self.keyboard_internal.set_reconnect_attempts(attempts) } fn set_auto_reconnect(&mut self, enabled: bool) { self.keyboard_internal.set_auto_reconnect(enabled) } fn reconnect(&mut self) -> UsbResult<()> { self.keyboard_internal.reconnect() } unsafe fn enable_signal_handling(&mut self) -> NixResult<()> { self.keyboard_internal.enable_signal_handling() } fn disable_signal_handling(&mut self) -> NixResult<()> { self.keyboard_internal.disable_signal_handling() } }<|fim▁end|>
<|file_name|>system_identification.py<|end_file_name|><|fim▁begin|>from grslra import testdata from grslra.grslra_batch import grslra_batch, slra_by_factorization from grslra.structures import Hankel from grslra.scaling import Scaling import numpy as np import time # The goal of this experiment is to identify an LTI system from a noisy outlier-contaminated and subsampled observation of its impulse response PROFILE = 0 if PROFILE: import cProfile N = 80 m = 20 k = 5 sigma=0.05 outlier_rate = 0.05 outlier_amplitude = 1 rate_Omega=0.5 N_f = 20 scaling = Scaling(centering=True) p = 0.1 x, x_0, U, Y = testdata.testdata_lti_outliers(N + N_f, m, k, rho=outlier_rate, amplitude=outlier_amplitude, sigma=sigma) # determine scaling factor scaling.scale_reference(x) mu = (1-p) * (3 * sigma / scaling.factor) ** 2 # draw sampling set card_Omega = np.int(np.round(rate_Omega * N)) Omega = np.random.choice(N, card_Omega, replace=False) # create binary support vectors for Omega and Omega_not entries = np.zeros((N + N_f, )) entries[Omega] = 1 entries_not = np.ones_like(entries) - entries # set unobserved entries in x to zero x *= entries x_Omega = x[Omega] n = N + N_f - m + 1 hankel = Hankel(m, n) grslra_params = {"PRINT": None, "VERBOSE": 1}<|fim▁hole|> t_start = time.time() l_grslra, U, Y = grslra_batch(x_Omega, hankel, k, p, mu, params=grslra_params, Omega=Omega, x_0=x_0, scaling=scaling) t_grslra = time.time() - t_start if PROFILE: profile.disable() profile.dump_stats("grslra.bin") print "error GRSLRA: ", np.linalg.norm(l_grslra - x_0) / np.linalg.norm(x_0) print "time GRSLRA: ", t_grslra if PROFILE: profile = cProfile.Profile() profile.enable() t_start = time.time() l_slrabyF = slra_by_factorization(x_Omega, m, k, PRINT=0, x_0=x_0, Omega=Omega, N=N + N_f) t_slrabyf = time.time() - t_start if PROFILE: profile.disable() profile.dump_stats("slrabyf.bin") print "error SLRA by F: ", np.linalg.norm(l_slrabyF - x_0) / np.linalg.norm(x_0) print "time SLRA by F: ", t_slrabyf np.savez('result_sysid_lti.npz', x_Omega=x_Omega, Omega=Omega, x_0=x_0, t_grslra=t_grslra, l_grslra=l_grslra, t_slrabyf=t_slrabyf, l_slrabyF=l_slrabyF)<|fim▁end|>
if PROFILE: profile = cProfile.Profile() profile.enable()
<|file_name|>SectionTitle.tsx<|end_file_name|><|fim▁begin|>import { ReactElement } from "react"; import Heading from "components/Heading"; import styles from "./PackageSassDoc.module.scss"; export interface SectionTitleProps { packageName: string; type: "Variables" | "Functions" | "Mixins"; } export default function SectionTitle({ packageName, type, }: SectionTitleProps): ReactElement {<|fim▁hole|> <Heading id={`${packageName}-${type.toLowerCase()}`} level={1} className={styles.title} > {type} </Heading> ); }<|fim▁end|>
return (
<|file_name|>omnicoinamountfield.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) 2011-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "omnicoinamountfield.h" #include "omnicoinunits.h" #include "guiconstants.h" #include "qvaluecombobox.h" #include <QApplication> #include <QAbstractSpinBox> #include <QHBoxLayout> #include <QKeyEvent> #include <QLineEdit> /** QSpinBox that uses fixed-point numbers internally and uses our own * formatting/parsing functions.<|fim▁hole|> Q_OBJECT public: explicit AmountSpinBox(QWidget *parent): QAbstractSpinBox(parent), currentUnit(OmnicoinUnits::OMC), singleStep(100000) // satoshis { setAlignment(Qt::AlignRight); connect(lineEdit(), SIGNAL(textEdited(QString)), this, SIGNAL(valueChanged())); } QValidator::State validate(QString &text, int &pos) const { if(text.isEmpty()) return QValidator::Intermediate; bool valid = false; parse(text, &valid); /* Make sure we return Intermediate so that fixup() is called on defocus */ return valid ? QValidator::Intermediate : QValidator::Invalid; } void fixup(QString &input) const { bool valid = false; CAmount val = parse(input, &valid); if(valid) { input = OmnicoinUnits::format(currentUnit, val, false, OmnicoinUnits::separatorAlways); lineEdit()->setText(input); } } CAmount value(bool *valid_out=0) const { return parse(text(), valid_out); } void setValue(const CAmount& value) { lineEdit()->setText(OmnicoinUnits::format(currentUnit, value, false, OmnicoinUnits::separatorAlways)); Q_EMIT valueChanged(); } void stepBy(int steps) { bool valid = false; CAmount val = value(&valid); val = val + steps * singleStep; val = qMin(qMax(val, CAmount(0)), OmnicoinUnits::maxMoney()); setValue(val); } void setDisplayUnit(int unit) { bool valid = false; CAmount val = value(&valid); currentUnit = unit; if(valid) setValue(val); else clear(); } void setSingleStep(const CAmount& step) { singleStep = step; } QSize minimumSizeHint() const { if(cachedMinimumSizeHint.isEmpty()) { ensurePolished(); const QFontMetrics fm(fontMetrics()); int h = lineEdit()->minimumSizeHint().height(); int w = fm.width(OmnicoinUnits::format(OmnicoinUnits::OMC, OmnicoinUnits::maxMoney(), false, OmnicoinUnits::separatorAlways)); w += 2; // cursor blinking space QStyleOptionSpinBox opt; initStyleOption(&opt); QSize hint(w, h); QSize extra(35, 6); opt.rect.setSize(hint + extra); extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxEditField, this).size(); // get closer to final result by repeating the calculation opt.rect.setSize(hint + extra); extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxEditField, this).size(); hint += extra; hint.setHeight(h); opt.rect = rect(); cachedMinimumSizeHint = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this) .expandedTo(QApplication::globalStrut()); } return cachedMinimumSizeHint; } private: int currentUnit; CAmount singleStep; mutable QSize cachedMinimumSizeHint; /** * Parse a string into a number of base monetary units and * return validity. * @note Must return 0 if !valid. */ CAmount parse(const QString &text, bool *valid_out=0) const { CAmount val = 0; bool valid = OmnicoinUnits::parse(currentUnit, text, &val); if(valid) { if(val < 0 || val > OmnicoinUnits::maxMoney()) valid = false; } if(valid_out) *valid_out = valid; return valid ? val : 0; } protected: bool event(QEvent *event) { if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Comma) { // Translate a comma into a period QKeyEvent periodKeyEvent(event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count()); return QAbstractSpinBox::event(&periodKeyEvent); } } return QAbstractSpinBox::event(event); } StepEnabled stepEnabled() const { if (isReadOnly()) // Disable steps when AmountSpinBox is read-only return StepNone; if (text().isEmpty()) // Allow step-up with empty field return StepUpEnabled; StepEnabled rv = 0; bool valid = false; CAmount val = value(&valid); if(valid) { if(val > 0) rv |= StepDownEnabled; if(val < OmnicoinUnits::maxMoney()) rv |= StepUpEnabled; } return rv; } Q_SIGNALS: void valueChanged(); }; #include "omnicoinamountfield.moc" OmnicoinAmountField::OmnicoinAmountField(QWidget *parent) : QWidget(parent), amount(0) { amount = new AmountSpinBox(this); amount->setLocale(QLocale::c()); amount->installEventFilter(this); amount->setMaximumWidth(170); QHBoxLayout *layout = new QHBoxLayout(this); layout->addWidget(amount); unit = new QValueComboBox(this); unit->setModel(new OmnicoinUnits(this)); layout->addWidget(unit); layout->addStretch(1); layout->setContentsMargins(0,0,0,0); setLayout(layout); setFocusPolicy(Qt::TabFocus); setFocusProxy(amount); // If one if the widgets changes, the combined content changes as well connect(amount, SIGNAL(valueChanged()), this, SIGNAL(valueChanged())); connect(unit, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int))); // Set default based on configuration unitChanged(unit->currentIndex()); } void OmnicoinAmountField::clear() { amount->clear(); unit->setCurrentIndex(0); } void OmnicoinAmountField::setEnabled(bool fEnabled) { amount->setEnabled(fEnabled); unit->setEnabled(fEnabled); } bool OmnicoinAmountField::validate() { bool valid = false; value(&valid); setValid(valid); return valid; } void OmnicoinAmountField::setValid(bool valid) { if (valid) amount->setStyleSheet(""); else amount->setStyleSheet(STYLE_INVALID); } bool OmnicoinAmountField::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::FocusIn) { // Clear invalid flag on focus setValid(true); } return QWidget::eventFilter(object, event); } QWidget *OmnicoinAmountField::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, amount); QWidget::setTabOrder(amount, unit); return unit; } CAmount OmnicoinAmountField::value(bool *valid_out) const { return amount->value(valid_out); } void OmnicoinAmountField::setValue(const CAmount& value) { amount->setValue(value); } void OmnicoinAmountField::setReadOnly(bool fReadOnly) { amount->setReadOnly(fReadOnly); } void OmnicoinAmountField::unitChanged(int idx) { // Use description tooltip for current unit for the combobox unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString()); // Determine new unit ID int newUnit = unit->itemData(idx, OmnicoinUnits::UnitRole).toInt(); amount->setDisplayUnit(newUnit); } void OmnicoinAmountField::setDisplayUnit(int newUnit) { unit->setValue(newUnit); } void OmnicoinAmountField::setSingleStep(const CAmount& step) { amount->setSingleStep(step); }<|fim▁end|>
*/ class AmountSpinBox: public QAbstractSpinBox {
<|file_name|>servicecontrol_v1_generated_service_controller_check_async.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright 2022 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 # # 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. #<|fim▁hole|># It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-service-control # [START servicecontrol_v1_generated_ServiceController_Check_async] from google.cloud import servicecontrol_v1 async def sample_check(): # Create a client client = servicecontrol_v1.ServiceControllerAsyncClient() # Initialize request argument(s) request = servicecontrol_v1.CheckRequest( ) # Make the request response = await client.check(request=request) # Handle the response print(response) # [END servicecontrol_v1_generated_ServiceController_Check_async]<|fim▁end|>
# Generated code. DO NOT EDIT! # # Snippet for Check # NOTE: This snippet has been automatically generated for illustrative purposes only.
<|file_name|>0016_negative_votes.py<|end_file_name|><|fim▁begin|># Generated by Django 2.2.15 on 2020-11-24 06:44 from decimal import Decimal import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("assignments", "0015_assignmentvote_delegated_user"), ] operations = [ migrations.AddField( model_name="assignmentpoll", name="db_amount_global_yes", field=models.DecimalField( blank=True, decimal_places=6, default=Decimal("0"), max_digits=15, null=True, validators=[django.core.validators.MinValueValidator(Decimal("-2"))], ), ), migrations.AddField( model_name="assignmentpoll", name="global_yes", field=models.BooleanField(default=True), ), migrations.AlterField( model_name="assignmentpoll", name="pollmethod", field=models.CharField( choices=[ ("votes", "Yes per candidate"), ("N", "No per candidate"), ("YN", "Yes/No per candidate"), ("YNA", "Yes/No/Abstain per candidate"), ], max_length=5, ), ), migrations.AlterField( model_name="assignmentpoll", name="onehundred_percent_base", field=models.CharField( choices=[ ("YN", "Yes/No per candidate"), ("YNA", "Yes/No/Abstain per candidate"), ("Y", "Sum of votes including general No/Abstain"), ("valid", "All valid ballots"), ("cast", "All casted ballots"), ("disabled", "Disabled (no percents)"), ], max_length=8, ), ), migrations.AlterField( model_name="assignmentpoll", name="pollmethod", field=models.CharField( choices=[ ("Y", "Yes per candidate"),<|fim▁hole|> ], max_length=5, ), ), ]<|fim▁end|>
("N", "No per candidate"), ("YN", "Yes/No per candidate"), ("YNA", "Yes/No/Abstain per candidate"),
<|file_name|>livecd.py<|end_file_name|><|fim▁begin|># # livecd.py: An anaconda backend to do an install from a live CD image # # The basic idea is that with a live CD, we already have an install # and should be able to just copy those bits over to the disk. So we dd # the image, move things to the "right" filesystem as needed, and then # resize the rootfs to the size of its container. # # Copyright (C) 2007 Red Hat, Inc. All rights reserved. # # 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, see <http://www.gnu.org/licenses/>. # # Author(s): Jeremy Katz <[email protected]> # import os, sys import stat import shutil import time import subprocess import storage import selinux from flags import flags from constants import * import gettext _ = lambda x: gettext.ldgettext("anaconda", x) import backend import isys import iutil import packages import logging log = logging.getLogger("anaconda") class Error(EnvironmentError): pass def copytree(src, dst, symlinks=False, preserveOwner=False, preserveSelinux=False): def tryChown(src, dest): try: os.chown(dest, os.stat(src)[stat.ST_UID], os.stat(src)[stat.ST_GID]) except OverflowError: log.error("Could not set owner and group on file %s" % dest) def trySetfilecon(src, dest): try: selinux.lsetfilecon(dest, selinux.lgetfilecon(src)[1]) except: log.error("Could not set selinux context on file %s" % dest) # copy of shutil.copytree which doesn't require dst to not exist # and which also has options to preserve the owner and selinux contexts names = os.listdir(src) if not os.path.isdir(dst): os.makedirs(dst) errors = [] for name in names: srcname = os.path.join(src, name)<|fim▁hole|> if symlinks and os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) if preserveSelinux: trySetfilecon(srcname, dstname) elif os.path.isdir(srcname): copytree(srcname, dstname, symlinks, preserveOwner, preserveSelinux) else: shutil.copyfile(srcname, dstname) if preserveOwner: tryChown(srcname, dstname) if preserveSelinux: trySetfilecon(srcname, dstname) shutil.copystat(srcname, dstname) except (IOError, os.error), why: errors.append((srcname, dstname, str(why))) # catch the Error from the recursive copytree so that we can # continue with other files except Error, err: errors.extend(err.args[0]) try: if preserveOwner: tryChown(src, dst) if preserveSelinux: trySetfilecon(src, dst) shutil.copystat(src, dst) except OSError as e: errors.extend((src, dst, e.strerror)) if errors: raise Error, errors class LiveCDCopyBackend(backend.AnacondaBackend): def __init__(self, anaconda): backend.AnacondaBackend.__init__(self, anaconda) flags.livecdInstall = True self.supportsUpgrades = False self.supportsPackageSelection = False self.skipFormatRoot = True self.osimg = anaconda.methodstr[8:] if not stat.S_ISBLK(os.stat(self.osimg)[stat.ST_MODE]): anaconda.intf.messageWindow(_("Unable to find image"), _("The given location isn't a valid %s " "live CD to use as an installation source.") %(productName,), type = "custom", custom_icon="error", custom_buttons=[_("Exit installer")]) sys.exit(0) self.rootFsType = isys.readFSType(self.osimg) def _getLiveBlockDevice(self): return os.path.normpath(self.osimg) def _getLiveSize(self): def parseField(output, field): for line in output.split("\n"): if line.startswith(field + ":"): return line[len(field) + 1:].strip() raise KeyError("Failed to find field '%s' in output" % field) output = subprocess.Popen(['/sbin/dumpe2fs', '-h', self.osimg], stdout=subprocess.PIPE, stderr=open('/dev/null', 'w') ).communicate()[0] blkcnt = int(parseField(output, "Block count")) blksize = int(parseField(output, "Block size")) return blkcnt * blksize def _getLiveSizeMB(self): return self._getLiveSize() / 1048576 def _unmountNonFstabDirs(self, anaconda): # unmount things that aren't listed in /etc/fstab. *sigh* dirs = [] if flags.selinux: dirs.append("/selinux") for dir in dirs: try: isys.umount("%s/%s" %(anaconda.rootPath,dir), removeDir = False) except Exception, e: log.error("unable to unmount %s: %s" %(dir, e)) def postAction(self, anaconda): self._unmountNonFstabDirs(anaconda) try: anaconda.id.storage.umountFilesystems(swapoff = False) os.rmdir(anaconda.rootPath) except Exception, e: log.error("Unable to unmount filesystems: %s" % e) def doPreInstall(self, anaconda): if anaconda.dir == DISPATCH_BACK: self._unmountNonFstabDirs(anaconda) return anaconda.id.storage.umountFilesystems(swapoff = False) def doInstall(self, anaconda): log.info("Preparing to install packages") progress = anaconda.id.instProgress progress.set_label(_("Copying live image to hard drive.")) progress.processEvents() osimg = self._getLiveBlockDevice() # the real image osfd = os.open(osimg, os.O_RDONLY) rootDevice = anaconda.id.storage.rootDevice rootDevice.setup() rootfd = os.open(rootDevice.path, os.O_WRONLY) readamt = 1024 * 1024 * 8 # 8 megs at a time size = self._getLiveSize() copied = 0 while copied < size: try: buf = os.read(osfd, readamt) written = os.write(rootfd, buf) except: rc = anaconda.intf.messageWindow(_("Error"), _("There was an error installing the live image to " "your hard drive. This could be due to bad media. " "Please verify your installation media.\n\nIf you " "exit, your system will be left in an inconsistent " "state that will require reinstallation."), type="custom", custom_icon="error", custom_buttons=[_("_Exit installer"), _("_Retry")]) if rc == 0: sys.exit(0) else: os.lseek(osfd, 0, 0) os.lseek(rootfd, 0, 0) copied = 0 continue if (written < readamt) and (written < len(buf)): raise RuntimeError, "error copying filesystem!" copied += written progress.set_fraction(pct = copied / float(size)) progress.processEvents() os.close(osfd) os.close(rootfd) anaconda.id.instProgress = None def _doFilesystemMangling(self, anaconda): log.info("doing post-install fs mangling") wait = anaconda.intf.waitWindow(_("Post-Installation"), _("Performing post-installation filesystem changes. This may take several minutes.")) # resize rootfs first, since it is 100% full due to genMinInstDelta self._resizeRootfs(anaconda, wait) # remount filesystems anaconda.id.storage.mountFilesystems() # restore the label of / to what we think it is rootDevice = anaconda.id.storage.rootDevice rootDevice.setup() # ensure we have a random UUID on the rootfs # FIXME: this should be abstracted per filesystem type iutil.execWithRedirect("tune2fs", ["-U", "random", rootDevice.path], stdout="/dev/tty5", stderr="/dev/tty5") # and now set the uuid in the storage layer rootDevice.updateSysfsPath() iutil.notify_kernel("/sys%s" %rootDevice.sysfsPath) storage.udev.udev_settle() rootDevice.updateSysfsPath() info = storage.udev.udev_get_block_device(rootDevice.sysfsPath) rootDevice.format.uuid = storage.udev.udev_device_get_uuid(info) log.info("reset the rootdev (%s) to have a uuid of %s" %(rootDevice.sysfsPath, rootDevice.format.uuid)) # for any filesystem that's _not_ on the root, we need to handle # moving the bits from the livecd -> the real filesystems. # this is pretty distasteful, but should work with things like # having a separate /usr/local def _setupFilesystems(mounts, chroot="", teardown=False): """ Setup or teardown all filesystems except for "/" """ mountpoints = sorted(mounts.keys(), reverse=teardown is True) if teardown: method = "teardown" kwargs = {} else: method = "setup" kwargs = {"chroot": chroot} mountpoints.remove("/") for mountpoint in mountpoints: device = mounts[mountpoint] getattr(device.format, method)(**kwargs) # Start by sorting the mountpoints in decreasing-depth order. mountpoints = sorted(anaconda.id.storage.mountpoints.keys(), reverse=True) # We don't want to copy the root filesystem. mountpoints.remove("/") stats = {} # mountpoint: posix.stat_result # unmount the filesystems, except for / _setupFilesystems(anaconda.id.storage.mountpoints, teardown=True) # mount all of the filesystems under /mnt so we can copy in content _setupFilesystems(anaconda.id.storage.mountpoints, chroot=anaconda.rootPath + "/mnt") # And now let's do the real copies for tocopy in mountpoints: device = anaconda.id.storage.mountpoints[tocopy] # FIXME: all calls to wait.refresh() are kind of a hack... we # should do better about not doing blocking things in the # main thread. but threading anaconda is a job for another # time. wait.refresh() if not os.path.exists("%s/%s" % (anaconda.rootPath, tocopy)): # the directory does not exist in the live image, so there's # nothing to move continue copytree("%s/%s" % (anaconda.rootPath, tocopy), "%s/mnt/%s" % (anaconda.rootPath, tocopy), True, True, flags.selinux) wait.refresh() shutil.rmtree("%s/%s" % (anaconda.rootPath, tocopy)) wait.refresh() # now unmount each fs, collect stat info for the mountpoint, then # remove the entire tree containing the mountpoint for tocopy in mountpoints: device = anaconda.id.storage.mountpoints[tocopy] device.format.teardown() if not os.path.exists("%s/%s" % (anaconda.rootPath, tocopy)): continue try: stats[tocopy]= os.stat("%s/mnt/%s" % (anaconda.rootPath, tocopy)) except Exception as e: log.info("failed to get stat info for mountpoint %s: %s" % (tocopy, e)) shutil.rmtree("%s/mnt/%s" % (anaconda.rootPath, tocopy.split("/")[1])) wait.refresh() # now mount all of the filesystems so that post-install writes end # up where they're supposed to end up _setupFilesystems(anaconda.id.storage.mountpoints, chroot=anaconda.rootPath) # restore stat info for each mountpoint for mountpoint in reversed(mountpoints): if mountpoint not in stats: # there's no info to restore since the mountpoint did not # exist in the live image continue dest = "%s/%s" % (anaconda.rootPath, mountpoint) st = stats[mountpoint] # restore the correct stat info for this mountpoint os.utime(dest, (st.st_atime, st.st_mtime)) os.chown(dest, st.st_uid, st.st_gid) os.chmod(dest, stat.S_IMODE(st.st_mode)) # ensure that non-fstab filesystems are mounted in the chroot if flags.selinux: try: isys.mount("/selinux", anaconda.rootPath + "/selinux", "selinuxfs") except Exception, e: log.error("error mounting selinuxfs: %s" %(e,)) wait.pop() def _resizeRootfs(self, anaconda, win = None): log.info("going to do resize") rootDevice = anaconda.id.storage.rootDevice # FIXME: we'd like to have progress here to give an idea of # how long it will take. or at least, to give an indefinite # progress window. but, not for this time cmd = ["resize2fs", rootDevice.path, "-p"] out = open("/dev/tty5", "w") proc = subprocess.Popen(cmd, stdout=out, stderr=out) rc = proc.poll() while rc is None: win and win.refresh() time.sleep(0.5) rc = proc.poll() if rc: log.error("error running resize2fs; leaving filesystem as is") return # we should also do a fsck afterwards cmd = ["e2fsck", "-f", "-y", rootDevice.path] out = open("/dev/tty5", "w") proc = subprocess.Popen(cmd, stdout=out, stderr=out) rc = proc.poll() while rc is None: win and win.refresh() time.sleep(0.5) rc = proc.poll() def doPostInstall(self, anaconda): import rpm self._doFilesystemMangling(anaconda) # setup /etc/rpm/ for the post-install environment iutil.writeRpmPlatform(anaconda.rootPath) storage.writeEscrowPackets(anaconda) packages.rpmSetupGraphicalSystem(anaconda) # now write out the "real" fstab and mtab anaconda.id.storage.write(anaconda.rootPath) f = open(anaconda.rootPath + "/etc/mtab", "w+") f.write(anaconda.id.storage.mtab) f.close() # copy over the modprobe.conf if os.path.exists("/etc/modprobe.conf"): shutil.copyfile("/etc/modprobe.conf", anaconda.rootPath + "/etc/modprobe.conf") # set the same keyboard the user selected in the keyboard dialog: anaconda.id.keyboard.write(anaconda.rootPath) # rebuild the initrd(s) vers = self.kernelVersionList(anaconda.rootPath) for (n, arch, tag) in vers: packages.recreateInitrd(n, anaconda.rootPath) def writeConfiguration(self): pass def kernelVersionList(self, rootPath = "/"): return packages.rpmKernelVersionList(rootPath) def getMinimumSizeMB(self, part): if part == "/": return self._getLiveSizeMB() return 0 def doBackendSetup(self, anaconda): # ensure there's enough space on the rootfs # FIXME: really, this should be in the general sanity checking, but # trying to weave that in is a little tricky at present. ossize = self._getLiveSizeMB() slash = anaconda.id.storage.rootDevice if slash.size < ossize: rc = anaconda.intf.messageWindow(_("Error"), _("The root filesystem you created is " "not large enough for this live " "image (%.2f MB required).") % ossize, type = "custom", custom_icon = "error", custom_buttons=[_("_Back"), _("_Exit installer")]) if rc == 0: return DISPATCH_BACK else: sys.exit(1) # package/group selection doesn't apply for this backend def groupExists(self, group): pass def selectGroup(self, group, *args): pass def deselectGroup(self, group, *args): pass def selectPackage(self, pkg, *args): pass def deselectPackage(self, pkg, *args): pass def packageExists(self, pkg): return True def getDefaultGroups(self, anaconda): return [] def writePackagesKS(self, f, anaconda): pass<|fim▁end|>
dstname = os.path.join(dst, name) try:
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>default_app_config = 'leonardo.apps.LeonardoConfig' __import__('pkg_resources').declare_namespace(__name__) try: from leonardo.base import leonardo # noqa except ImportError: import warnings def simple_warn(message, category, filename, lineno, file=None, line=None):<|fim▁hole|> "This is normal during installation.\n") warnings.formatwarning = simple_warn warnings.warn(msg, Warning)<|fim▁end|>
return '%s: %s' % (category.__name__, message) msg = ("Could not import Leonardo dependencies. "
<|file_name|>documents.py<|end_file_name|><|fim▁begin|>from docar import Document, Collection from docar import fields from docar.backends.http import HttpBackendManager from libthirty.state import uri, app_uri, service_uri, resource_collection_uri from libthirty.validators import naming, max_25_chars, naming_with_dashes import os HttpBackendManager.SSL_CERT = os.path.join( os.path.dirname(__file__), "ssl", "StartSSL_CA.pem") class User(Document): username = fields.StringField(validators=[naming, max_25_chars]) email = fields.StringField() is_active = fields.BooleanField() class Account(Document): name = fields.StringField(validators=[naming, max_25_chars]) #users = fields.CollectionField(User) class Meta: backend_type = 'http' identifier = 'name' class CnameRecord(Document): record = fields.StringField() class Meta: backend_type = 'http' identifier = 'record' class CnameRecords(Collection): document = CnameRecord class EnvironmentVariable(Document): id = fields.NumberField(render=False, optional=True) name = fields.StringField() value = fields.StringField() class Meta: backend_type = 'http' class EnvironmentVariables(Collection): document = EnvironmentVariable class Postgres(Document): name = fields.StringField(validators=[naming_with_dashes, max_25_chars], read_only=True, optional=True) label = fields.StaticField(value="postgres") variant = fields.ChoicesField(choices=['postgres_micro'], default="postgres_micro") username = fields.StringField(optional=True, read_only=True) password = fields.StringField(optional=True, read_only=True) host = fields.StringField(optional=True, read_only=True) port = fields.NumberField(optional=True, read_only=True) published = fields.BooleanField(default=False, read_only=True) class Meta: backend_type = 'http' identifier = 'name' context = ['account'] def post_uri(self): return '%s/services' % app_uri() def uri(self): return service_uri(service='postgres') class PostgresCollection(Collection): document = Postgres def uri(self): return resource_collection_uri(label='postgres') class Mongodb(Document): name = fields.StringField(validators=[naming_with_dashes, max_25_chars], read_only=True, optional=True) label = fields.StaticField(value="mongodb") variant = fields.ChoicesField(choices=['mongodb_micro'], default='mongodb_micro') username = fields.StringField(optional=True, read_only=True) password = fields.StringField(optional=True, read_only=True) host = fields.StringField(optional=True, read_only=True) port = fields.NumberField(optional=True, read_only=True) published = fields.BooleanField(default=False, read_only=True) class Meta: backend_type = 'http' identifier = 'name' context = ['account'] def post_uri(self): return '%s/services' % app_uri() def uri(self): return service_uri(service='mongodb') class MongodbCollection(Collection): document = Mongodb def uri(self): return resource_collection_uri(label='mongodb') class Repository(Document): name = fields.StringField(validators=[naming_with_dashes, max_25_chars], read_only=True, optional=True, render=False) label = fields.StaticField(value="repository") variant = fields.ChoicesField(choices=['git'], default='git') location = fields.StringField() ssh_key = fields.StringField(optional=True) class Meta: backend_type = 'http' identifier = 'name' context = ['account'] def post_uri(self): return '%s/services' % app_uri() def uri(self): return service_uri(service='repository') class RepositoryCollection(Collection): document = Repository def uri(self): return resource_collection_uri(label='repository') class Worker(Document): name = fields.StringField(validators=[naming_with_dashes, max_25_chars], read_only=True, render=False, optional=True) label = fields.StaticField(value="worker") variant = fields.ChoicesField(choices=['python'], default='python') instances = fields.NumberField(default=1) published = fields.BooleanField(default=False, read_only=True) envvars = fields.CollectionField(EnvironmentVariables, inline=True) class Meta: backend_type = 'http' identifier = 'name' context = ['account'] def post_uri(self): return '%s/services' % app_uri() def uri(self): return service_uri(service='worker') class WorkerCollection(Collection): document = Worker def uri(self): return resource_collection_uri(label='worker') class App(Document): name = fields.StringField(validators=[naming, max_25_chars]) label = fields.StaticField(value="app") variant = fields.ChoicesField(default='python', choices=['static', 'python']) repository = fields.ForeignDocument(Repository) postgres = fields.ForeignDocument(Postgres, optional=True) mongodb = fields.ForeignDocument(Mongodb, optional=True) worker = fields.ForeignDocument(Worker, optional=True) repo_commit = fields.StringField(default='HEAD') region = fields.ChoicesField(default="eu-nl", choices=['eu-nl', 'ams1']) instances = fields.NumberField(default=1) dns_record = fields.StringField(optional=True) cnames = fields.CollectionField(CnameRecords, inline=True) published = fields.BooleanField(default=False, read_only=True) envvars = fields.CollectionField(EnvironmentVariables, inline=True) class Meta: backend_type = 'http' identifier = 'name' context = ['account'] def post_uri(self): return '%s/apps' % uri() def uri(self): return app_uri(appname=self.name)<|fim▁hole|>class AppCollection(Collection): document = App def uri(self): return '%s/apps' % uri()<|fim▁end|>
<|file_name|>args.rs<|end_file_name|><|fim▁begin|><|fim▁hole|> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ use quote::*; use syn::*; use syn::parse::*; pub mod kw { syn::custom_keyword!(default); syn::custom_keyword!(errtype); syn::custom_keyword!(bitnames); syn::custom_keyword!(variant); syn::custom_keyword!(frag_variant); syn::custom_keyword!(pat_variant); syn::custom_keyword!(dimensions); syn::custom_keyword!(outer_frag_variant); syn::custom_keyword!(inner_frag_variant); syn::custom_keyword!(encode_extra_type); syn::custom_keyword!(decode_extra_type); } #[derive(Debug)] pub struct ArgWithExpr { pub ident: Ident, _eq: syn::token::Eq, pub expr: Expr, } impl Parse for ArgWithExpr { fn parse(input: ParseStream) -> syn::parse::Result<Self> { Ok(ArgWithExpr { ident: input.parse()?, _eq: input.parse()?, expr: input.parse()?, }) } } impl ToTokens for ArgWithExpr { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { self.ident.to_tokens(tokens); self._eq.to_tokens(tokens); self.expr.to_tokens(tokens); } } #[derive(Debug)] pub struct StrArgWithExpr { pub litstr: LitStr, _eq: syn::token::Eq, pub expr: Expr, } impl Parse for StrArgWithExpr { fn parse(input: ParseStream) -> syn::parse::Result<Self> { Ok(StrArgWithExpr { litstr: input.parse()?, _eq: input.parse()?, expr: input.parse()?, }) } } impl ToTokens for StrArgWithExpr { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { self.litstr.to_tokens(tokens); self._eq.to_tokens(tokens); self.expr.to_tokens(tokens); } } #[derive(Debug)] pub struct ArgWithType { _ident: Ident, _eq: syn::token::Eq, pub ty: Type, } impl Parse for ArgWithType { fn parse(input: ParseStream) -> syn::parse::Result<Self> { Ok(ArgWithType { _ident: input.parse()?, _eq: input.parse()?, ty: input.parse()?, }) } } impl ToTokens for ArgWithType { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { self._ident.to_tokens(tokens); self._eq.to_tokens(tokens); self.ty.to_tokens(tokens); } } #[derive(Debug)] pub struct ArgWithLitStr { _ident: Ident, _eq: syn::token::Eq, pub litstr: LitStr, } impl Parse for ArgWithLitStr { fn parse(input: ParseStream) -> syn::parse::Result<Self> { Ok(ArgWithLitStr { _ident: input.parse()?, _eq: input.parse()?, litstr: input.parse()?, }) } } impl ToTokens for ArgWithLitStr { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { self._ident.to_tokens(tokens); self._eq.to_tokens(tokens); self.litstr.to_tokens(tokens); } } #[derive(Debug)] pub struct ArgWithLitInt { _ident: Ident, _eq: syn::token::Eq, pub litint: LitInt, } impl Parse for ArgWithLitInt { fn parse(input: ParseStream) -> syn::parse::Result<Self> { Ok(ArgWithLitInt { _ident: input.parse()?, _eq: input.parse()?, litint: input.parse()?, }) } } impl ToTokens for ArgWithLitInt { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { self._ident.to_tokens(tokens); self._eq.to_tokens(tokens); self.litint.to_tokens(tokens); } }<|fim▁end|>
/* Copyright (c) 2020, R. Ou <[email protected]> and contributors All rights reserved.
<|file_name|>preAnalysisRun.py<|end_file_name|><|fim▁begin|>import os import sys from src import impl as rlcs import utils as ut import analysis as anls import matplotlib.pyplot as plt import logging import pickle as pkl import time config = ut.loadConfig('config') sylbSimFolder=config['sylbSimFolder'] transFolder=config['transFolder'] lblDir=config['lblDir'] onsDir=config['onsDir'] resultDir=config['resultDir'] queryList = [['DHE','RE','DHE','RE','KI','TA','TA','KI','NA','TA','TA','KI','TA','TA','KI','NA'],['TA','TA','KI','TA','TA','KI','TA','TA','KI','TA','TA','KI','TA','TA','KI','TA'], ['TA','KI','TA','TA','KI','TA','TA','KI'], ['TA','TA','KI','TA','TA','KI'], ['TA', 'TA','KI', 'TA'],['KI', 'TA', 'TA', 'KI'], ['TA','TA','KI','NA'], ['DHA','GE','TA','TA']] queryLenCheck = [4,6,8,16] for query in queryList: if len(query) not in queryLenCheck: print 'The query is not of correct length!!' sys.exit() masterData = ut.getAllSylbData(tPath = transFolder, lblDir = lblDir, onsDir = onsDir) <|fim▁hole|><|fim▁end|>
res = anls.getPatternsInTransInGTPos(masterData, queryList)
<|file_name|>MC_12_11104124_MagUp.py<|end_file_name|><|fim▁begin|>#-- GAUDI jobOptions generated on Fri Jul 17 16:39:48 2015 #-- Contains event types : #-- 11104124 - 106 files - 1087377 events - 233.68 GBytes #-- Extra information about the data processing phases: #-- Processing Pass Step-124620 #-- StepId : 124620 #-- StepName : Digi13 with G4 dE/dx #-- ApplicationName : Boole #-- ApplicationVersion : v26r3 #-- OptionFiles : $APPCONFIGOPTS/Boole/Default.py;$APPCONFIGOPTS/Boole/DataType-2012.py;$APPCONFIGOPTS/Boole/Boole-SiG4EnergyDeposit.py;$APPCONFIGOPTS/Persistency/Compression-ZLIB-1.py #-- DDDB : fromPreviousStep #-- CONDDB : fromPreviousStep #-- ExtraPackages : AppConfig.v3r164 #-- Visible : Y #-- Processing Pass Step-124630 #-- StepId : 124630 #-- StepName : Stripping20-NoPrescalingFlagged for Sim08 #-- ApplicationName : DaVinci #-- ApplicationVersion : v32r2p1 #-- OptionFiles : $APPCONFIGOPTS/DaVinci/DV-Stripping20-Stripping-MC-NoPrescaling.py;$APPCONFIGOPTS/DaVinci/DataType-2012.py;$APPCONFIGOPTS/DaVinci/InputType-DST.py;$APPCONFIGOPTS/Persistency/Compression-ZLIB-1.py #-- DDDB : fromPreviousStep #-- CONDDB : fromPreviousStep #-- ExtraPackages : AppConfig.v3r164 #-- Visible : Y #-- Processing Pass Step-125877 #-- StepId : 125877 #-- StepName : L0 emulation - TCK 003d #-- ApplicationName : Moore #-- ApplicationVersion : v20r4 #-- OptionFiles : $APPCONFIGOPTS/L0App/L0AppSimProduction.py;$APPCONFIGOPTS/L0App/L0AppTCK-0x003d.py;$APPCONFIGOPTS/L0App/DataType-2012.py #-- DDDB : fromPreviousStep #-- CONDDB : fromPreviousStep #-- ExtraPackages : AppConfig.v3r200 #-- Visible : N #-- Processing Pass Step-127200 #-- StepId : 127200 #-- StepName : TCK-0x4097003d Flagged for Sim08 2012 #-- ApplicationName : Moore #-- ApplicationVersion : v14r2p1 #-- OptionFiles : $APPCONFIGOPTS/Moore/MooreSimProductionForSeparateL0AppStep.py;$APPCONFIGOPTS/Conditions/TCK-0x4097003d.py;$APPCONFIGOPTS/Moore/DataType-2012.py #-- DDDB : fromPreviousStep #-- CONDDB : fromPreviousStep #-- ExtraPackages : AppConfig.v3r206 #-- Visible : Y #-- Processing Pass Step-124834 #-- StepId : 124834 #-- StepName : Reco14a for MC #-- ApplicationName : Brunel #-- ApplicationVersion : v43r2p7 #-- OptionFiles : $APPCONFIGOPTS/Brunel/DataType-2012.py;$APPCONFIGOPTS/Brunel/MC-WithTruth.py;$APPCONFIGOPTS/Persistency/Compression-ZLIB-1.py #-- DDDB : fromPreviousStep #-- CONDDB : fromPreviousStep #-- ExtraPackages : AppConfig.v3r164 #-- Visible : Y #-- Processing Pass Step-127148 #-- StepId : 127148 #-- StepName : Sim08g - 2012 - MU - Pythia8 #-- ApplicationName : Gauss #-- ApplicationVersion : v45r9 #-- OptionFiles : $APPCONFIGOPTS/Gauss/Sim08-Beam4000GeV-mu100-2012-nu2.5.py;$DECFILESROOT/options/@{eventType}.py;$LBPYTHIA8ROOT/options/Pythia8.py;$APPCONFIGOPTS/Gauss/G4PL_FTFP_BERT_EmNoCuts.py;$APPCONFIGOPTS/Persistency/Compression-ZLIB-1.py #-- DDDB : dddb-20130929-1 #-- CONDDB : sim-20130522-1-vc-mu100 #-- ExtraPackages : AppConfig.v3r205;DecFiles.v27r37 #-- Visible : Y from Gaudi.Configuration import * from GaudiConf import IOHelper IOHelper('ROOT').inputFiles(['LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000001_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000002_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000003_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000004_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000005_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000006_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000007_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000008_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000009_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000010_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000011_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000012_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000013_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000014_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000015_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000016_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000017_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000018_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000019_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000020_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000021_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000022_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000023_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000024_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000025_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000026_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000027_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000032_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000033_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000034_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000045_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000057_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000058_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000062_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000073_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000074_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000075_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000076_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000077_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000078_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000079_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000080_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000081_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000082_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000083_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000084_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000085_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000086_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000087_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000088_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000089_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000090_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000091_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000092_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000093_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000094_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000095_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000096_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000097_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000098_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000099_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000100_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000101_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000102_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000103_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000104_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000105_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000106_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000107_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000108_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000109_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000110_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000111_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000112_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000113_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000114_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000115_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000116_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000117_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000118_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000119_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000120_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000121_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000122_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000123_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000124_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000125_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000126_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000127_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000128_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000129_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000130_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000131_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000132_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000133_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000134_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000135_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000136_1.allstreams.dst',<|fim▁hole|>'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000139_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000140_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000141_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000142_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000143_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000144_1.allstreams.dst' ], clear=True)<|fim▁end|>
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000137_1.allstreams.dst', 'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00043567/0000/00043567_00000138_1.allstreams.dst',
<|file_name|>condition_evaluator.ts<|end_file_name|><|fim▁begin|>/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {IMinimatch, Minimatch} from 'minimatch'; /** Map that holds patterns and their corresponding Minimatch globs. */ const patternCache = new Map<string, IMinimatch>(); /** * Context that is provided to conditions. Conditions can use various helpers * that PullApprove provides. We try to mock them here. Consult the official * docs for more details: https://docs.pullapprove.com/config/conditions. */<|fim▁hole|> 'len': (value: any[]) => value.length, 'contains_any_globs': (files: PullApproveArray, patterns: string[]) => { // Note: Do not always create globs for the same pattern again. This method // could be called for each source file. Creating glob's is expensive. return files.some(f => patterns.some(pattern => getOrCreateGlob(pattern).match(f))); } }; /** * Converts a given condition to a function that accepts a set of files. The returned * function can be called to check if the set of files matches the condition. */ export function convertConditionToFunction(expr: string): (files: string[]) => boolean { // Creates a dynamic function with the specified expression. The first parameter will // be `files` as that corresponds to the supported `files` variable that can be accessed // in PullApprove condition expressions. The followed parameters correspond to other // context variables provided by PullApprove for conditions. const evaluateFn = new Function('files', ...Object.keys(conditionContext), ` return (${transformExpressionToJs(expr)}); `); // Create a function that calls the dynamically constructed function which mimics // the condition expression that is usually evaluated with Python in PullApprove. return files => { const result = evaluateFn(new PullApproveArray(...files), ...Object.values(conditionContext)); // If an array is returned, we consider the condition as active if the array is not // empty. This matches PullApprove's condition evaluation that is based on Python. if (Array.isArray(result)) { return result.length !== 0; } return !!result; }; } /** * Transforms a condition expression from PullApprove that is based on python * so that it can be run inside JavaScript. Current transformations: * 1. `not <..>` -> `!<..>` */ function transformExpressionToJs(expression: string): string { return expression.replace(/not\s+/g, '!'); } /** * Superset of a native array. The superset provides methods which mimic the * list data structure used in PullApprove for files in conditions. */ class PullApproveArray extends Array<string> { constructor(...elements: string[]) { super(...elements); // Set the prototype explicitly because in ES5, the prototype is accidentally // lost due to a limitation in down-leveling. // https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work. Object.setPrototypeOf(this, PullApproveArray.prototype); } /** Returns a new array which only includes files that match the given pattern. */ include(pattern: string): PullApproveArray { return new PullApproveArray(...this.filter(s => getOrCreateGlob(pattern).match(s))); } /** Returns a new array which only includes files that did not match the given pattern. */ exclude(pattern: string): PullApproveArray { return new PullApproveArray(...this.filter(s => !getOrCreateGlob(pattern).match(s))); } } /** * Gets a glob for the given pattern. The cached glob will be returned * if available. Otherwise a new glob will be created and cached. */ function getOrCreateGlob(pattern: string) { if (patternCache.has(pattern)) { return patternCache.get(pattern)!; } const glob = new Minimatch(pattern, {dot: true}); patternCache.set(pattern, glob); return glob; }<|fim▁end|>
const conditionContext = {
<|file_name|>dialogflow_v3beta1_generated_experiments_delete_experiment_sync.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright 2022 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 # # http://www.apache.org/licenses/LICENSE-2.0<|fim▁hole|># 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 code. DO NOT EDIT! # # Snippet for DeleteExperiment # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-dialogflowcx # [START dialogflow_v3beta1_generated_Experiments_DeleteExperiment_sync] from google.cloud import dialogflowcx_v3beta1 def sample_delete_experiment(): # Create a client client = dialogflowcx_v3beta1.ExperimentsClient() # Initialize request argument(s) request = dialogflowcx_v3beta1.DeleteExperimentRequest( name="name_value", ) # Make the request client.delete_experiment(request=request) # [END dialogflow_v3beta1_generated_Experiments_DeleteExperiment_sync]<|fim▁end|>
# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS,
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from .workout import Workout from .duration import Time from .duration import Distance<|fim▁end|>
<|file_name|>test_core.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ type 'pytest -v' to run u test series """ import codecs import json import os import pytest import tempfile import sys sys.path.insert(1, os.path.join(sys.path[0], '..')) import core class TestHelpers: @staticmethod def file_read(fd): """ from current descriptor, create a new descriptor in read mode and read file content :return file content :rtype str """ with codecs.open(fd.name, 'r', 'utf-8') as f: res = f.read() return res @staticmethod def same_class(instance, should_cls): return str(instance.__class__) == str(should_cls) @staticmethod def json_compare(a, b): return json.dumps(a) == json.dumps(b) class Fake(object): pass @pytest.fixture() def fixture_dict_data(): return dict( id=1, active=True, name='foobar', nested=dict(id=1, name='nested'), items=[dict(id=1, name='item1'),], ) def fixture_dict_data_check_matching(o, data): assert o # check __dict__ assert isinstance(o.__dict__, dict) assert len(o.__dict__.keys()) == len(data.keys()) assert o.__dict__['id'] == data['id'] assert o.__dict__['active'] == data['active'] assert o.__dict__['name'] == data['name'] assert TestHelpers.same_class(o.__dict__['nested'], core.Object) assert len(o.__dict__['nested'].__dict__.keys()) == len(data['nested'].keys()) assert o.__dict__['nested'].__dict__['id'] == data['nested']['id'] assert o.__dict__['nested'].__dict__['name'] == data['nested']['name'] assert isinstance(o.__dict__['items'], list) assert len(o.__dict__['items']) == len(data['items']) assert TestHelpers.same_class(o.__dict__['items'][0], core.Object) assert o.__dict__['items'][0].__dict__['id'] == data['items'][0]['id'] assert o.__dict__['items'][0].__dict__['name'] == data['items'][0]['name'] # check attrs assert hasattr(o, 'id') assert hasattr(o, 'active') assert hasattr(o, 'name') assert hasattr(o, 'nested') assert hasattr(o, 'items') assert o.id == data['id'] assert o.active == data['active'] assert o.name == data['name'] assert TestHelpers.same_class(o.nested, core.Object) assert hasattr(o.nested, 'id') assert hasattr(o.nested, 'name') assert o.nested.id == data['nested']['id'] assert o.nested.name == data['nested']['name'] assert isinstance(o.items, list) assert len(o.items) == len(data['items']) assert hasattr(o.items[0], 'id') assert hasattr(o.items[0], 'name') assert o.items[0].id == data['items'][0]['id'] assert o.items[0].name == data['items'][0]['name'] @pytest.fixture() def fixture_json_data(): return json.dumps(dict( id=1, active=True, name='foobar', nested=dict(id=1, name='nested'), items=[dict(id=1, name='item1')], )) @pytest.fixture() def fixture_repr_data(): return "<class 'core.Object'>, 5 attrs: active: True, id: 1," \ " items: [<class 'core.Object'>, 2 attrs: id: 1, name: 'item1']," \ " name: 'foobar', nested: <class 'core.Object'>, 2 attrs: id: 1, name: 'nested'" @pytest.fixture() def fixture_str_data(): return "<class 'core.Object'>, 5 attrs: active: True, id: 1," \ " items: [{'id': 1, 'name': 'item1'}], name: 'foobar'," \ " nested: {'id': 1, 'name': 'nested'}" @pytest.fixture() def fixture_update_merge_data(): return { 'data': {'foo': {'bar': {'message': 'foobar'}}}, 'data2': { 'foo': {'bar': {'color': 'green'}}, 'foo2': {'bar': {'message': 'foobar 2', 'color': 'orange'}}, }, 'merge': { 'foo': {'bar': {'message': 'foobar', 'color': 'green'}}, 'foo2': {'bar': {'message': 'foobar 2', 'color': 'orange'}}, }, } @pytest.fixture() def fixture_config_file(request): fd = tempfile.NamedTemporaryFile(mode='w', suffix='.ini', delete=False) with fd: fd.write(""" [foo] foo1=Fee foo2=Fie [bar] bar1=Foe bar2=Foo """) def delete(): if not fd.closed: fd.close() os.remove(fd.name) request.addfinalizer(delete) return fd @pytest.fixture() def fixture_config_file_expected_data(): return dict(<|fim▁hole|> class Test01ObjectContract(): def test_00_of_class_ko(self): assert not core.Object.of_class(None) assert not core.Object.of_class(False) assert not core.Object.of_class(True) assert not core.Object.of_class(1) assert not core.Object.of_class('a') assert not core.Object.of_class(object()) assert not core.Object.of_class(Fake()) class Test02ObjectConstructor(): def test_00_contract_ko(self): with pytest.raises(AssertionError, message=core.Object.CONTRACT_DATA_DICT): core.Object(False) with pytest.raises(AssertionError, message=core.Object.CONTRACT_DATA_DICT): core.Object(True) with pytest.raises(AssertionError, message=core.Object.CONTRACT_DATA_DICT): core.Object(1) with pytest.raises(AssertionError, message=core.Object.CONTRACT_DATA_DICT): core.Object('a') with pytest.raises(AssertionError, message=core.Object.CONTRACT_DATA_DICT): core.Object(object()) def test_01_empty(self): o = core.Object() assert o # alias o = core.o() assert o o = core.Object(None) assert o o = core.Object(dict()) assert o def test_02_of_class(self): assert core.Object.of_class(core.Object()) assert core.Object.of_class(core.o()) @pytest.mark.usefixtures('fixture_dict_data') def test_03_from_dict(self, fixture_dict_data): fixture_dict_data_check_matching(core.Object(fixture_dict_data), fixture_dict_data) fixture_dict_data_check_matching(core.o(fixture_dict_data), fixture_dict_data) # get_dict: will be used for following test so at serie start @pytest.mark.usefixtures('fixture_dict_data') def test_04_get_dict(self, fixture_dict_data): o = core.o(fixture_dict_data) assert o.get_dict() == fixture_dict_data def test_05_kwargs(self): o = core.o(id=1, name='kwarg') assert o.get_dict() == dict(id=1, name='kwarg') o = core.o(dict(), id=1, name='kwarg') assert o.get_dict() == dict(id=1, name='kwarg') o = core.o(dict(description='from dict'), id=1, name='kwarg') assert o.get_dict() == dict(description='from dict', id=1, name='kwarg') class Test02ObjectUpdateContent(): @pytest.mark.usefixtures('fixture_dict_data') def test_00_setattr(self, fixture_dict_data): o = core.o(fixture_dict_data) # change exiting attribute o.name = 'changed' assert o.name == 'changed' o.nested.name = 'changed2' assert o.nested.name == 'changed2' o.items[0].name = 'changed3' assert o.items[0].name == 'changed3' # new attribute o.description = 'description' assert o.description == 'description' o.nested2 = core.o(dict(id=2, name='nested2')) assert o.nested2.id == 2 assert o.nested2.name == 'nested2' o.nested3 = core.o() o.nested3.id = 3 assert o.nested3.id == 3 o.items2 = [core.o(dict(id=2, name='item2'))] assert o.items2[0].id == 2 assert o.items2[0].name == 'item2' @pytest.mark.usefixtures('fixture_update_merge_data') def test_01_update(self, fixture_update_merge_data): with pytest.raises(AssertionError, message=core.Object.CONTRACT_DATA_SELF): core.o().update(1) data = fixture_update_merge_data['data'] data2 = fixture_update_merge_data['data2'] o = core.o(data) assert o.get_dict() == data o.update(data2) assert o.get_dict() == data2 assert core.o(data).update(data2).get_dict() == data2 # chained style o = core.o() assert o.get_dict() == {} o.update(data) assert o.get_dict() == data o.update(data2) assert o.get_dict() == data2 assert core.o().update(data).update(data2).get_dict() == data2 # chained style o = core.o(data) o.update(core.o(data2)) assert o.get_dict() == data2 assert core.o(data).update(core.o(data2)).get_dict() == data2 # chained style o = core.o() assert o.get_dict() == {} o.update(core.o(data)) assert o.get_dict() == data o.update(core.o(data2)) assert o.get_dict() == data2 assert core.o().update(core.o(data)).update(core.o(data2)).get_dict() == data2 # chained style @pytest.mark.usefixtures('fixture_update_merge_data') def test_02_merge(self, fixture_update_merge_data): with pytest.raises(AssertionError, message=core.Object.CONTRACT_DATA_SELF): core.o().merge(1) data = fixture_update_merge_data['data'] data2 = fixture_update_merge_data['data2'] merge = fixture_update_merge_data['merge'] o = core.o(data) assert o.get_dict() == data o.merge(data2) assert o.get_dict() == merge assert core.o(data).merge(data2).get_dict() == merge # chained style o = core.o() o.merge(data) assert o.get_dict() == data o.merge(data2) assert o.get_dict() == merge assert core.o().merge(data).merge(data2).get_dict() == merge # chained style o = core.o(data) o.merge(core.o(data2)) assert o.get_dict() == merge assert core.o(data).merge(core.o(data2)).get_dict() == merge # chained style o = core.o() assert o.get_dict() == {} o.merge(core.o(data)) assert o.get_dict() == data o.merge(core.o(data2)) assert o.get_dict() == merge assert core.o().merge(core.o(data)).merge(core.o(data2)).get_dict() == merge class Test03Json(): @pytest.mark.usefixtures('fixture_dict_data') @pytest.mark.usefixtures('fixture_json_data') def test_00_jsonify(self, fixture_dict_data, fixture_json_data): assert TestHelpers.json_compare(core.o(fixture_dict_data).jsonify(), fixture_json_data) @pytest.mark.usefixtures('fixture_dict_data') @pytest.mark.usefixtures('fixture_json_data') def test_01_unjsonify(self, fixture_dict_data, fixture_json_data): with pytest.raises(AssertionError): core.Object.unjsonify(1) assert core.Object.unjsonify(fixture_json_data).get_dict() == fixture_dict_data assert core.unjsonify(fixture_json_data).get_dict() == fixture_dict_data class Test04ObjectMagic(): @pytest.mark.usefixtures('fixture_dict_data') @pytest.mark.usefixtures('fixture_repr_data') def test_00_repr(self, fixture_dict_data, fixture_repr_data): assert repr(core.o(fixture_dict_data)) == fixture_repr_data @pytest.mark.usefixtures('fixture_dict_data') @pytest.mark.usefixtures('fixture_str_data') def test_01_str(self, fixture_dict_data, fixture_str_data): assert str(core.o(fixture_dict_data)) == fixture_str_data def test_02_eq_ne(self): o1 = core.o(id=1, name='foobar') o2 = core.o(id=1, name='foobar') o3 = core.o(id=3, name='foobar3') assert o1 == o2 assert o1 != o3 @pytest.mark.usefixtures('fixture_update_merge_data') def test_03_add(self, fixture_update_merge_data): data = fixture_update_merge_data['data'] data2 = fixture_update_merge_data['data2'] merge = fixture_update_merge_data['merge'] assert (core.o(data) + core.o(data2)).get_dict() == merge @pytest.mark.usefixtures('fixture_update_merge_data') def test_04_iadd(self, fixture_update_merge_data): data = fixture_update_merge_data['data'] data2 = fixture_update_merge_data['data2'] merge = fixture_update_merge_data['merge'] o = core.o(data) o += core.o(data2) assert o.get_dict() == merge class Test05ObjectGetContent(): def test_00_get(self): data = {'foo': {'bar': {'message': 'foobar'}}} o = core.o(data) assert o.get('ko') is None assert TestHelpers.same_class(o.get('foo'), core.Object) assert o.get('foo').get_dict() == {'bar': {'message': 'foobar'}} assert TestHelpers.same_class(o.get('foo').get('bar'), core.Object) assert o.get('foo').get('bar').get_dict() == {'message': 'foobar'} assert o.get('foo').get('bar').get('message') == 'foobar' def test_01_get_dot(self): data = {'foo': {'bar': {'message': 'foobar'}}} o = core.o(data) assert o.get_dot('ko') is None assert o.get_dot('ko.ko') is None assert TestHelpers.same_class(o.get_dot('foo'), core.Object) assert o.get_dot('foo').get_dict() == {'bar': {'message': 'foobar'}} assert TestHelpers.same_class(o.get_dot('foo.bar'), core.Object) assert o.get_dot('foo.bar').get_dict() == {'message': 'foobar'} assert o.get_dot('foo.bar.message') == 'foobar' @pytest.mark.usefixtures('fixture_dict_data') def test_02_attrs(self, fixture_dict_data): o = core.o(fixture_dict_data) assert o.attrs() == sorted(fixture_dict_data.keys()) class Test06ObjectExtra(): @pytest.mark.usefixtures('fixture_config_file') @pytest.mark.usefixtures('fixture_config_file_expected_data') def test_00_cfg_read_get(self, fixture_config_file, fixture_config_file_expected_data): with pytest.raises(AssertionError): core.o().read_cfg(1) assert core.o().read_cfg(fixture_config_file.name).get_dict() == fixture_config_file_expected_data<|fim▁end|>
foo=dict(foo1='Fee', foo2='Fie'), bar=dict(bar1='Foe', bar2='Foo'), )
<|file_name|>dom_document_type.rs<|end_file_name|><|fim▁begin|>// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files.git) // DO NOT EDIT use crate::DOMEventTarget; use crate::DOMNamedNodeMap; use crate::DOMNode; use crate::DOMObject; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib::wrapper! { pub struct DOMDocumentType(Object<ffi::WebKitDOMDocumentType, ffi::WebKitDOMDocumentTypeClass>) @extends DOMNode, DOMObject, @implements DOMEventTarget; match fn { type_ => || ffi::webkit_dom_document_type_get_type(), } } pub const NONE_DOM_DOCUMENT_TYPE: Option<&DOMDocumentType> = None; pub trait DOMDocumentTypeExt: 'static { #[cfg_attr(feature = "v2_22", deprecated)] #[doc(alias = "webkit_dom_document_type_get_entities")] fn entities(&self) -> Option<DOMNamedNodeMap>; #[cfg_attr(feature = "v2_22", deprecated)] #[doc(alias = "webkit_dom_document_type_get_internal_subset")] fn internal_subset(&self) -> Option<glib::GString>; #[cfg_attr(feature = "v2_22", deprecated)] #[doc(alias = "webkit_dom_document_type_get_name")] fn name(&self) -> Option<glib::GString>; #[cfg_attr(feature = "v2_22", deprecated)] #[doc(alias = "webkit_dom_document_type_get_notations")] fn notations(&self) -> Option<DOMNamedNodeMap>; #[cfg_attr(feature = "v2_22", deprecated)] #[doc(alias = "webkit_dom_document_type_get_public_id")] fn public_id(&self) -> Option<glib::GString>; #[cfg_attr(feature = "v2_22", deprecated)] #[doc(alias = "webkit_dom_document_type_get_system_id")] fn system_id(&self) -> Option<glib::GString>; fn connect_property_entities_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_internal_subset_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId; fn connect_property_name_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_notations_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_public_id_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_system_id_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<DOMDocumentType>> DOMDocumentTypeExt for O { fn entities(&self) -> Option<DOMNamedNodeMap> { unsafe { from_glib_full(ffi::webkit_dom_document_type_get_entities( self.as_ref().to_glib_none().0, )) } } <|fim▁hole|> fn internal_subset(&self) -> Option<glib::GString> { unsafe { from_glib_full(ffi::webkit_dom_document_type_get_internal_subset( self.as_ref().to_glib_none().0, )) } } fn name(&self) -> Option<glib::GString> { unsafe { from_glib_full(ffi::webkit_dom_document_type_get_name( self.as_ref().to_glib_none().0, )) } } fn notations(&self) -> Option<DOMNamedNodeMap> { unsafe { from_glib_full(ffi::webkit_dom_document_type_get_notations( self.as_ref().to_glib_none().0, )) } } fn public_id(&self) -> Option<glib::GString> { unsafe { from_glib_full(ffi::webkit_dom_document_type_get_public_id( self.as_ref().to_glib_none().0, )) } } fn system_id(&self) -> Option<glib::GString> { unsafe { from_glib_full(ffi::webkit_dom_document_type_get_system_id( self.as_ref().to_glib_none().0, )) } } fn connect_property_entities_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_entities_trampoline<P, F: Fn(&P) + 'static>( this: *mut ffi::WebKitDOMDocumentType, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) where P: IsA<DOMDocumentType>, { let f: &F = &*(f as *const F); f(&DOMDocumentType::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::entities\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_entities_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_property_internal_subset_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_internal_subset_trampoline<P, F: Fn(&P) + 'static>( this: *mut ffi::WebKitDOMDocumentType, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) where P: IsA<DOMDocumentType>, { let f: &F = &*(f as *const F); f(&DOMDocumentType::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::internal-subset\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_internal_subset_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_property_name_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_name_trampoline<P, F: Fn(&P) + 'static>( this: *mut ffi::WebKitDOMDocumentType, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) where P: IsA<DOMDocumentType>, { let f: &F = &*(f as *const F); f(&DOMDocumentType::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::name\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_name_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_property_notations_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_notations_trampoline<P, F: Fn(&P) + 'static>( this: *mut ffi::WebKitDOMDocumentType, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) where P: IsA<DOMDocumentType>, { let f: &F = &*(f as *const F); f(&DOMDocumentType::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::notations\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_notations_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_property_public_id_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_public_id_trampoline<P, F: Fn(&P) + 'static>( this: *mut ffi::WebKitDOMDocumentType, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) where P: IsA<DOMDocumentType>, { let f: &F = &*(f as *const F); f(&DOMDocumentType::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::public-id\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_public_id_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_property_system_id_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_system_id_trampoline<P, F: Fn(&P) + 'static>( this: *mut ffi::WebKitDOMDocumentType, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) where P: IsA<DOMDocumentType>, { let f: &F = &*(f as *const F); f(&DOMDocumentType::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::system-id\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_system_id_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } } impl fmt::Display for DOMDocumentType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("DOMDocumentType") } }<|fim▁end|>
<|file_name|>test_helpers.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from celeryone.helpers import queue_one_key, kwargs_to_list, force_string import pytest import six def test_force_string_1(): assert force_string('a') == 'a' def test_force_string_2(): assert force_string(u'a') == 'a' def test_force_string_3(): assert force_string('é') == 'é' def test_force_string_4(): assert force_string(u'é') == 'é' def test_kwargs_to_list_empty(): keys = kwargs_to_list({}) assert keys == [] def test_kwargs_to_list_1(): keys = kwargs_to_list({'int': 1}) assert keys == ["int-1"] def test_kwargs_to_list_2(): keys = kwargs_to_list({'int': 1, 'boolean': True}) assert keys == ["boolean-True", "int-1"] def test_kwargs_to_list_3(): keys = kwargs_to_list({'int': 1, 'boolean': True, 'str': "abc"}) assert keys == ["boolean-True", "int-1", "str-abc"] def test_kwargs_to_list_4(): keys = kwargs_to_list( {'int': 1, 'boolean': True, 'str': 'abc', 'list': [1, '2']}) assert keys == ["boolean-True", "int-1", "list-[1, '2']", "str-abc"] @pytest.mark.skipif(six.PY3, reason='requires python 2') def test_kwargs_to_list_5(): keys = kwargs_to_list( {'a': {u'é': 'c'}, 'b': [u'a', 'é'], u'c': 1, 'd': 'é', 'e': u'é'}) assert keys == [ "a-{'\\xc3\\xa9': 'c'}", "b-['a', '\\xc3\\xa9']", "c-1", "d-\xc3\xa9", "e-\xc3\xa9", ]<|fim▁hole|> @pytest.mark.skipif(six.PY2, reason='requires python 3') def test_kwargs_to_list_6(): keys = kwargs_to_list( {'a': {u'é': 'c'}, 'b': [u'a', 'é'], u'c': 1, 'd': 'é', 'e': u'é'}) assert keys == ["a-{'é': 'c'}", "b-['a', 'é']", "c-1", "d-é", 'e-é'] def test_queue_one_key(): key = queue_one_key("example", {}) assert key == "qo_example" def test_queue_one_key_kwargs(): key = queue_one_key("example", {'pk': 10}) assert key == "qo_example_pk-10" def test_queue_one_key_kwargs_restrict_keys(): key = queue_one_key("example", {'pk': 10, 'id': 10}, restrict_to=['pk']) assert key == "qo_example_pk-10" @pytest.mark.skipif(six.PY3, reason='requires python 2') def test_queue_one_key_unicode_py2(): key = queue_one_key(u"éxample", {'a': u'é', u'b': 'é'}) assert key == "qo_\xc3\xa9xample_a-\xc3\xa9_b-\xc3\xa9" @pytest.mark.skipif(six.PY2, reason='requires python 3') def test_queue_one_key_unicode_py3(): key = queue_one_key(u"éxample", {'a': u'é', u'b': 'é'}) assert key == "qo_éxample_a-é_b-é"<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright (C) 2017,2019 Rodrigo Jose Hernandez Cordoba # # 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. bl_info = { "name": "AeonGames Skeleton Format (.skl)", "author": "Rodrigo Hernandez", "version": (1, 0, 0), "blender": (2, 80, 0), "location": "File > Export > Export AeonGames Skeleton", "description": "Exports an armature to an AeonGames Skeleton (SKL) file", "warning": "", "wiki_url": "", "tracker_url": "", "category": "Import-Export"} import bpy from . import export def skl_menu_func(self, context): self.layout.operator( export.SKL_OT_exporter.bl_idname, text="AeonGames Skeleton (.skl)") def register(): bpy.utils.register_class(export.SKL_OT_exporter) bpy.types.TOPBAR_MT_file_export.append(skl_menu_func)<|fim▁hole|> if __name__ == "__main__": register()<|fim▁end|>
<|file_name|>core-getapp.py<|end_file_name|><|fim▁begin|># core-getapp.py from wax import * class MainFrame(Frame): def Body(self):<|fim▁hole|> app = core.GetApp() print app assert isinstance(app, Application) app = Application(MainFrame, title="core-getapp") app.Run()<|fim▁end|>
<|file_name|>parser_tests.rs<|end_file_name|><|fim▁begin|>#[cfg(test)] mod tests { use model::{Model, TemplateParameter}; use std::fs::File; use std::io::Write; use clang::{Clang, Index}; use tempdir::TempDir; use serde_json; use std::fmt::Debug; use response_file::ExtendWithResponseFile; const INTERFACE: &'static str = r#" namespace foo { namespace sample { struct Interface { virtual ~Interface() = default; virtual void method(int foo) = 0; virtual int foo(double bar) = 0; virtual bool baz() {return true}; }; }} "#; const TEMPLATE_INTERFACE: &'static str = r#" namespace foo { namespace bar { template <typename T, typename U, class V> class Baz { virtual ~Baz() = default; Baz(const Baz&) = delete;<|fim▁hole|> virtual bool boo() = 0; }; }} "#; fn create_model(input: &str) -> Model { create_model_with_args(input, &[&"-x", &"c++", &"-std=c++14"]) } fn create_model_with_args<S: AsRef<str> + Debug>(input: &str, args: &[S]) -> Model { println!("input: {:?} args: {:?}", input, args); let tmp_dir = TempDir::new("cpp-codegen").expect("create temp dir"); let file_path = tmp_dir.path().join("interface.h"); let mut tmp_file = File::create(&file_path).expect("create temp file"); tmp_file.write(input.as_bytes()).expect("write file"); let clang = Clang::new().expect("instantiate clang"); let index = Index::new(&clang, false, false); let tu = index.parser(&file_path) .arguments(args) .parse() .expect("parse interface"); Model::new(&tu) } #[test] fn should_parse() { create_model(INTERFACE); } #[test] fn should_list_namespaces() { let model = create_model(INTERFACE); assert!(model.interfaces[0].namespaces == vec!["foo".to_string(), "sample".to_string()]); } #[test] fn should_not_include_destructors() { let model = create_model(INTERFACE); assert!(!model.interfaces[0] .clone() .methods .into_iter() .any(|x| x.name == "~Interface")); } #[test] fn should_parse_template_class() { create_model(TEMPLATE_INTERFACE); } #[test] fn should_list_template_parameters() { let model = create_model(TEMPLATE_INTERFACE); assert!(model.interfaces.len() > 0); assert_eq!(model.interfaces[0] .clone() .template_parameters .unwrap(), vec![TemplateParameter { type_name: "T".to_string() }, TemplateParameter { type_name: "U".to_string() }, TemplateParameter { type_name: "V".to_string() }]); } #[test] fn should_generate_random_names_for_anonymous_method_arguments() { const INTERFACE_WITH_NAMELESS_ARGUMENT_METHODS: &'static str = r#" struct Foo { virtual void noArgumentName(double) = 0; }; "#; let model = create_model(INTERFACE_WITH_NAMELESS_ARGUMENT_METHODS); assert!(serde_json::ser::to_string(&model.interfaces[0].methods[0].arguments[0].name) .unwrap() .len() > 0) } #[test] fn should_parse_template_methods() { const INTERFACE_WITH_TEMPLATE_METHODS: &'static str = r#" struct Foo { template <typename T> void foo(T bar); }; "#; let model = create_model(INTERFACE_WITH_TEMPLATE_METHODS); assert_eq!(model.interfaces[0] .clone() .methods[0] .clone() .template_arguments .unwrap(), vec![TemplateParameter { type_name: "T".to_string() }]) } #[test] fn should_parse_arguments_with_namespaced_types() { const INTERFACE_WITH_NAMESPACED_METHOD_PARAMETERS: &'static str = r#" namespace a { namespace b { using c = int; }} struct A { virtual void method(a::b::c abc); }; "#; let model = create_model(INTERFACE_WITH_NAMESPACED_METHOD_PARAMETERS); println!("{:?}", model); assert_eq!(model.interfaces[0] .clone() .methods[0] .clone() .arguments[0] .argument_type, "a::b::c".to_string()); assert_eq!(model.interfaces[0] .clone() .methods[0] .clone() .arguments[0] .name, Some("abc".to_string())); } #[test] fn should_support_response_file() { const INTERFACE_WITH_RESPONSE_FILE_DEFINE: &'static str = r#" #ifdef FLAG struct A { virtual void method(int abc); }; #endif "#; const RESPONSE_FILE: &'static str = "-x;c++;-std=c++14;-DFLAG"; let tmp_dir = TempDir::new("cpp-codegen").expect("create temp dir"); let response_file_path = tmp_dir.path().join("interface.rsp"); let mut response_file = File::create(&response_file_path).expect("create temp file"); response_file.write(RESPONSE_FILE.as_bytes()).expect("write file"); let model = create_model_with_args(INTERFACE_WITH_RESPONSE_FILE_DEFINE, &vec!["@".to_string() + &response_file_path.to_string_lossy()] .into_iter() .extend_with_response_file() .collect::<Vec<_>>()); assert_eq!(model.interfaces[0].name, "A".to_string()); } }<|fim▁end|>
<|file_name|>chart.js<|end_file_name|><|fim▁begin|>'use strict'; /* Controllers */ app // Flot Chart controller .controller('FlotChartDemoCtrl', ['$scope', function($scope) { $scope.d = [ [1,6.5],[2,6.5],[3,7],[4,8],[5,7.5],[6,7],[7,6.8],[8,7],[9,7.2],[10,7],[11,6.8],[12,7] ]; $scope.d0_1 = [ [0,7],[1,6.5],[2,12.5],[3,7],[4,9],[5,6],[6,11],[7,6.5],[8,8],[9,7] ]; $scope.d0_2 = [ [0,4],[1,4.5],[2,7],[3,4.5],[4,3],[5,3.5],[6,6],[7,3],[8,4],[9,3] ]; $scope.d1_1 = [ [10, 120], [20, 70], [30, 70], [40, 60] ]; $scope.d1_2 = [ [10, 50], [20, 60], [30, 90], [40, 35] ]; $scope.d1_3 = [ [10, 80], [20, 40], [30, 30], [40, 20] ]; $scope.d2 = []; for (var i = 0; i < 20; ++i) { $scope.d2.push([i, Math.round( Math.sin(i)*100)/100] ); } $scope.d3 = [ { label: "iPhone5S", data: 40 }, { label: "iPad Mini", data: 10 }, { label: "iPad Mini Retina", data: 20 }, { label: "iPhone4S", data: 12 }, { label: "iPad Air", data: 18 } ]; $scope.refreshData = function(){ $scope.d0_1 = $scope.d0_2; }; $scope.getRandomData = function() { var data = [], totalPoints = 150; if (data.length > 0) data = data.slice(1); while (data.length < totalPoints) { var prev = data.length > 0 ? data[data.length - 1] : 50, y = prev + Math.random() * 10 - 5; if (y < 0) { y = 0; } else if (y > 100) { y = 100; } data.push(Math.round(y*100)/100); } // Zip the generated y values with the x values var res = []; for (var i = 0; i < data.length; ++i) { res.push([i, data[i]]) } return res;<|fim▁hole|> } $scope.d4 = $scope.getRandomData(); }]);<|fim▁end|>
<|file_name|>ColorRGBProperty.cpp<|end_file_name|><|fim▁begin|>/* * ColorRGB property file * * This file is part of the "ForkENGINE" (Copyright (c) 2014 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "Engine/Component/Component.h" #include "IO/FileSystem/File.h" namespace Fork { namespace Engine { Component::Property::Types Component::ColorRGBProperty::Type() const { return Types::ColorRGB; } void Component::ColorRGBProperty::WriteToFile(IO::File& file) const { file.Write<unsigned char>(value.r); file.Write<unsigned char>(value.g); file.Write<unsigned char>(value.b); } void Component::ColorRGBProperty::ReadFromFile(IO::File& file) { value.r = file.Read<unsigned char>(); value.g = file.Read<unsigned char>(); value.b = file.Read<unsigned char>(); } void Component::ColorRGBProperty::WriteToVariant(IO::Variant& variant) const { variant = value;<|fim▁hole|> value = variant.GetColorRGB(); } } // /namespace Engine } // /namespace Fork // ========================<|fim▁end|>
} void Component::ColorRGBProperty::ReadFromVariant(const IO::Variant& variant) {
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import os <|fim▁hole|> return theme_dir<|fim▁end|>
def get_html_theme_path(): theme_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
<|file_name|>admin.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django import forms from django.contrib import admin from django.contrib.auth.admin import UserAdmin as AuthUserAdmin from django.contrib.auth.forms import UserChangeForm, UserCreationForm from django.utils.translation import ugettext_lazy as _ from .models import User class MyUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = User class MyUserCreationForm(UserCreationForm): error_message = UserCreationForm.error_messages.update({ 'duplicate_username': _("This username has already been taken.") })<|fim▁hole|> class Meta(UserCreationForm.Meta): model = User def clean_username(self): username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError(self.error_messages['duplicate_username']) @admin.register(User) class UserAdmin(AuthUserAdmin): form = MyUserChangeForm add_form = MyUserCreationForm<|fim▁end|>
<|file_name|>bookmark.js<|end_file_name|><|fim▁begin|>module.exports = [<|fim▁hole|>].join(' ');<|fim▁end|>
'M6 2 L26 2 L26 30', 'L16 24 L6 30 Z'
<|file_name|>mentions.component.spec.ts<|end_file_name|><|fim▁begin|>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { MentionsComponent } from './mentions.component'; describe('MentionsComponent', () => {<|fim▁hole|> let fixture: ComponentFixture<MentionsComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ MentionsComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(MentionsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });<|fim▁end|>
let component: MentionsComponent;
<|file_name|>hangman.py<|end_file_name|><|fim▁begin|># This is a hangman game. # Your game must do the following things. # Everytime a user guesses a character, it should tell them if their character # is in the secret word or not. # # Also, it should print the guessed character in the following format # if the secret word is unicorn and the user guessed the letter 'n' # you program should print _n____n # # It should also print a picture of the current state of the hanged man. # # If the user guesses a letter he already guessed, give them a warning. # # The user can make at most 6 mistakes. import random # don't worry about these lines. from hangman_pics import HANGMANPICS LIST_OF_WORDS = ['hangman', 'chairs', 'backpack', 'bodywash', 'clothing', 'computer', 'python', 'program', 'glasses', 'sweatshirt', 'sweatpants', 'mattress', 'friends', 'clocks', 'biology', 'algebra', 'suitcase', 'knives', 'ninjas', 'shampoo'] # First let's write a function to select a random word from the list of words. def getSecretWord(): # this line generates a random number use it to index into the list of words # and return a secret word. rnd = random.randint(0, len(LIST_OF_WORDS) - 1) return ... secret_word = getSecretWord() # functions help us organize our code! mistakes = 0 # Now create an empty list to keep track of the letters the user guessed def string_contains_character(c, word): # copy your function from lesson6 here. def hide_word(guesses, secret_word): hidden_word = "" for letter in secret_word: if letter in guesses: ... # This is the while(True): guess = raw_input() # Check if the guess was a letter that the user already guessed. If so,<|fim▁hole|> # give them a warning and go back to the beginning of the loop. # If this is a new guess, add it to the list of letters the user guessed. # Maybe you could use one of the list methods... # Check if the new guess is in the secret word, using the function # string_contains_character you wrote on lesson6. # If the user made a mistake, increase their number of mistakes and let them # know! # Now, complete the function hide_word, which takes in the guesses made and # the secret_word and returns a the word in a hidden format. Remember, if the # letter was in the guesses, it should appear in the word, if it's not it # should appear as an underscore "_" # # If your hidden word has no underscores, the user won! Let them know about # that and break out of the loop print(HANGMANPICS[mistakes]) # this line will print a picture of the hanged man # If the user made 6 mistakes, tell them the game is over and break out of the # loop.<|fim▁end|>
<|file_name|>coord_transform.py<|end_file_name|><|fim▁begin|>""" S.Tomin and I.Zagorodnov, 2017, DESY/XFEL """ from ocelot.common.globals import * import logging logger = logging.getLogger(__name__) try: import numexpr as ne ne_flag = True except: logger.debug("coord_transform.py: module NUMEXPR is not installed. Install it to speed up calculation") ne_flag = False def xp_2_xxstg_mad(xp, xxstg, gamref):<|fim▁hole|> pref = m_e_eV * np.sqrt(gamref ** 2 - 1) betaref = np.sqrt(1 - gamref ** -2) u = np.c_[xp[3], xp[4], xp[5]] if ne_flag: sum_u2 = ne.evaluate('sum(u * u, 1)') gamma = ne.evaluate('sqrt(1 + sum_u2 / m_e_eV ** 2)') beta = ne.evaluate('sqrt(1 - gamma ** -2)') else: gamma = np.sqrt(1 + np.sum(u * u, 1) / m_e_eV ** 2) beta = np.sqrt(1 - gamma ** -2) if np.__version__ > "1.8": p0 = np.linalg.norm(u, 2, 1).reshape((N, 1)) else: p0 = np.sqrt(u[:, 0] ** 2 + u[:, 1] ** 2 + u[:, 2] ** 2).reshape((N, 1)) u = u / p0 u0 = u[:, 0] u1 = u[:, 1] u2 = u[:, 2] if ne_flag: xp0 = xp[0] xp1 = xp[1] xp2 = xp[2] cdt = ne.evaluate('-xp2 / (beta * u2)') xxstg[0] = ne.evaluate('xp0 + beta * u0 * cdt') xxstg[2] = ne.evaluate('xp1 + beta * u1 * cdt') xxstg[5] = ne.evaluate('(gamma / gamref - 1) / betaref') else: cdt = -xp[2] / (beta * u2) xxstg[0] = xp[0] + beta * u0 * cdt xxstg[2] = xp[1] + beta * u1 * cdt xxstg[5] = (gamma / gamref - 1) / betaref xxstg[4] = cdt xxstg[1] = xp[3] / pref xxstg[3] = xp[4] / pref return xxstg def xxstg_2_xp_mad(xxstg, xp, gamref): # from mad format N = xxstg.shape[1] #pref = m_e_eV * np.sqrt(gamref ** 2 - 1) betaref = np.sqrt(1 - gamref ** -2) if ne_flag: xxstg1 = xxstg[1] xxstg3 = xxstg[3] xxstg5 = xxstg[5] gamma = ne.evaluate('(betaref * xxstg5 + 1) * gamref') beta = ne.evaluate('sqrt(1 - gamma ** -2)') pz2pref = ne.evaluate('sqrt(((gamma * beta) / (gamref * betaref)) ** 2 - xxstg1 ** 2 - xxstg3 ** 2)') else: gamma = (betaref * xxstg[5] + 1) * gamref beta = np.sqrt(1 - gamma ** -2) pz2pref = np.sqrt(((gamma * beta) / (gamref * betaref)) ** 2 - xxstg[1] ** 2 - xxstg[3] ** 2) u = np.c_[xxstg[1] / pz2pref, xxstg[3] / pz2pref, np.ones(N)] if np.__version__ > "1.8": norm = np.linalg.norm(u, 2, 1).reshape((N, 1)) else: norm = np.sqrt(u[:, 0] ** 2 + u[:, 1] ** 2 + u[:, 2] ** 2).reshape((N, 1)) u = u / norm u0 = u[:, 0] u1 = u[:, 1] u2 = u[:, 2] if ne_flag: xxstg0 = xxstg[0] xxstg2 = xxstg[2] xxstg4 = xxstg[4] xp[0] = ne.evaluate('xxstg0 - u0 * beta * xxstg4') xp[1] = ne.evaluate('xxstg2 - u1 * beta * xxstg4') xp[2] = ne.evaluate('-u2 * beta * xxstg4') xp[3] = ne.evaluate('u0 * gamma * beta * m_e_eV') xp[4] = ne.evaluate('u1 * gamma * beta * m_e_eV') xp[5] = ne.evaluate('u2 * gamma * beta * m_e_eV') else: xp[0] = xxstg[0] - u0 * beta * xxstg[4] xp[1] = xxstg[2] - u1 * beta * xxstg[4] xp[2] = -u2 * beta * xxstg[4] xp[3] = u0 * gamma * beta * m_e_eV xp[4] = u1 * gamma * beta * m_e_eV xp[5] = u2 * gamma * beta * m_e_eV return xp<|fim▁end|>
# to mad format N = xp.shape[1]
<|file_name|>__openerp__.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # # Copyright (C) 2015 Didotech srl (<http://www.didotech.com>). # # All Rights Reserved # # 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/>. # ############################################################################## { "name": "Sale Order Analysis", "version": "3.1.1.2", "author": "Didotech SRL", "website": "http://www.didotech.com", "category": "Sales Management", "description": """ Module permits to create a simple analysis on sale shop based on date, sales team, user """, "depends": [ 'sale_order_confirm', ], "data": [ 'sale/sale_shop_view.xml'<|fim▁hole|> ], "active": False, "installable": True, }<|fim▁end|>
<|file_name|>definitions.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # This file is part of INSPIRE. # Copyright (C) 2014, 2015 CERN. # # INSPIRE 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. # # INSPIRE 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<|fim▁hole|># GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with INSPIRE. If not, see <http://www.gnu.org/licenses/>. # # In applying this licence, CERN does not waive the privileges and immunities # granted to it by virtue of its status as an Intergovernmental Organization # or submit itself to any jurisdiction. from invenio_workflows.definitions import WorkflowBase class HarvestingWorkflowBase(WorkflowBase): """Base harvesting definition.""" @staticmethod def get_title(bwo, **kwargs): """Return the value to put in the title column of HoldingPen.""" args = bwo.get_extra_data().get("args", {}) return "Summary of {0} harvesting from {1} to {2}".format( args.get("workflow", "unknown"), args.get("from_date", "unknown"), args.get("to_date", "unknown"), ) @staticmethod def get_description(bwo, **kwargs): """Return the value to put in the title column of HoldingPen.""" return "No description. See log for details." @staticmethod def formatter(obj, **kwargs): """Format the object.""" return "No data. See log for details."<|fim▁end|>
<|file_name|>formats-data.js<|end_file_name|><|fim▁begin|>'use strict'; exports.BattleFormatsData = { bulbasaur: { randomBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "hiddenpowerice", "sludgebomb", "powerwhip", "leechseed", "synthesis"], randomDoubleBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "hiddenpowerice", "sludgebomb", "powerwhip", "protect"], eventPokemon: [ {"generation": 3, "level": 70, "moves":["sweetscent", "growth", "solarbeam", "synthesis"]}, {"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "growl", "leechseed", "vinewhip"]}, {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tackle", "growl", "leechseed", "vinewhip"]}, {"generation": 5, "level": 1, "shiny": 1, "ivs": {"def": 31}, "isHidden": false, "moves":["falseswipe", "block", "frenzyplant", "weatherball"]}, {"generation": 6, "level": 5, "isHidden": false, "moves":["growl", "leechseed", "vinewhip", "poisonpowder"], "pokeball": "cherishball"}, {"generation": 6, "level": 5, "isHidden": true, "moves":["tackle", "growl", "celebrate"], "pokeball": "cherishball"}, ], tier: "LC", }, ivysaur: { randomBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "hiddenpowerice", "sludgebomb", "powerwhip", "leechseed", "synthesis"], randomDoubleBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "hiddenpowerice", "sludgebomb", "powerwhip", "protect"], tier: "NFE", }, venusaur: { randomBattleMoves: ["sunnyday", "sleeppowder", "gigadrain", "hiddenpowerfire", "sludgebomb", "leechseed", "substitute"], randomDoubleBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "hiddenpowerice", "sludgebomb", "powerwhip", "protect"], eventPokemon: [ {"generation": 6, "level": 100, "isHidden": true, "moves":["solarbeam", "frenzyplant", "synthesis", "grasspledge"], "pokeball": "cherishball"}, ], tier: "RU", }, venusaurmega: { randomBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "sludgebomb", "leechseed", "synthesis", "earthquake", "knockoff"], randomDoubleBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "hiddenpowerice", "sludgebomb", "powerwhip", "protect"], requiredItem: "Venusaurite", tier: "OU", }, charmander: { randomBattleMoves: ["flamethrower", "overheat", "dragonpulse", "hiddenpowergrass", "fireblast"], randomDoubleBattleMoves: ["heatwave", "dragonpulse", "hiddenpowergrass", "fireblast", "protect"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "growl", "ember"]}, {"generation": 4, "level": 40, "gender": "M", "nature": "Mild", "moves":["return", "hiddenpower", "quickattack", "howl"], "pokeball": "cherishball"}, {"generation": 4, "level": 40, "gender": "M", "nature": "Naive", "moves":["return", "hiddenpower", "quickattack", "howl"], "pokeball": "cherishball"}, {"generation": 4, "level": 40, "gender": "M", "nature": "Naughty", "moves":["return", "hiddenpower", "quickattack", "howl"], "pokeball": "cherishball"}, {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["scratch", "growl", "ember", "smokescreen"]}, {"generation": 4, "level": 40, "gender": "M", "nature": "Hardy", "moves":["return", "hiddenpower", "quickattack", "howl"], "pokeball": "cherishball"}, {"generation": 5, "level": 1, "shiny": 1, "ivs": {"spe": 31}, "isHidden": false, "moves":["falseswipe", "block", "blastburn", "acrobatics"]}, {"generation": 6, "level": 5, "isHidden": false, "moves":["growl", "ember", "smokescreen", "dragonrage"], "pokeball": "cherishball"}, {"generation": 6, "level": 5, "isHidden": true, "moves":["scratch", "growl", "celebrate"], "pokeball": "cherishball"}, ], tier: "LC", }, charmeleon: { randomBattleMoves: ["flamethrower", "overheat", "dragonpulse", "hiddenpowergrass", "fireblast", "dragondance", "flareblitz", "shadowclaw", "dragonclaw"], randomDoubleBattleMoves: ["heatwave", "dragonpulse", "hiddenpowergrass", "fireblast", "protect"], tier: "NFE", }, charizard: { randomBattleMoves: ["fireblast", "airslash", "focusblast", "roost", "swordsdance", "flamecharge", "acrobatics", "earthquake", "willowisp"], randomDoubleBattleMoves: ["heatwave", "fireblast", "airslash", "overheat", "dragonpulse", "roost", "tailwind", "protect"], eventPokemon: [ {"generation": 3, "level": 70, "moves":["wingattack", "slash", "dragonrage", "firespin"]}, {"generation": 6, "level": 36, "gender": "M", "isHidden": false, "moves":["firefang", "flameburst", "airslash", "inferno"], "pokeball": "cherishball"}, {"generation": 6, "level": 36, "gender": "M", "isHidden": false, "moves":["firefang", "airslash", "dragonclaw", "dragonrage"], "pokeball": "cherishball"}, {"generation": 6, "level": 36, "shiny": true, "gender": "M", "isHidden": false, "moves":["overheat", "solarbeam", "focusblast", "holdhands"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "isHidden": true, "moves":["flareblitz", "blastburn", "scaryface", "firepledge"], "pokeball": "cherishball"}, {"generation": 7, "level": 40, "gender": "M", "nature": "Jolly", "isHidden": false, "moves":["flareblitz", "dragonclaw", "fly", "dragonrage"], "pokeball": "cherishball"}, {"generation": 7, "level": 40, "gender": "M", "nature": "Adamant", "isHidden": false, "moves":["flamethrower", "dragonrage", "slash", "seismictoss"], "pokeball": "pokeball"}, ], tier: "BL4", }, charizardmegax: { randomBattleMoves: ["dragondance", "flareblitz", "dragonclaw", "earthquake", "roost", "willowisp"], randomDoubleBattleMoves: ["dragondance", "flareblitz", "dragonclaw", "earthquake", "rockslide", "roost", "substitute"], requiredItem: "Charizardite X", tier: "OU", }, charizardmegay: { randomBattleMoves: ["fireblast", "airslash", "roost", "solarbeam", "focusblast", "dragonpulse"], randomDoubleBattleMoves: ["heatwave", "fireblast", "airslash", "roost", "solarbeam", "focusblast", "protect"], requiredItem: "Charizardite Y", tier: "OU", }, squirtle: { randomBattleMoves: ["icebeam", "hydropump", "rapidspin", "scald", "aquajet", "toxic"], randomDoubleBattleMoves: ["muddywater", "icebeam", "hydropump", "fakeout", "scald", "followme", "icywind", "protect"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "tailwhip", "bubble", "withdraw"]}, {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tackle", "tailwhip", "bubble", "withdraw"]}, {"generation": 5, "level": 1, "shiny": 1, "ivs": {"hp": 31}, "isHidden": false, "moves":["falseswipe", "block", "hydrocannon", "followme"]}, {"generation": 6, "level": 5, "isHidden": false, "moves":["tailwhip", "watergun", "withdraw", "bubble"], "pokeball": "cherishball"}, {"generation": 6, "level": 5, "isHidden": true, "moves":["tackle", "tailwhip", "celebrate"], "pokeball": "cherishball"}, ], tier: "LC", }, wartortle: { randomBattleMoves: ["icebeam", "hydropump", "rapidspin", "scald", "aquajet", "toxic"], randomDoubleBattleMoves: ["muddywater", "icebeam", "hydropump", "fakeout", "scald", "followme", "icywind", "protect"], tier: "NFE", }, blastoise: { randomBattleMoves: ["icebeam", "rapidspin", "scald", "toxic", "dragontail", "roar"], randomDoubleBattleMoves: ["muddywater", "icebeam", "hydropump", "fakeout", "scald", "followme", "icywind", "protect", "waterspout"], eventPokemon: [ {"generation": 3, "level": 70, "moves":["protect", "raindance", "skullbash", "hydropump"]}, {"generation": 6, "level": 100, "isHidden": true, "moves":["hydropump", "hydrocannon", "irondefense", "waterpledge"], "pokeball": "cherishball"}, ], tier: "RU", }, blastoisemega: { randomBattleMoves: ["icebeam", "hydropump", "rapidspin", "scald", "dragontail", "darkpulse", "aurasphere"], randomDoubleBattleMoves: ["muddywater", "icebeam", "hydropump", "fakeout", "scald", "darkpulse", "aurasphere", "followme", "icywind", "protect"], requiredItem: "Blastoisinite", tier: "UU", }, caterpie: { randomBattleMoves: ["bugbite", "snore", "tackle", "electroweb"], tier: "LC", }, metapod: { randomBattleMoves: ["snore", "bugbite", "tackle", "electroweb"], tier: "NFE", }, butterfree: { randomBattleMoves: ["sleeppowder", "quiverdance", "bugbuzz", "airslash", "gigadrain", "substitute"], randomDoubleBattleMoves: ["quiverdance", "bugbuzz", "substitute", "sleeppowder", "airslash", "shadowball", "protect"], eventPokemon: [ {"generation": 3, "level": 30, "moves":["morningsun", "psychic", "sleeppowder", "aerialace"]}, ], tier: "PU", }, weedle: { randomBattleMoves: ["bugbite", "stringshot", "poisonsting", "electroweb"], tier: "LC", }, kakuna: { randomBattleMoves: ["electroweb", "bugbite", "irondefense", "poisonsting"], tier: "NFE", }, beedrill: { randomBattleMoves: ["toxicspikes", "tailwind", "uturn", "endeavor", "poisonjab", "knockoff"], randomDoubleBattleMoves: ["xscissor", "uturn", "poisonjab", "drillrun", "brickbreak", "knockoff", "protect", "stringshot"], eventPokemon: [ {"generation": 3, "level": 30, "moves":["batonpass", "sludgebomb", "twineedle", "swordsdance"]}, ], tier: "PU", }, beedrillmega: { randomBattleMoves: ["xscissor", "swordsdance", "uturn", "poisonjab", "drillrun", "knockoff"], randomDoubleBattleMoves: ["xscissor", "uturn", "substitute", "poisonjab", "drillrun", "knockoff", "protect"], requiredItem: "Beedrillite", tier: "UU", }, pidgey: { randomBattleMoves: ["roost", "bravebird", "heatwave", "return", "workup", "uturn", "thief"], randomDoubleBattleMoves: ["bravebird", "heatwave", "return", "uturn", "tailwind", "protect"], tier: "LC", }, pidgeotto: { randomBattleMoves: ["roost", "bravebird", "heatwave", "return", "workup", "uturn", "thief"], randomDoubleBattleMoves: ["bravebird", "heatwave", "return", "uturn", "tailwind", "protect"], eventPokemon: [ {"generation": 3, "level": 30, "abilities":["keeneye"], "moves":["refresh", "wingattack", "steelwing", "featherdance"]}, ], tier: "NFE", }, pidgeot: { randomBattleMoves: ["roost", "bravebird", "heatwave", "return", "doubleedge", "uturn", "hurricane"], randomDoubleBattleMoves: ["bravebird", "heatwave", "return", "doubleedge", "uturn", "tailwind", "protect"], eventPokemon: [ {"generation": 5, "level": 61, "gender": "M", "nature": "Naughty", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "abilities":["keeneye"], "moves":["whirlwind", "wingattack", "skyattack", "mirrormove"], "pokeball": "cherishball"}, ], tier: "PU", }, pidgeotmega: { randomBattleMoves: ["roost", "heatwave", "uturn", "hurricane", "defog"], randomDoubleBattleMoves: ["tailwind", "heatwave", "uturn", "hurricane", "protect"], requiredItem: "Pidgeotite", tier: "UU", }, rattata: { randomBattleMoves: ["facade", "flamewheel", "suckerpunch", "uturn", "wildcharge", "thunderwave", "crunch", "revenge"], randomDoubleBattleMoves: ["facade", "flamewheel", "suckerpunch", "uturn", "wildcharge", "superfang", "crunch", "protect"], tier: "LC", }, rattataalola: { tier: "LC", }, raticate: { randomBattleMoves: ["protect", "facade", "flamewheel", "suckerpunch", "uturn", "swordsdance"], randomDoubleBattleMoves: ["facade", "flamewheel", "suckerpunch", "uturn", "crunch", "protect"], eventPokemon: [ {"generation": 3, "level": 34, "moves":["refresh", "superfang", "scaryface", "hyperfang"]}, ], tier: "PU", }, raticatealola: { randomBattleMoves: ["swordsdance", "return", "suckerpunch", "crunch", "doubleedge"], randomDoubleBattleMoves: ["doubleedge", "suckerpunch", "protect", "crunch", "uturn"], tier: "PU", }, spearow: { randomBattleMoves: ["return", "drillpeck", "doubleedge", "uturn", "quickattack", "pursuit", "drillrun", "featherdance"], randomDoubleBattleMoves: ["return", "drillpeck", "doubleedge", "uturn", "quickattack", "drillrun", "protect"], eventPokemon: [ {"generation": 3, "level": 22, "moves":["batonpass", "falseswipe", "leer", "aerialace"]}, ], tier: "LC", }, fearow: { randomBattleMoves: ["return", "drillpeck", "doubleedge", "uturn", "pursuit", "drillrun"], randomDoubleBattleMoves: ["return", "drillpeck", "doubleedge", "uturn", "quickattack", "drillrun", "protect"], tier: "PU", }, ekans: { randomBattleMoves: ["coil", "gunkshot", "glare", "suckerpunch", "earthquake", "rest"], randomDoubleBattleMoves: ["gunkshot", "seedbomb", "suckerpunch", "aquatail", "earthquake", "rest", "rockslide", "protect"], eventPokemon: [ {"generation": 3, "level": 14, "gender": "F", "nature": "Docile", "ivs": {"hp": 26, "atk": 28, "def": 6, "spa": 14, "spd": 30, "spe": 11}, "abilities":["shedskin"], "moves":["leer", "wrap", "poisonsting", "bite"]}, {"generation": 3, "level": 10, "gender": "M", "moves":["wrap", "leer", "poisonsting"]}, ], tier: "LC", }, arbok: { randomBattleMoves: ["coil", "gunkshot", "suckerpunch", "aquatail", "earthquake", "rest"], randomDoubleBattleMoves: ["gunkshot", "suckerpunch", "aquatail", "crunch", "earthquake", "rest", "rockslide", "protect"], eventPokemon: [ {"generation": 3, "level": 33, "moves":["refresh", "sludgebomb", "glare", "bite"]}, ], tier: "PU", }, pichu: { randomBattleMoves: ["fakeout", "volttackle", "encore", "irontail", "toxic", "thunderbolt"], randomDoubleBattleMoves: ["fakeout", "volttackle", "encore", "irontail", "protect", "thunderbolt"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["thundershock", "charm", "surf"]}, {"generation": 3, "level": 5, "shiny": 1, "moves":["thundershock", "charm", "wish"]}, {"generation": 3, "level": 5, "shiny": 1, "moves":["thundershock", "charm", "teeterdance"]}, {"generation": 3, "level": 5, "shiny": 1, "moves":["thundershock", "charm", "followme"]}, {"generation": 4, "level": 1, "moves":["volttackle", "thunderbolt", "grassknot", "return"]}, {"generation": 4, "level": 30, "shiny": true, "gender": "M", "nature": "Jolly", "moves":["charge", "volttackle", "endeavor", "endure"], "pokeball": "cherishball"}, ], tier: "LC", }, pichuspikyeared: { eventPokemon: [ {"generation": 4, "level": 30, "gender": "F", "nature": "Naughty", "moves":["helpinghand", "volttackle", "swagger", "painsplit"]}, ], eventOnly: true, gen: 4, tier: "Illegal", }, pikachu: { randomBattleMoves: ["thunderbolt", "volttackle", "voltswitch", "grassknot", "hiddenpowerice", "brickbreak", "extremespeed", "encore", "substitute", "knockoff"], randomDoubleBattleMoves: ["fakeout", "thunderbolt", "volttackle", "voltswitch", "grassknot", "hiddenpowerice", "brickbreak", "extremespeed", "encore", "substitute", "knockoff", "protect", "discharge"], eventPokemon: [ {"generation": 3, "level": 50, "moves":["thunderbolt", "agility", "thunder", "lightscreen"]}, {"generation": 3, "level": 10, "moves":["thundershock", "growl", "tailwhip", "thunderwave"]}, {"generation": 3, "level": 10, "moves":["fly", "tailwhip", "growl", "thunderwave"]}, {"generation": 3, "level": 5, "moves":["surf", "growl", "tailwhip", "thunderwave"]}, {"generation": 3, "level": 10, "moves":["fly", "growl", "tailwhip", "thunderwave"]}, {"generation": 3, "level": 10, "moves":["thundershock", "growl", "thunderwave", "surf"]}, {"generation": 3, "level": 70, "moves":["thunderbolt", "thunder", "lightscreen", "fly"]}, {"generation": 3, "level": 70, "moves":["thunderbolt", "thunder", "lightscreen", "surf"]}, {"generation": 3, "level": 70, "moves":["thunderbolt", "thunder", "lightscreen", "agility"]}, {"generation": 4, "level": 10, "gender": "F", "nature": "Hardy", "moves":["surf", "volttackle", "tailwhip", "thunderwave"]}, {"generation": 3, "level": 10, "gender": "M", "moves":["thundershock", "growl", "tailwhip", "thunderwave"]}, {"generation": 4, "level": 50, "gender": "M", "nature": "Hardy", "moves":["surf", "thunderbolt", "lightscreen", "quickattack"], "pokeball": "cherishball"}, {"generation": 4, "level": 20, "gender": "F", "nature": "Bashful", "moves":["present", "quickattack", "thundershock", "tailwhip"], "pokeball": "cherishball"}, {"generation": 4, "level": 20, "gender": "M", "nature": "Jolly", "moves":["grassknot", "thunderbolt", "flash", "doubleteam"], "pokeball": "cherishball"}, {"generation": 4, "level": 40, "gender": "M", "nature": "Modest", "moves":["surf", "thunder", "protect"], "pokeball": "cherishball"}, {"generation": 4, "level": 20, "gender": "F", "nature": "Bashful", "moves":["quickattack", "thundershock", "tailwhip", "present"], "pokeball": "cherishball"}, {"generation": 4, "level": 40, "gender": "M", "nature": "Mild", "moves":["surf", "thunder", "protect"], "pokeball": "cherishball"}, {"generation": 4, "level": 20, "gender": "F", "nature": "Bashful", "moves":["present", "quickattack", "thunderwave", "tailwhip"], "pokeball": "cherishball"}, {"generation": 4, "level": 30, "gender": "M", "nature": "Naughty", "moves":["lastresort", "present", "thunderbolt", "quickattack"], "pokeball": "cherishball"}, {"generation": 4, "level": 50, "gender": "M", "nature": "Relaxed", "moves":["rest", "sleeptalk", "yawn", "snore"], "pokeball": "cherishball"}, {"generation": 4, "level": 20, "gender": "M", "nature": "Docile", "moves":["present", "quickattack", "thundershock", "tailwhip"], "pokeball": "cherishball"}, {"generation": 4, "level": 50, "gender": "M", "nature": "Naughty", "moves":["volttackle", "irontail", "quickattack", "thunderbolt"], "pokeball": "cherishball"}, {"generation": 4, "level": 20, "gender": "M", "nature": "Bashful", "moves":["present", "quickattack", "thundershock", "tailwhip"], "pokeball": "cherishball"}, {"generation": 5, "level": 30, "gender": "F", "isHidden": true, "moves":["sing", "teeterdance", "encore", "electroball"], "pokeball": "cherishball"}, {"generation": 5, "level": 50, "isHidden": false, "moves":["fly", "irontail", "electroball", "quickattack"], "pokeball": "cherishball"}, {"generation": 5, "level": 100, "shiny": 1, "gender": "F", "isHidden": false, "moves":["thunder", "volttackle", "grassknot", "quickattack"], "pokeball": "cherishball"}, {"generation": 5, "level": 50, "shiny": 1, "gender": "F", "isHidden": false, "moves":["extremespeed", "thunderbolt", "grassknot", "brickbreak"], "pokeball": "cherishball"}, {"generation": 5, "level": 50, "gender": "F", "nature": "Timid", "isHidden": true, "moves":["fly", "thunderbolt", "grassknot", "protect"], "pokeball": "cherishball"}, {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["thundershock", "tailwhip", "thunderwave", "headbutt"]}, {"generation": 5, "level": 100, "gender": "M", "isHidden": true, "moves":["volttackle", "quickattack", "feint", "voltswitch"], "pokeball": "cherishball"}, {"generation": 5, "level": 50, "gender": "M", "nature": "Brave", "isHidden": false, "moves":["thunderbolt", "quickattack", "irontail", "electroball"], "pokeball": "cherishball"}, {"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "growl", "playnice", "quickattack"], "pokeball": "cherishball"}, {"generation": 6, "level": 22, "isHidden": false, "moves":["quickattack", "electroball", "doubleteam", "megakick"], "pokeball": "cherishball"}, {"generation": 6, "level": 10, "isHidden": false, "moves":["thunderbolt", "quickattack", "surf", "holdhands"], "pokeball": "cherishball"}, {"generation": 6, "level": 10, "gender": "F", "isHidden": false, "moves":["thunderbolt", "quickattack", "heartstamp", "holdhands"], "pokeball": "healball"}, {"generation": 6, "level": 36, "shiny": true, "isHidden": true, "moves":["thunder", "substitute", "playnice", "holdhands"], "pokeball": "cherishball"}, {"generation": 6, "level": 10, "gender": "F", "isHidden": false, "moves":["playnice", "charm", "nuzzle", "sweetkiss"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "gender": "M", "nature": "Naughty", "isHidden": false, "moves":["thunderbolt", "quickattack", "irontail", "electroball"], "pokeball": "cherishball"}, {"generation": 6, "level": 10, "shiny": true, "isHidden": false, "moves":["teeterdance", "playnice", "tailwhip", "nuzzle"], "pokeball": "cherishball"}, {"generation": 6, "level": 10, "perfectIVs": 2, "isHidden": true, "moves":["fakeout", "encore", "volttackle", "endeavor"], "pokeball": "cherishball"}, {"generation": 6, "level": 99, "isHidden": false, "moves":["happyhour", "playnice", "holdhands", "flash"], "pokeball": "cherishball"}, {"generation": 6, "level": 10, "isHidden": false, "moves":["fly", "surf", "agility", "celebrate"], "pokeball": "cherishball"}, {"generation": 6, "level": 10, "isHidden": false, "moves":["bestow", "holdhands", "return", "playnice"], "pokeball": "healball"}, {"generation": 7, "level": 10, "nature": "Jolly", "isHidden": false, "moves":["celebrate", "growl", "playnice", "quickattack"], "pokeball": "cherishball"}, {"generation": 7, "level": 10, "isHidden": false, "moves":["bestow", "holdhands", "return", "playnice"], "pokeball": "cherishball"}, {"generation": 7, "level": 10, "isHidden": false, "moves":["holdhands", "playnice", "teeterdance", "happyhour"], "pokeball": "cherishball"}, {"generation": 7, "level": 10, "isHidden": false, "moves":["growl", "quickattack", "thundershock", "happyhour"], "pokeball": "cherishball"}, ], tier: "NFE", }, pikachucosplay: { eventPokemon: [ {"generation": 6, "level": 20, "moves":["quickattack", "electroball", "thunderwave", "thundershock"]}, ], eventOnly: true, gen: 6, tier: "Illegal", }, pikachurockstar: { eventPokemon: [ {"generation": 6, "level": 20, "moves":["quickattack", "electroball", "thunderwave", "meteormash"]}, ], eventOnly: true, gen: 6, tier: "Illegal", }, pikachubelle: { eventPokemon: [ {"generation": 6, "level": 20, "moves":["quickattack", "electroball", "thunderwave", "iciclecrash"]}, ], eventOnly: true, gen: 6, tier: "Illegal", }, pikachupopstar: { eventPokemon: [ {"generation": 6, "level": 20, "moves":["quickattack", "electroball", "thunderwave", "drainingkiss"]}, ], eventOnly: true, gen: 6, tier: "Illegal", }, pikachuphd: { eventPokemon: [ {"generation": 6, "level": 20, "moves":["quickattack", "electroball", "thunderwave", "electricterrain"]}, ], eventOnly: true, gen: 6, tier: "Illegal", }, pikachulibre: { eventPokemon: [ {"generation": 6, "level": 20, "moves":["quickattack", "electroball", "thunderwave", "flyingpress"]}, ], eventOnly: true, gen: 6, tier: "Illegal", }, pikachuoriginal: { eventPokemon: [ {"generation": 7, "level": 1, "nature": "Hardy", "moves":["thunderbolt", "quickattack", "thunder", "agility"]}, ], eventOnly: true, gen: 7, tier: "PU", }, pikachuhoenn: { eventPokemon: [ {"generation": 7, "level": 6, "nature": "Hardy", "moves":["thunderbolt", "quickattack", "thunder", "irontail"]}, ], eventOnly: true, gen: 7, tier: "PU", }, pikachusinnoh: { eventPokemon: [ {"generation": 7, "level": 10, "nature": "Hardy", "moves":["thunderbolt", "quickattack", "irontail", "volttackle"]}, ], eventOnly: true, gen: 7, tier: "PU", }, pikachuunova: { eventPokemon: [ {"generation": 7, "level": 14, "nature": "Hardy", "moves":["thunderbolt", "quickattack", "irontail", "volttackle"]}, ], eventOnly: true, gen: 7, tier: "PU", }, pikachukalos: { eventPokemon: [ {"generation": 7, "level": 17, "nature": "Hardy", "moves":["thunderbolt", "quickattack", "irontail", "electroball"]}, ], eventOnly: true, gen: 7, tier: "PU", }, pikachualola: { eventPokemon: [ {"generation": 7, "level": 20, "nature": "Hardy", "moves":["thunderbolt", "quickattack", "irontail", "electroball"]}, ], eventOnly: true, gen: 7, tier: "PU", }, raichu: { randomBattleMoves: ["nastyplot", "encore", "thunderbolt", "grassknot", "hiddenpowerice", "focusblast", "voltswitch"], randomDoubleBattleMoves: ["fakeout", "encore", "thunderbolt", "grassknot", "hiddenpowerice", "focusblast", "voltswitch", "protect"], tier: "PU", }, raichualola: { randomBattleMoves: ["nastyplot", "thunderbolt", "psyshock", "focusblast", "voltswitch", "surf"], randomDoubleBattleMoves: ["thunderbolt", "fakeout", "encore", "psychic", "protect", "voltswitch"], tier: "PU", }, sandshrew: { randomBattleMoves: ["earthquake", "rockslide", "swordsdance", "rapidspin", "xscissor", "stealthrock", "toxic", "knockoff"], randomDoubleBattleMoves: ["earthquake", "rockslide", "swordsdance", "xscissor", "knockoff", "protect"], eventPokemon: [ {"generation": 3, "level": 12, "gender": "M", "nature": "Docile", "ivs": {"hp": 4, "atk": 23, "def": 8, "spa": 31, "spd": 1, "spe": 25}, "moves":["scratch", "defensecurl", "sandattack", "poisonsting"]}, ], tier: "LC", }, sandshrewalola: { eventPokemon: [ {"generation": 7, "level": 10, "isHidden": false, "moves":["rapidspin", "iceball", "powdersnow", "bide"], "pokeball": "cherishball"}, ], tier: "LC", }, sandslash: { randomBattleMoves: ["earthquake", "swordsdance", "rapidspin", "toxic", "stealthrock", "knockoff"], randomDoubleBattleMoves: ["earthquake", "rockslide", "stoneedge", "swordsdance", "xscissor", "knockoff", "protect"], tier: "PU", }, sandslashalola: { randomBattleMoves: ["substitute", "swordsdance", "iciclecrash", "ironhead", "earthquake", "rapidspin"], randomDoubleBattleMoves: ["protect", "swordsdance", "iciclecrash", "ironhead", "earthquake", "rockslide"], tier: "NU", }, nidoranf: { randomBattleMoves: ["toxicspikes", "crunch", "poisonjab", "honeclaws"], randomDoubleBattleMoves: ["helpinghand", "crunch", "poisonjab", "protect"], tier: "LC", }, nidorina: { randomBattleMoves: ["toxicspikes", "crunch", "poisonjab", "honeclaws", "icebeam", "thunderbolt", "shadowclaw"], randomDoubleBattleMoves: ["helpinghand", "crunch", "poisonjab", "protect", "icebeam", "thunderbolt", "shadowclaw"], tier: "NFE", }, nidoqueen: { randomBattleMoves: ["toxicspikes", "stealthrock", "fireblast", "icebeam", "earthpower", "sludgewave"], randomDoubleBattleMoves: ["protect", "fireblast", "icebeam", "earthpower", "sludgebomb", "thunderbolt"], eventPokemon: [ {"generation": 6, "level": 41, "perfectIVs": 2, "isHidden": false, "abilities":["poisonpoint"], "moves":["tailwhip", "doublekick", "poisonsting", "bodyslam"], "pokeball": "cherishball"}, ], tier: "RU", }, nidoranm: { randomBattleMoves: ["suckerpunch", "poisonjab", "headsmash", "honeclaws", "shadowclaw"], randomDoubleBattleMoves: ["suckerpunch", "poisonjab", "shadowclaw", "helpinghand", "protect"], tier: "LC", }, nidorino: { randomBattleMoves: ["suckerpunch", "poisonjab", "headsmash", "honeclaws", "shadowclaw"], randomDoubleBattleMoves: ["suckerpunch", "poisonjab", "shadowclaw", "helpinghand", "protect"], tier: "NFE", }, nidoking: { randomBattleMoves: ["substitute", "fireblast", "icebeam", "earthpower", "sludgewave", "superpower"], randomDoubleBattleMoves: ["protect", "fireblast", "thunderbolt", "icebeam", "earthpower", "sludgebomb", "focusblast"], tier: "UU", }, cleffa: { randomBattleMoves: ["reflect", "thunderwave", "lightscreen", "toxic", "fireblast", "encore", "wish", "protect", "aromatherapy"], randomDoubleBattleMoves: ["reflect", "thunderwave", "lightscreen", "safeguard", "fireblast", "protect"], tier: "LC", }, clefairy: { randomBattleMoves: ["healingwish", "reflect", "thunderwave", "lightscreen", "toxic", "fireblast", "encore", "wish", "protect", "aromatherapy", "stealthrock", "moonblast", "knockoff", "moonlight"], randomDoubleBattleMoves: ["reflect", "thunderwave", "lightscreen", "safeguard", "fireblast", "followme", "protect", "moonblast"], tier: "NFE", }, clefable: { randomBattleMoves: ["calmmind", "softboiled", "fireblast", "moonblast", "stealthrock", "thunderwave"], randomDoubleBattleMoves: ["reflect", "thunderwave", "lightscreen", "safeguard", "fireblast", "followme", "protect", "moonblast", "dazzlinggleam", "softboiled"], tier: "OU", }, vulpix: { randomBattleMoves: ["flamethrower", "fireblast", "willowisp", "energyball", "substitute", "toxic", "hypnosis", "painsplit"], randomDoubleBattleMoves: ["heatwave", "fireblast", "willowisp", "energyball", "substitute", "protect"], eventPokemon: [ {"generation": 3, "level": 18, "gender": "F", "nature": "Quirky", "ivs": {"hp": 15, "atk": 6, "def": 3, "spa": 25, "spd": 13, "spe": 22}, "moves":["tailwhip", "roar", "quickattack", "willowisp"]}, {"generation": 3, "level": 18, "moves":["charm", "heatwave", "ember", "dig"]}, ], tier: "LC Uber", }, vulpixalola: { eventPokemon: [ {"generation": 7, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "babydolleyes", "iceshard"], "pokeball": "cherishball"}, {"generation": 7, "level": 10, "gender": "F", "nature": "Modest", "isHidden": false, "moves":["powdersnow"], "pokeball": "cherishball"}, ], tier: "LC", }, ninetales: { randomBattleMoves: ["fireblast", "willowisp", "solarbeam", "nastyplot", "substitute", "hiddenpowerice"], randomDoubleBattleMoves: ["heatwave", "fireblast", "willowisp", "solarbeam", "substitute", "protect"], eventPokemon: [ {"generation": 5, "level": 50, "gender": "M", "nature": "Bold", "ivs": {"def": 31}, "isHidden": true, "moves":["heatwave", "solarbeam", "psyshock", "willowisp"], "pokeball": "cherishball"}, ], tier: "PU", }, ninetalesalola: { randomBattleMoves: ["nastyplot", "blizzard", "moonblast", "substitute", "hiddenpowerfire", "freezedry", "auroraveil"], randomDoubleBattleMoves: ["blizzard", "moonblast", "protect", "hiddenpowerfire", "freezedry", "auroraveil", "encore"], tier: "OU", }, igglybuff: { randomBattleMoves: ["wish", "thunderwave", "reflect", "lightscreen", "healbell", "seismictoss", "counter", "protect"], randomDoubleBattleMoves: ["wish", "thunderwave", "reflect", "lightscreen", "seismictoss", "protect"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "abilities":["cutecharm"], "moves":["sing", "charm", "defensecurl", "tickle"]}, ], tier: "LC", }, jigglypuff: { randomBattleMoves: ["wish", "thunderwave", "reflect", "lightscreen", "healbell", "seismictoss", "counter", "stealthrock", "protect", "knockoff", "dazzlinggleam"], randomDoubleBattleMoves: ["wish", "thunderwave", "reflect", "lightscreen", "seismictoss", "protect", "knockoff", "dazzlinggleam"], tier: "NFE", }, wigglytuff: { randomBattleMoves: ["wish", "protect", "fireblast", "stealthrock", "dazzlinggleam", "hypervoice"], randomDoubleBattleMoves: ["thunderwave", "reflect", "lightscreen", "protect", "dazzlinggleam", "fireblast", "icebeam", "hypervoice"], tier: "PU", }, zubat: { randomBattleMoves: ["bravebird", "roost", "toxic", "taunt", "nastyplot", "gigadrain", "sludgebomb", "airslash", "uturn", "whirlwind", "heatwave", "superfang"], randomDoubleBattleMoves: ["bravebird", "taunt", "nastyplot", "gigadrain", "sludgebomb", "airslash", "uturn", "protect", "heatwave", "superfang"], tier: "LC", }, golbat: { randomBattleMoves: ["bravebird", "roost", "toxic", "taunt", "defog", "superfang", "uturn"], randomDoubleBattleMoves: ["bravebird", "taunt", "nastyplot", "gigadrain", "sludgebomb", "airslash", "uturn", "protect", "heatwave", "superfang"], tier: "NU", }, crobat: { randomBattleMoves: ["bravebird", "roost", "toxic", "taunt", "defog", "uturn", "superfang"], randomDoubleBattleMoves: ["bravebird", "taunt", "tailwind", "crosspoison", "uturn", "protect", "superfang"], eventPokemon: [ {"generation": 4, "level": 30, "gender": "M", "nature": "Timid", "moves":["heatwave", "airslash", "sludgebomb", "superfang"], "pokeball": "cherishball"}, ], tier: "UU", }, oddish: { randomBattleMoves: ["gigadrain", "sludgebomb", "synthesis", "sleeppowder", "stunspore", "toxic", "hiddenpowerfire", "leechseed", "dazzlinggleam", "sunnyday"], randomDoubleBattleMoves: ["gigadrain", "sludgebomb", "sleeppowder", "stunspore", "protect", "hiddenpowerfire", "leechseed", "dazzlinggleam", "sunnyday"], eventPokemon: [ {"generation": 3, "level": 26, "gender": "M", "nature": "Quirky", "ivs": {"hp": 23, "atk": 24, "def": 20, "spa": 21, "spd": 9, "spe": 16}, "moves":["poisonpowder", "stunspore", "sleeppowder", "acid"]}, {"generation": 3, "level": 5, "shiny": 1, "moves":["absorb", "leechseed"]}, ], tier: "LC", }, gloom: { randomBattleMoves: ["gigadrain", "sludgebomb", "synthesis", "sleeppowder", "stunspore", "toxic", "hiddenpowerfire", "leechseed", "dazzlinggleam", "sunnyday"], randomDoubleBattleMoves: ["gigadrain", "sludgebomb", "sleeppowder", "stunspore", "protect", "hiddenpowerfire", "leechseed", "dazzlinggleam", "sunnyday"], eventPokemon: [ {"generation": 3, "level": 50, "moves":["sleeppowder", "acid", "moonlight", "petaldance"]}, ], tier: "NFE", }, vileplume: { randomBattleMoves: ["gigadrain", "sludgebomb", "synthesis", "sleeppowder", "hiddenpowerfire", "aromatherapy"], randomDoubleBattleMoves: ["gigadrain", "sludgebomb", "sleeppowder", "stunspore", "protect", "hiddenpowerfire", "moonblast"], tier: "NU", }, bellossom: { randomBattleMoves: ["gigadrain", "sleeppowder", "hiddenpowerfire", "hiddenpowerrock", "quiverdance", "moonblast"], randomDoubleBattleMoves: ["gigadrain", "sludgebomb", "sleeppowder", "stunspore", "protect", "hiddenpowerfire", "moonblast", "sunnyday", "solarbeam"], tier: "PU", }, paras: { randomBattleMoves: ["spore", "stunspore", "xscissor", "seedbomb", "synthesis", "leechseed", "aromatherapy", "knockoff"], randomDoubleBattleMoves: ["spore", "stunspore", "xscissor", "seedbomb", "ragepowder", "leechseed", "protect", "knockoff", "wideguard"], eventPokemon: [ {"generation": 3, "level": 28, "abilities":["effectspore"], "moves":["refresh", "spore", "slash", "falseswipe"]}, ], tier: "LC", }, parasect: { randomBattleMoves: ["spore", "substitute", "leechlife", "seedbomb", "leechseed", "knockoff"], randomDoubleBattleMoves: ["spore", "stunspore", "leechlife", "seedbomb", "ragepowder", "leechseed", "protect", "knockoff", "wideguard"], tier: "PU", }, venonat: { randomBattleMoves: ["sleeppowder", "morningsun", "toxicspikes", "sludgebomb", "signalbeam", "stunspore", "psychic"], randomDoubleBattleMoves: ["sleeppowder", "morningsun", "ragepowder", "sludgebomb", "signalbeam", "stunspore", "psychic", "protect"], tier: "LC", }, venomoth: { randomBattleMoves: ["sleeppowder", "quiverdance", "batonpass", "bugbuzz", "sludgebomb", "substitute"], randomDoubleBattleMoves: ["sleeppowder", "roost", "ragepowder", "quiverdance", "protect", "bugbuzz", "sludgebomb", "gigadrain", "substitute", "psychic"], eventPokemon: [ {"generation": 3, "level": 32, "abilities":["shielddust"], "moves":["refresh", "silverwind", "substitute", "psychic"]}, ], tier: "BL2", }, diglett: { randomBattleMoves: ["earthquake", "rockslide", "stealthrock", "suckerpunch", "reversal", "substitute", "shadowclaw"], randomDoubleBattleMoves: ["earthquake", "rockslide", "protect", "suckerpunch", "shadowclaw"], tier: "LC", }, diglettalola: { eventPokemon: [ {"generation": 7, "level": 10, "isHidden": false, "abilities":["tanglinghair"], "moves":["mudslap", "astonish", "growl", "metalclaw"], "pokeball": "cherishball"}, ], tier: "LC", }, dugtrio: { randomBattleMoves: ["earthquake", "stoneedge", "stealthrock", "suckerpunch", "reversal", "substitute"], randomDoubleBattleMoves: ["earthquake", "rockslide", "protect", "suckerpunch", "stoneedge"], eventPokemon: [ {"generation": 3, "level": 40, "moves":["charm", "earthquake", "sandstorm", "triattack"]}, ], tier: "OU", }, dugtrioalola: { randomBattleMoves: ["earthquake", "ironhead", "substitute", "reversal", "stoneedge", "suckerpunch"], randomDoubleBattleMoves: ["earthquake", "ironhead", "protect", "rockslide", "stoneedge", "suckerpunch"], tier: "PU", }, meowth: { randomBattleMoves: ["fakeout", "uturn", "thief", "taunt", "return", "hypnosis"], randomDoubleBattleMoves: ["fakeout", "uturn", "nightslash", "taunt", "return", "hypnosis", "feint", "protect"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["scratch", "growl", "petaldance"]}, {"generation": 3, "level": 5, "moves":["scratch", "growl"]}, {"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "growl", "bite"]}, {"generation": 3, "level": 22, "moves":["sing", "slash", "payday", "bite"]}, {"generation": 4, "level": 21, "gender": "F", "nature": "Jolly", "abilities":["pickup"], "moves":["bite", "fakeout", "furyswipes", "screech"], "pokeball": "cherishball"}, {"generation": 4, "level": 10, "gender": "M", "nature": "Jolly", "abilities":["pickup"], "moves":["fakeout", "payday", "assist", "scratch"], "pokeball": "cherishball"}, {"generation": 5, "level": 15, "gender": "M", "isHidden": false, "abilities":["pickup"], "moves":["furyswipes", "sing", "nastyplot", "snatch"], "pokeball": "cherishball"}, {"generation": 6, "level": 20, "isHidden": false, "abilities":["pickup"], "moves":["happyhour", "screech", "bite", "fakeout"], "pokeball": "cherishball"}, ], tier: "LC", }, meowthalola: { tier: "LC", }, persian: { randomBattleMoves: ["fakeout", "uturn", "taunt", "return", "knockoff"], randomDoubleBattleMoves: ["fakeout", "uturn", "knockoff", "taunt", "return", "hypnosis", "feint", "protect"], tier: "PU", }, persianalola: { randomBattleMoves: ["nastyplot", "darkpulse", "powergem", "hypnosis", "hiddenpowerfighting"], randomDoubleBattleMoves: ["fakeout", "foulplay", "darkpulse", "powergem", "snarl", "hiddenpowerfighting", "partingshot", "protect"], tier: "PU", }, psyduck: { randomBattleMoves: ["hydropump", "scald", "icebeam", "hiddenpowergrass", "crosschop", "encore", "psychic", "signalbeam"], randomDoubleBattleMoves: ["hydropump", "scald", "icebeam", "hiddenpowergrass", "crosschop", "encore", "psychic", "signalbeam", "surf", "icywind", "protect"], eventPokemon: [ {"generation": 3, "level": 27, "gender": "M", "nature": "Lax", "ivs": {"hp": 31, "atk": 16, "def": 12, "spa": 29, "spd": 31, "spe": 14}, "abilities":["damp"], "moves":["tailwhip", "confusion", "disable", "screech"]}, {"generation": 3, "level": 5, "shiny": 1, "moves":["watersport", "scratch", "tailwhip", "mudsport"]}, ], tier: "LC", }, golduck: { randomBattleMoves: ["hydropump", "scald", "icebeam", "psyshock", "encore", "calmmind", "substitute"], randomDoubleBattleMoves: ["hydropump", "scald", "icebeam", "hiddenpowergrass", "focusblast", "encore", "psychic", "icywind", "protect"], eventPokemon: [ {"generation": 3, "level": 33, "moves":["charm", "waterfall", "psychup", "brickbreak"]}, ], tier: "PU", }, mankey: { randomBattleMoves: ["closecombat", "uturn", "icepunch", "rockslide", "punishment", "earthquake", "poisonjab"], randomDoubleBattleMoves: ["closecombat", "uturn", "icepunch", "rockslide", "punishment", "earthquake", "poisonjab", "protect"], tier: "LC", }, primeape: { randomBattleMoves: ["closecombat", "uturn", "icepunch", "stoneedge", "encore", "earthquake", "gunkshot"], randomDoubleBattleMoves: ["closecombat", "uturn", "icepunch", "rockslide", "punishment", "earthquake", "poisonjab", "protect", "taunt", "stoneedge"], eventPokemon: [ {"generation": 3, "level": 34, "abilities":["vitalspirit"], "moves":["helpinghand", "crosschop", "focusenergy", "reversal"]}, ], tier: "PU", }, growlithe: { randomBattleMoves: ["flareblitz", "wildcharge", "hiddenpowergrass", "closecombat", "morningsun", "willowisp", "toxic", "flamethrower"], randomDoubleBattleMoves: ["flareblitz", "wildcharge", "hiddenpowergrass", "closecombat", "willowisp", "snarl", "heatwave", "helpinghand", "protect"], eventPokemon: [ {"generation": 3, "level": 32, "gender": "F", "nature": "Quiet", "ivs": {"hp": 11, "atk": 24, "def": 28, "spa": 1, "spd": 20, "spe": 2}, "abilities":["intimidate"], "moves":["leer", "odorsleuth", "takedown", "flamewheel"]}, {"generation": 3, "level": 10, "gender": "M", "moves":["bite", "roar", "ember"]}, {"generation": 3, "level": 28, "moves":["charm", "flamethrower", "bite", "takedown"]}, ], tier: "LC", }, arcanine: { randomBattleMoves: ["flareblitz", "wildcharge", "extremespeed", "closecombat", "morningsun", "willowisp", "toxic", "crunch", "roar"], randomDoubleBattleMoves: ["flareblitz", "wildcharge", "closecombat", "willowisp", "snarl", "protect", "extremespeed"], eventPokemon: [ {"generation": 4, "level": 50, "abilities":["intimidate"], "moves":["flareblitz", "thunderfang", "crunch", "extremespeed"], "pokeball": "cherishball"}, {"generation": 7, "level": 50, "isHidden": false, "abilities":["intimidate"], "moves":["flareblitz", "extremespeed", "willowisp", "protect"], "pokeball": "cherishball"}, ], tier: "UU", }, poliwag: { randomBattleMoves: ["hydropump", "icebeam", "encore", "bellydrum", "hypnosis", "waterfall", "return"], randomDoubleBattleMoves: ["hydropump", "icebeam", "encore", "icywind", "hypnosis", "waterfall", "return", "protect", "helpinghand"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["bubble", "sweetkiss"]}, ], tier: "LC", }, poliwhirl: { randomBattleMoves: ["hydropump", "icebeam", "encore", "bellydrum", "hypnosis", "waterfall", "return", "earthquake"], randomDoubleBattleMoves: ["hydropump", "icebeam", "encore", "icywind", "hypnosis", "waterfall", "return", "protect", "helpinghand", "earthquake"], tier: "NFE", }, poliwrath: { randomBattleMoves: ["hydropump", "focusblast", "icebeam", "rest", "sleeptalk", "scald", "circlethrow", "raindance"], randomDoubleBattleMoves: ["bellydrum", "encore", "waterfall", "protect", "icepunch", "earthquake", "brickbreak", "rockslide"], eventPokemon: [ {"generation": 3, "level": 42, "moves":["helpinghand", "hydropump", "raindance", "brickbreak"]}, ], tier: "PU", }, politoed: { randomBattleMoves: ["scald", "toxic", "encore", "perishsong", "protect", "hypnosis", "rest"], randomDoubleBattleMoves: ["scald", "hypnosis", "icywind", "encore", "helpinghand", "protect", "icebeam", "focusblast", "hydropump", "hiddenpowergrass"], eventPokemon: [ {"generation": 5, "level": 50, "gender": "M", "nature": "Calm", "ivs": {"hp": 31, "atk": 13, "def": 31, "spa": 5, "spd": 31, "spe": 5}, "isHidden": true, "moves":["scald", "icebeam", "perishsong", "protect"], "pokeball": "cherishball"}, ], tier: "PU", }, abra: { randomBattleMoves: ["calmmind", "psychic", "psyshock", "hiddenpowerfighting", "shadowball", "encore", "substitute"], randomDoubleBattleMoves: ["protect", "psychic", "psyshock", "hiddenpowerfighting", "shadowball", "encore", "substitute"], tier: "LC", }, kadabra: { randomBattleMoves: ["calmmind", "psychic", "psyshock", "hiddenpowerfighting", "shadowball", "encore", "substitute"], randomDoubleBattleMoves: ["protect", "psychic", "psyshock", "hiddenpowerfighting", "shadowball", "encore", "substitute"], tier: "NFE", }, alakazam: { randomBattleMoves: ["psyshock", "psychic", "focusblast", "shadowball", "hiddenpowerice", "hiddenpowerfire"], randomDoubleBattleMoves: ["protect", "psychic", "psyshock", "focusblast", "shadowball", "encore", "substitute", "dazzlinggleam"], eventPokemon: [ {"generation": 3, "level": 70, "moves":["futuresight", "calmmind", "psychic", "trick"]}, ], tier: "BL", }, alakazammega: { randomBattleMoves: ["calmmind", "psyshock", "focusblast", "shadowball", "encore", "substitute"], randomDoubleBattleMoves: ["protect", "psychic", "psyshock", "focusblast", "shadowball", "encore", "substitute", "dazzlinggleam"], requiredItem: "Alakazite", tier: "OU", }, machop: { randomBattleMoves: ["dynamicpunch", "bulkup", "icepunch", "rockslide", "bulletpunch", "knockoff"], randomDoubleBattleMoves: ["dynamicpunch", "protect", "icepunch", "rockslide", "bulletpunch", "knockoff"], tier: "LC", }, machoke: { randomBattleMoves: ["dynamicpunch", "bulkup", "icepunch", "rockslide", "bulletpunch", "poweruppunch", "knockoff"], randomDoubleBattleMoves: ["dynamicpunch", "protect", "icepunch", "rockslide", "bulletpunch", "knockoff"], eventPokemon: [ {"generation": 5, "level": 30, "isHidden": false, "moves":["lowsweep", "foresight", "seismictoss", "revenge"], "pokeball": "cherishball"}, ], tier: "NFE", }, machamp: { randomBattleMoves: ["dynamicpunch", "icepunch", "stoneedge", "bulletpunch", "knockoff", "substitute"], randomDoubleBattleMoves: ["dynamicpunch", "protect", "icepunch", "stoneedge", "rockslide", "bulletpunch", "knockoff", "wideguard"], eventPokemon: [ {"generation": 3, "level": 38, "gender": "M", "nature": "Quiet", "ivs": {"hp": 9, "atk": 23, "def": 25, "spa": 20, "spd": 15, "spe": 10}, "abilities":["guts"], "moves":["seismictoss", "foresight", "revenge", "vitalthrow"]}, {"generation": 6, "level": 50, "shiny": true, "gender": "M", "nature": "Adamant", "ivs": {"hp": 31, "atk": 31, "def": 31, "spa": 31, "spd": 31, "spe": 31}, "isHidden": false, "abilities":["noguard"], "moves":["dynamicpunch", "stoneedge", "wideguard", "knockoff"], "pokeball": "cherishball"}, {"generation": 7, "level": 34, "gender": "F", "nature": "Brave", "ivs": {"atk": 31}, "isHidden": false, "abilities":["guts"], "moves":["strength", "bulkup", "quickguard", "doubleedge"], "pokeball": "cherishball"}, ], tier: "RU", }, bellsprout: { randomBattleMoves: ["swordsdance", "sleeppowder", "sunnyday", "growth", "solarbeam", "gigadrain", "sludgebomb", "weatherball", "suckerpunch", "seedbomb"], randomDoubleBattleMoves: ["swordsdance", "sleeppowder", "sunnyday", "growth", "solarbeam", "gigadrain", "sludgebomb", "weatherball", "suckerpunch", "seedbomb", "protect"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["vinewhip", "teeterdance"]}, {"generation": 3, "level": 10, "gender": "M", "moves":["vinewhip", "growth"]}, ], tier: "LC", }, weepinbell: { randomBattleMoves: ["swordsdance", "sleeppowder", "sunnyday", "growth", "solarbeam", "gigadrain", "sludgebomb", "weatherball", "suckerpunch", "seedbomb", "knockoff"], randomDoubleBattleMoves: ["swordsdance", "sleeppowder", "sunnyday", "growth", "solarbeam", "gigadrain", "sludgebomb", "weatherball", "suckerpunch", "seedbomb", "protect", "knockoff"], eventPokemon: [ {"generation": 3, "level": 32, "moves":["morningsun", "magicalleaf", "sludgebomb", "sweetscent"]}, ], tier: "NFE", }, victreebel: { randomBattleMoves: ["sleeppowder", "sunnyday", "growth", "solarbeam", "gigadrain", "sludgebomb", "weatherball", "suckerpunch", "powerwhip", "knockoff", "swordsdance"], randomDoubleBattleMoves: ["swordsdance", "sleeppowder", "sunnyday", "growth", "solarbeam", "gigadrain", "sludgebomb", "weatherball", "suckerpunch", "powerwhip", "protect", "knockoff"], tier: "PU", }, tentacool: { randomBattleMoves: ["toxicspikes", "rapidspin", "scald", "sludgebomb", "icebeam", "knockoff", "gigadrain", "toxic", "dazzlinggleam"], randomDoubleBattleMoves: ["muddywater", "scald", "sludgebomb", "icebeam", "knockoff", "gigadrain", "protect", "dazzlinggleam"], tier: "LC", }, tentacruel: { randomBattleMoves: ["toxicspikes", "rapidspin", "scald", "sludgebomb", "acidspray", "knockoff"], randomDoubleBattleMoves: ["muddywater", "scald", "sludgebomb", "acidspray", "icebeam", "knockoff", "gigadrain", "protect", "dazzlinggleam"], tier: "UU", }, geodude: { randomBattleMoves: ["stealthrock", "earthquake", "stoneedge", "suckerpunch", "hammerarm", "firepunch", "rockblast"], randomDoubleBattleMoves: ["rockslide", "earthquake", "stoneedge", "suckerpunch", "hammerarm", "firepunch", "protect"], tier: "LC", }, geodudealola: { tier: "LC", }, graveler: { randomBattleMoves: ["stealthrock", "earthquake", "stoneedge", "suckerpunch", "hammerarm", "firepunch", "rockblast"], randomDoubleBattleMoves: ["rockslide", "earthquake", "stoneedge", "suckerpunch", "hammerarm", "firepunch", "protect"], tier: "NFE", }, graveleralola: { tier: "NFE", }, golem: { randomBattleMoves: ["stealthrock", "earthquake", "explosion", "suckerpunch", "toxic", "rockblast"], randomDoubleBattleMoves: ["rockslide", "earthquake", "stoneedge", "suckerpunch", "hammerarm", "firepunch", "protect"], tier: "PU", }, golemalola: { randomBattleMoves: ["stealthrock", "stoneedge", "return", "thunderpunch", "earthquake", "toxic"], randomDoubleBattleMoves: ["doubleedge", "stoneedge", "rockslide", "earthquake", "protect"], tier: "PU", }, ponyta: { randomBattleMoves: ["flareblitz", "wildcharge", "morningsun", "hypnosis", "flamecharge"], randomDoubleBattleMoves: ["flareblitz", "wildcharge", "protect", "hypnosis", "flamecharge"], tier: "LC", }, rapidash: { randomBattleMoves: ["flareblitz", "wildcharge", "morningsun", "drillrun", "willowisp"], randomDoubleBattleMoves: ["flareblitz", "wildcharge", "protect", "hypnosis", "flamecharge", "megahorn", "drillrun", "willowisp"], eventPokemon: [ {"generation": 3, "level": 40, "moves":["batonpass", "solarbeam", "sunnyday", "flamethrower"]}, ], tier: "PU", }, slowpoke: { randomBattleMoves: ["scald", "aquatail", "zenheadbutt", "thunderwave", "toxic", "slackoff", "trickroom"], randomDoubleBattleMoves: ["scald", "aquatail", "zenheadbutt", "thunderwave", "slackoff", "trickroom", "protect"], eventPokemon: [ {"generation": 3, "level": 31, "gender": "F", "nature": "Naive", "ivs": {"hp": 17, "atk": 11, "def": 19, "spa": 20, "spd": 5, "spe": 10}, "abilities":["oblivious"], "moves":["watergun", "confusion", "disable", "headbutt"]}, {"generation": 3, "level": 10, "gender": "M", "moves":["curse", "yawn", "tackle", "growl"]}, {"generation": 5, "level": 30, "isHidden": false, "moves":["confusion", "disable", "headbutt", "waterpulse"], "pokeball": "cherishball"}, ], tier: "LC", }, slowbro: { randomBattleMoves: ["scald", "toxic", "thunderwave", "psyshock", "fireblast", "icebeam", "slackoff"], randomDoubleBattleMoves: ["scald", "fireblast", "icebeam", "psychic", "grassknot", "thunderwave", "slackoff", "trickroom", "protect", "psyshock"], eventPokemon: [ {"generation": 6, "level": 100, "nature": "Quiet", "isHidden": false, "abilities":["oblivious"], "moves":["scald", "trickroom", "slackoff", "irontail"], "pokeball": "cherishball"}, ], tier: "NU", }, slowbromega: { randomBattleMoves: ["calmmind", "scald", "psyshock", "slackoff", "fireblast", "psychic", "icebeam"], randomDoubleBattleMoves: ["scald", "fireblast", "icebeam", "psychic", "thunderwave", "slackoff", "trickroom", "protect", "psyshock"], requiredItem: "Slowbronite", tier: "BL", }, slowking: { randomBattleMoves: ["scald", "fireblast", "icebeam", "psychic", "grassknot", "thunderwave", "toxic", "slackoff", "trickroom", "nastyplot", "dragontail", "psyshock"], randomDoubleBattleMoves: ["scald", "fireblast", "icebeam", "psychic", "grassknot", "thunderwave", "slackoff", "trickroom", "protect", "psyshock"], tier: "NU", }, magnemite: { randomBattleMoves: ["thunderbolt", "thunderwave", "magnetrise", "substitute", "flashcannon", "hiddenpowerice", "voltswitch"], randomDoubleBattleMoves: ["thunderbolt", "thunderwave", "magnetrise", "substitute", "flashcannon", "hiddenpowerice", "voltswitch", "protect", "electroweb", "discharge"], tier: "LC", }, magneton: { randomBattleMoves: ["thunderbolt", "substitute", "flashcannon", "hiddenpowerice", "voltswitch", "chargebeam", "hiddenpowerfire"], randomDoubleBattleMoves: ["thunderbolt", "thunderwave", "magnetrise", "substitute", "flashcannon", "hiddenpowerice", "voltswitch", "protect", "electroweb", "discharge", "hiddenpowerfire"], eventPokemon: [ {"generation": 3, "level": 30, "moves":["refresh", "doubleedge", "raindance", "thunder"]}, ], tier: "UU", }, magnezone: { randomBattleMoves: ["thunderbolt", "substitute", "flashcannon", "hiddenpowerice", "voltswitch", "hiddenpowerfire"], randomDoubleBattleMoves: ["thunderbolt", "substitute", "flashcannon", "hiddenpowerice", "voltswitch", "protect", "electroweb", "discharge", "hiddenpowerfire"], tier: "OU", }, farfetchd: { randomBattleMoves: ["bravebird", "swordsdance", "return", "leafblade", "roost", "nightslash"], randomDoubleBattleMoves: ["bravebird", "swordsdance", "return", "leafblade", "protect", "nightslash"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["yawn", "wish"]}, {"generation": 3, "level": 36, "moves":["batonpass", "slash", "swordsdance", "aerialace"]}, ], tier: "PU", }, doduo: { randomBattleMoves: ["bravebird", "return", "doubleedge", "roost", "quickattack", "pursuit"], randomDoubleBattleMoves: ["bravebird", "return", "doubleedge", "quickattack", "protect"], tier: "LC", }, dodrio: { randomBattleMoves: ["bravebird", "return", "swordsdance", "roost", "quickattack", "knockoff", "jumpkick"], randomDoubleBattleMoves: ["bravebird", "return", "doubleedge", "quickattack", "knockoff", "protect"], eventPokemon: [ {"generation": 3, "level": 34, "moves":["batonpass", "drillpeck", "agility", "triattack"]}, ], tier: "NU", }, seel: { randomBattleMoves: ["surf", "icebeam", "aquajet", "protect", "rest", "toxic", "drillrun"], randomDoubleBattleMoves: ["surf", "icebeam", "aquajet", "protect", "rest", "toxic", "fakeout", "drillrun", "icywind"], eventPokemon: [ {"generation": 3, "level": 23, "abilities":["thickfat"], "moves":["helpinghand", "surf", "safeguard", "icebeam"]}, ], tier: "LC", }, dewgong: { randomBattleMoves: ["surf", "icebeam", "perishsong", "encore", "toxic", "protect"], randomDoubleBattleMoves: ["surf", "icebeam", "protect", "perishsong", "fakeout", "encore", "toxic"], tier: "PU", }, grimer: { randomBattleMoves: ["curse", "gunkshot", "poisonjab", "shadowsneak", "painsplit", "icepunch", "firepunch", "memento"], randomDoubleBattleMoves: ["gunkshot", "poisonjab", "shadowsneak", "protect", "icepunch", "firepunch"], eventPokemon: [ {"generation": 3, "level": 23, "moves":["helpinghand", "sludgebomb", "shadowpunch", "minimize"]}, ], tier: "LC", }, grimeralola: { eventPokemon: [ {"generation": 7, "level": 10, "isHidden": false, "abilities":["poisontouch"], "moves":["bite", "harden", "poisongas", "pound"], "pokeball": "cherishball"}, ], tier: "LC", }, muk: { randomBattleMoves: ["curse", "gunkshot", "poisonjab", "shadowsneak", "icepunch", "firepunch", "memento"], randomDoubleBattleMoves: ["gunkshot", "poisonjab", "shadowsneak", "protect", "icepunch", "firepunch", "brickbreak"], tier: "PU", }, mukalola: { randomBattleMoves: ["curse", "gunkshot", "knockoff", "poisonjab", "shadowsneak", "stoneedge", "pursuit"], randomDoubleBattleMoves: ["gunkshot", "knockoff", "stoneedge", "snarl", "protect", "poisonjab", "shadowsneak"], tier: "UU", }, shellder: { randomBattleMoves: ["shellsmash", "hydropump", "razorshell", "rockblast", "iciclespear", "rapidspin"], randomDoubleBattleMoves: ["shellsmash", "hydropump", "razorshell", "rockblast", "iciclespear", "protect"], eventPokemon: [ {"generation": 3, "level": 24, "gender": "F", "nature": "Brave", "ivs": {"hp": 5, "atk": 19, "def": 18, "spa": 5, "spd": 11, "spe": 13}, "abilities":["shellarmor"], "moves":["withdraw", "iciclespear", "supersonic", "aurorabeam"]}, {"generation": 3, "level": 10, "gender": "M", "abilities":["shellarmor"], "moves":["tackle", "withdraw", "iciclespear"]}, {"generation": 3, "level": 29, "abilities":["shellarmor"], "moves":["refresh", "takedown", "surf", "aurorabeam"]}, ], tier: "LC", }, cloyster: { randomBattleMoves: ["shellsmash", "hydropump", "rockblast", "iciclespear", "iceshard", "rapidspin", "spikes", "toxicspikes"], randomDoubleBattleMoves: ["shellsmash", "hydropump", "razorshell", "rockblast", "iciclespear", "protect"], eventPokemon: [ {"generation": 5, "level": 30, "gender": "M", "nature": "Naughty", "isHidden": false, "abilities":["skilllink"], "moves":["iciclespear", "rockblast", "hiddenpower", "razorshell"]}, ], tier: "RU", }, gastly: { randomBattleMoves: ["shadowball", "sludgebomb", "hiddenpowerfighting", "thunderbolt", "substitute", "disable", "painsplit", "hypnosis", "gigadrain", "trick", "dazzlinggleam"], randomDoubleBattleMoves: ["shadowball", "sludgebomb", "hiddenpowerfighting", "thunderbolt", "substitute", "disable", "taunt", "hypnosis", "gigadrain", "trick", "dazzlinggleam", "protect"], tier: "LC", }, haunter: { randomBattleMoves: ["shadowball", "sludgebomb", "dazzlinggleam", "substitute", "destinybond"], randomDoubleBattleMoves: ["shadowball", "sludgebomb", "hiddenpowerfighting", "thunderbolt", "substitute", "disable", "taunt", "hypnosis", "gigadrain", "trick", "dazzlinggleam", "protect"], eventPokemon: [ {"generation": 5, "level": 30, "moves":["confuseray", "suckerpunch", "shadowpunch", "payback"], "pokeball": "cherishball"}, ], tier: "NFE", }, gengar: { randomBattleMoves: ["shadowball", "sludgewave", "focusblast", "substitute", "disable", "painsplit", "willowisp"], randomDoubleBattleMoves: ["shadowball", "sludgebomb", "focusblast", "substitute", "disable", "taunt", "hypnosis", "willowisp", "dazzlinggleam", "protect"], eventPokemon: [ {"generation": 3, "level": 23, "gender": "F", "nature": "Hardy", "ivs": {"hp": 19, "atk": 14, "def": 0, "spa": 14, "spd": 17, "spe": 27}, "moves":["spite", "curse", "nightshade", "confuseray"]}, {"generation": 6, "level": 25, "nature": "Timid", "moves":["psychic", "confuseray", "suckerpunch", "shadowpunch"], "pokeball": "cherishball"}, {"generation": 6, "level": 25, "moves":["nightshade", "confuseray", "suckerpunch", "shadowpunch"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "moves":["shadowball", "sludgebomb", "willowisp", "destinybond"], "pokeball": "cherishball"}, {"generation": 6, "level": 25, "shiny": true, "moves":["shadowball", "sludgewave", "confuseray", "astonish"], "pokeball": "duskball"}, {"generation": 6, "level": 50, "shiny": true, "gender": "M", "moves":["meanlook", "hypnosis", "psychic", "hyperbeam"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "moves":["meanlook", "hypnosis", "psychic", "hyperbeam"], "pokeball": "cherishball"}, ], tier: "OU", }, gengarmega: { randomBattleMoves: ["shadowball", "sludgewave", "focusblast", "taunt", "destinybond", "disable", "perishsong", "protect"], randomDoubleBattleMoves: ["shadowball", "sludgebomb", "focusblast", "substitute", "disable", "taunt", "hypnosis", "willowisp", "dazzlinggleam", "protect"], requiredItem: "Gengarite", tier: "Uber", }, onix: { randomBattleMoves: ["stealthrock", "earthquake", "stoneedge", "dragontail", "curse"], randomDoubleBattleMoves: ["stealthrock", "earthquake", "stoneedge", "rockslide", "protect", "explosion"], tier: "LC", }, steelix: { randomBattleMoves: ["stealthrock", "earthquake", "ironhead", "roar", "toxic", "rockslide"], randomDoubleBattleMoves: ["stealthrock", "earthquake", "ironhead", "rockslide", "protect", "explosion"], tier: "NU", }, steelixmega: { randomBattleMoves: ["stealthrock", "earthquake", "heavyslam", "roar", "toxic", "dragontail"], randomDoubleBattleMoves: ["stealthrock", "earthquake", "heavyslam", "rockslide", "protect", "explosion"], requiredItem: "Steelixite", tier: "UU", }, drowzee: { randomBattleMoves: ["psychic", "seismictoss", "thunderwave", "wish", "protect", "toxic", "shadowball", "trickroom", "calmmind", "dazzlinggleam"], randomDoubleBattleMoves: ["psychic", "seismictoss", "thunderwave", "wish", "protect", "hypnosis", "shadowball", "trickroom", "calmmind", "dazzlinggleam", "toxic"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "abilities":["insomnia"], "moves":["bellydrum", "wish"]}, ], tier: "LC", }, hypno: { randomBattleMoves: ["psychic", "seismictoss", "foulplay", "wish", "protect", "thunderwave", "toxic"], randomDoubleBattleMoves: ["psychic", "seismictoss", "thunderwave", "wish", "protect", "hypnosis", "trickroom", "dazzlinggleam", "foulplay"], eventPokemon: [ {"generation": 3, "level": 34, "abilities":["insomnia"], "moves":["batonpass", "psychic", "meditate", "shadowball"]}, ], tier: "PU", }, krabby: { randomBattleMoves: ["crabhammer", "swordsdance", "agility", "rockslide", "substitute", "xscissor", "superpower", "knockoff"], randomDoubleBattleMoves: ["crabhammer", "swordsdance", "rockslide", "substitute", "xscissor", "superpower", "knockoff", "protect"], tier: "LC", }, kingler: { randomBattleMoves: ["crabhammer", "xscissor", "rockslide", "swordsdance", "agility", "superpower", "knockoff"], randomDoubleBattleMoves: ["crabhammer", "xscissor", "rockslide", "substitute", "superpower", "knockoff", "protect", "wideguard"], tier: "PU", }, voltorb: { randomBattleMoves: ["voltswitch", "thunderbolt", "taunt", "foulplay", "hiddenpowerice"], randomDoubleBattleMoves: ["voltswitch", "thunderbolt", "taunt", "foulplay", "hiddenpowerice", "protect", "thunderwave"], eventPokemon: [ {"generation": 3, "level": 19, "moves":["refresh", "mirrorcoat", "spark", "swift"]}, ], tier: "LC", }, electrode: { randomBattleMoves: ["voltswitch", "thunderbolt", "taunt", "foulplay", "hiddenpowergrass", "signalbeam"], randomDoubleBattleMoves: ["voltswitch", "discharge", "taunt", "foulplay", "hiddenpowerice", "protect", "thunderwave"], tier: "PU", }, exeggcute: { randomBattleMoves: ["substitute", "leechseed", "gigadrain", "psychic", "sleeppowder", "stunspore", "hiddenpowerfire", "synthesis"], randomDoubleBattleMoves: ["substitute", "leechseed", "gigadrain", "psychic", "sleeppowder", "stunspore", "hiddenpowerfire", "protect", "trickroom"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["sweetscent", "wish"]}, ], tier: "LC", }, exeggutor: { randomBattleMoves: ["substitute", "leechseed", "gigadrain", "psychic", "sleeppowder", "hiddenpowerfire"], randomDoubleBattleMoves: ["substitute", "leechseed", "gigadrain", "psychic", "sleeppowder", "hiddenpowerfire", "protect", "trickroom", "psyshock"], eventPokemon: [ {"generation": 3, "level": 46, "moves":["refresh", "psychic", "hypnosis", "ancientpower"]}, ], tier: "PU", }, exeggutoralola: { randomBattleMoves: ["dracometeor", "leafstorm", "flamethrower", "earthquake", "woodhammer", "gigadrain", "dragonhammer"], randomDoubleBattleMoves: ["dracometeor", "leafstorm", "protect", "flamethrower", "trickroom", "woodhammer", "dragonhammer"], eventPokemon: [ {"generation": 7, "level": 50, "gender": "M", "nature": "Modest", "isHidden": true, "moves":["powerswap", "celebrate", "leafstorm", "dracometeor"], "pokeball": "cherishball"}, ], tier: "PU", }, cubone: { randomBattleMoves: ["substitute", "bonemerang", "doubleedge", "rockslide", "firepunch", "earthquake"], randomDoubleBattleMoves: ["substitute", "bonemerang", "doubleedge", "rockslide", "firepunch", "earthquake", "protect"], tier: "LC", },<|fim▁hole|> marowak: { randomBattleMoves: ["bonemerang", "earthquake", "knockoff", "doubleedge", "stoneedge", "stealthrock", "substitute"], randomDoubleBattleMoves: ["substitute", "bonemerang", "doubleedge", "rockslide", "firepunch", "earthquake", "protect", "swordsdance"], eventPokemon: [ {"generation": 3, "level": 44, "moves":["sing", "earthquake", "swordsdance", "rockslide"]}, ], tier: "PU", }, marowakalola: { randomBattleMoves: ["flamecharge", "shadowbone", "bonemerang", "willowisp", "stoneedge", "flareblitz", "substitute"], randomDoubleBattleMoves: ["shadowbone", "bonemerang", "willowisp", "stoneedge", "flareblitz", "protect"], tier: "OU", }, tyrogue: { randomBattleMoves: ["highjumpkick", "rapidspin", "fakeout", "bulletpunch", "machpunch", "toxic", "counter"], randomDoubleBattleMoves: ["highjumpkick", "fakeout", "bulletpunch", "machpunch", "helpinghand", "protect"], tier: "LC", }, hitmonlee: { randomBattleMoves: ["highjumpkick", "knockoff", "stoneedge", "rapidspin", "machpunch", "poisonjab", "fakeout"], randomDoubleBattleMoves: ["knockoff", "rockslide", "machpunch", "fakeout", "highjumpkick", "earthquake", "blazekick", "wideguard", "protect"], eventPokemon: [ {"generation": 3, "level": 38, "abilities":["limber"], "moves":["refresh", "highjumpkick", "mindreader", "megakick"]}, ], tier: "NU", }, hitmonchan: { randomBattleMoves: ["bulkup", "drainpunch", "icepunch", "firepunch", "machpunch", "rapidspin"], randomDoubleBattleMoves: ["fakeout", "drainpunch", "icepunch", "firepunch", "machpunch", "earthquake", "rockslide", "protect", "thunderpunch"], eventPokemon: [ {"generation": 3, "level": 38, "abilities":["keeneye"], "moves":["helpinghand", "skyuppercut", "mindreader", "megapunch"]}, ], tier: "PU", }, hitmontop: { randomBattleMoves: ["suckerpunch", "machpunch", "rapidspin", "closecombat", "toxic"], randomDoubleBattleMoves: ["fakeout", "feint", "suckerpunch", "closecombat", "helpinghand", "machpunch", "wideguard"], eventPokemon: [ {"generation": 5, "level": 55, "gender": "M", "nature": "Adamant", "isHidden": false, "abilities":["intimidate"], "moves":["fakeout", "closecombat", "suckerpunch", "helpinghand"]}, ], tier: "NU", }, lickitung: { randomBattleMoves: ["wish", "protect", "dragontail", "curse", "bodyslam", "return", "powerwhip", "swordsdance", "earthquake", "toxic", "healbell"], randomDoubleBattleMoves: ["wish", "protect", "dragontail", "knockoff", "bodyslam", "return", "powerwhip", "swordsdance", "earthquake"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["healbell", "wish"]}, {"generation": 3, "level": 38, "moves":["helpinghand", "doubleedge", "defensecurl", "rollout"]}, ], tier: "LC", }, lickilicky: { randomBattleMoves: ["wish", "protect", "bodyslam", "knockoff", "dragontail", "healbell", "swordsdance", "explosion", "earthquake", "powerwhip"], randomDoubleBattleMoves: ["wish", "protect", "dragontail", "knockoff", "bodyslam", "rockslide", "powerwhip", "earthquake", "explosion"], tier: "PU", }, koffing: { randomBattleMoves: ["painsplit", "sludgebomb", "willowisp", "fireblast", "toxic", "clearsmog", "rest", "sleeptalk", "thunderbolt"], randomDoubleBattleMoves: ["protect", "sludgebomb", "willowisp", "fireblast", "toxic", "rest", "sleeptalk", "thunderbolt"], tier: "LC", }, weezing: { randomBattleMoves: ["painsplit", "sludgebomb", "willowisp", "fireblast", "protect", "toxicspikes"], randomDoubleBattleMoves: ["protect", "sludgebomb", "willowisp", "fireblast", "toxic", "painsplit", "thunderbolt", "explosion"], tier: "PU", }, rhyhorn: { randomBattleMoves: ["stoneedge", "earthquake", "aquatail", "megahorn", "stealthrock", "rockblast", "rockpolish"], randomDoubleBattleMoves: ["stoneedge", "earthquake", "aquatail", "megahorn", "stealthrock", "rockslide", "protect"], tier: "LC", }, rhydon: { randomBattleMoves: ["stealthrock", "earthquake", "rockblast", "roar", "swordsdance", "stoneedge", "megahorn", "rockpolish"], randomDoubleBattleMoves: ["stoneedge", "earthquake", "aquatail", "megahorn", "stealthrock", "rockslide", "protect"], eventPokemon: [ {"generation": 3, "level": 46, "moves":["helpinghand", "megahorn", "scaryface", "earthquake"]}, ], tier: "NU", }, rhyperior: { randomBattleMoves: ["stoneedge", "earthquake", "aquatail", "megahorn", "stealthrock", "rockblast", "rockpolish", "dragontail"], randomDoubleBattleMoves: ["stoneedge", "earthquake", "hammerarm", "megahorn", "stealthrock", "rockslide", "aquatail", "protect"], tier: "RU", }, happiny: { randomBattleMoves: ["aromatherapy", "toxic", "thunderwave", "counter", "endeavor", "lightscreen", "fireblast"], randomDoubleBattleMoves: ["aromatherapy", "toxic", "thunderwave", "helpinghand", "swagger", "lightscreen", "fireblast", "protect"], tier: "LC", }, chansey: { randomBattleMoves: ["softboiled", "healbell", "stealthrock", "thunderwave", "toxic", "seismictoss", "wish", "protect", "counter"], randomDoubleBattleMoves: ["aromatherapy", "toxic", "thunderwave", "helpinghand", "softboiled", "lightscreen", "seismictoss", "protect", "wish"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["sweetscent", "wish"]}, {"generation": 3, "level": 10, "moves":["pound", "growl", "tailwhip", "refresh"]}, {"generation": 3, "level": 39, "moves":["sweetkiss", "thunderbolt", "softboiled", "skillswap"]}, ], tier: "OU", }, blissey: { randomBattleMoves: ["toxic", "flamethrower", "seismictoss", "softboiled", "wish", "healbell", "protect", "thunderwave", "stealthrock"], randomDoubleBattleMoves: ["wish", "softboiled", "protect", "toxic", "aromatherapy", "seismictoss", "helpinghand", "thunderwave", "flamethrower", "icebeam"], eventPokemon: [ {"generation": 5, "level": 10, "isHidden": true, "moves":["pound", "growl", "tailwhip", "refresh"]}, ], tier: "UU", }, tangela: { randomBattleMoves: ["gigadrain", "sleeppowder", "hiddenpowerfire", "hiddenpowerice", "leechseed", "knockoff", "leafstorm", "sludgebomb", "synthesis"], randomDoubleBattleMoves: ["gigadrain", "sleeppowder", "hiddenpowerrock", "hiddenpowerice", "leechseed", "knockoff", "leafstorm", "stunspore", "protect", "hiddenpowerfire"], eventPokemon: [ {"generation": 3, "level": 30, "abilities":["chlorophyll"], "moves":["morningsun", "solarbeam", "sunnyday", "ingrain"]}, ], tier: "LC Uber", }, tangrowth: { randomBattleMoves: ["gigadrain", "leafstorm", "knockoff", "earthquake", "hiddenpowerfire", "rockslide", "sleeppowder", "leechseed", "synthesis"], randomDoubleBattleMoves: ["gigadrain", "sleeppowder", "hiddenpowerice", "leechseed", "knockoff", "ragepowder", "focusblast", "protect", "powerwhip", "earthquake"], eventPokemon: [ {"generation": 4, "level": 50, "gender": "M", "nature": "Brave", "moves":["sunnyday", "morningsun", "ancientpower", "naturalgift"], "pokeball": "cherishball"}, ], tier: "OU", }, kangaskhan: { randomBattleMoves: ["return", "suckerpunch", "earthquake", "drainpunch", "crunch", "fakeout"], randomDoubleBattleMoves: ["fakeout", "return", "suckerpunch", "earthquake", "doubleedge", "drainpunch", "crunch", "protect"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "abilities":["earlybird"], "moves":["yawn", "wish"]}, {"generation": 3, "level": 10, "abilities":["earlybird"], "moves":["cometpunch", "leer", "bite"]}, {"generation": 3, "level": 35, "abilities":["earlybird"], "moves":["sing", "earthquake", "tailwhip", "dizzypunch"]}, {"generation": 6, "level": 50, "isHidden": false, "abilities":["scrappy"], "moves":["fakeout", "return", "earthquake", "suckerpunch"], "pokeball": "cherishball"}, ], tier: "PU", }, kangaskhanmega: { randomBattleMoves: ["fakeout", "return", "suckerpunch", "earthquake", "poweruppunch", "crunch"], randomDoubleBattleMoves: ["fakeout", "return", "suckerpunch", "earthquake", "doubleedge", "poweruppunch", "drainpunch", "crunch", "protect"], requiredItem: "Kangaskhanite", tier: "Uber", }, horsea: { randomBattleMoves: ["hydropump", "icebeam", "substitute", "hiddenpowergrass", "raindance"], randomDoubleBattleMoves: ["hydropump", "icebeam", "substitute", "hiddenpowergrass", "raindance", "muddywater", "protect"], eventPokemon: [ {"generation": 5, "level": 1, "shiny": true, "isHidden": false, "moves":["bubble"]}, ], tier: "LC", }, seadra: { randomBattleMoves: ["hydropump", "icebeam", "agility", "substitute", "hiddenpowergrass"], randomDoubleBattleMoves: ["hydropump", "icebeam", "substitute", "hiddenpowergrass", "agility", "muddywater", "protect"], eventPokemon: [ {"generation": 3, "level": 45, "abilities":["poisonpoint"], "moves":["leer", "watergun", "twister", "agility"]}, ], tier: "NFE", }, kingdra: { randomBattleMoves: ["dragondance", "waterfall", "outrage", "ironhead", "substitute", "raindance", "hydropump", "dracometeor"], randomDoubleBattleMoves: ["hydropump", "icebeam", "raindance", "dracometeor", "dragonpulse", "muddywater", "protect"], eventPokemon: [ {"generation": 3, "level": 50, "abilities":["swiftswim"], "moves":["leer", "watergun", "twister", "agility"]}, {"generation": 5, "level": 50, "gender": "M", "nature": "Timid", "ivs": {"hp": 31, "atk": 17, "def": 8, "spa": 31, "spd": 11, "spe": 31}, "isHidden": false, "abilities":["swiftswim"], "moves":["dracometeor", "muddywater", "dragonpulse", "protect"], "pokeball": "cherishball"}, ], tier: "OU", }, goldeen: { randomBattleMoves: ["waterfall", "megahorn", "knockoff", "drillrun", "icebeam"], randomDoubleBattleMoves: ["waterfall", "megahorn", "knockoff", "drillrun", "icebeam", "protect"], tier: "LC", }, seaking: { randomBattleMoves: ["waterfall", "megahorn", "knockoff", "drillrun", "scald", "icebeam"], randomDoubleBattleMoves: ["waterfall", "surf", "megahorn", "knockoff", "drillrun", "icebeam", "icywind", "protect"], tier: "PU", }, staryu: { randomBattleMoves: ["scald", "thunderbolt", "icebeam", "rapidspin", "recover", "dazzlinggleam", "hydropump"], randomDoubleBattleMoves: ["scald", "thunderbolt", "icebeam", "protect", "recover", "dazzlinggleam", "hydropump"], eventPokemon: [ {"generation": 3, "level": 50, "moves":["minimize", "lightscreen", "cosmicpower", "hydropump"]}, {"generation": 3, "level": 18, "nature": "Timid", "ivs": {"hp": 10, "atk": 3, "def": 22, "spa": 24, "spd": 3, "spe": 18}, "abilities":["illuminate"], "moves":["harden", "watergun", "rapidspin", "recover"]}, ], tier: "LC", }, starmie: { randomBattleMoves: ["thunderbolt", "icebeam", "rapidspin", "recover", "psyshock", "scald", "hydropump"], randomDoubleBattleMoves: ["surf", "thunderbolt", "icebeam", "protect", "recover", "psychic", "psyshock", "scald", "hydropump"], eventPokemon: [ {"generation": 3, "level": 41, "moves":["refresh", "waterfall", "icebeam", "recover"]}, ], tier: "UU", }, mimejr: { randomBattleMoves: ["batonpass", "psychic", "thunderwave", "hiddenpowerfighting", "healingwish", "nastyplot", "thunderbolt", "encore"], randomDoubleBattleMoves: ["fakeout", "psychic", "thunderwave", "hiddenpowerfighting", "healingwish", "nastyplot", "thunderbolt", "encore", "icywind", "protect"], tier: "LC", }, mrmime: { randomBattleMoves: ["nastyplot", "psychic", "psyshock", "dazzlinggleam", "shadowball", "batonpass", "focusblast", "healingwish", "encore"], randomDoubleBattleMoves: ["fakeout", "thunderwave", "hiddenpowerfighting", "psychic", "thunderbolt", "encore", "icywind", "protect", "wideguard", "dazzlinggleam", "followme"], eventPokemon: [ {"generation": 3, "level": 42, "abilities":["soundproof"], "moves":["followme", "psychic", "encore", "thunderpunch"]}, ], tier: "PU", }, scyther: { randomBattleMoves: ["swordsdance", "roost", "bugbite", "quickattack", "brickbreak", "aerialace", "batonpass", "uturn", "knockoff"], randomDoubleBattleMoves: ["swordsdance", "protect", "bugbite", "quickattack", "brickbreak", "aerialace", "feint", "uturn", "knockoff"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "abilities":["swarm"], "moves":["quickattack", "leer", "focusenergy"]}, {"generation": 3, "level": 40, "abilities":["swarm"], "moves":["morningsun", "razorwind", "silverwind", "slash"]}, {"generation": 5, "level": 30, "isHidden": false, "moves":["agility", "wingattack", "furycutter", "slash"], "pokeball": "cherishball"}, ], tier: "NU", }, scizor: { randomBattleMoves: ["swordsdance", "bulletpunch", "bugbite", "superpower", "uturn", "pursuit", "knockoff"], randomDoubleBattleMoves: ["swordsdance", "roost", "bulletpunch", "bugbite", "superpower", "uturn", "protect", "feint", "knockoff"], eventPokemon: [ {"generation": 3, "level": 50, "gender": "M", "abilities":["swarm"], "moves":["furycutter", "metalclaw", "swordsdance", "slash"]}, {"generation": 4, "level": 50, "gender": "M", "nature": "Adamant", "abilities":["swarm"], "moves":["xscissor", "swordsdance", "irondefense", "agility"], "pokeball": "cherishball"}, {"generation": 5, "level": 100, "gender": "M", "isHidden": false, "abilities":["technician"], "moves":["bulletpunch", "bugbite", "roost", "swordsdance"], "pokeball": "cherishball"}, {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["leer", "focusenergy", "pursuit", "steelwing"]}, {"generation": 6, "level": 50, "gender": "M", "isHidden": false, "moves":["xscissor", "nightslash", "doublehit", "ironhead"], "pokeball": "cherishball"}, {"generation": 6, "level": 25, "nature": "Adamant", "isHidden": false, "abilities":["technician"], "moves":["aerialace", "falseswipe", "agility", "furycutter"], "pokeball": "cherishball"}, {"generation": 6, "level": 25, "isHidden": false, "moves":["metalclaw", "falseswipe", "agility", "furycutter"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "isHidden": false, "abilities":["technician"], "moves":["bulletpunch", "swordsdance", "roost", "uturn"], "pokeball": "cherishball"}, ], tier: "UU", }, scizormega: { randomBattleMoves: ["swordsdance", "roost", "bulletpunch", "bugbite", "superpower", "uturn", "defog", "knockoff"], randomDoubleBattleMoves: ["swordsdance", "roost", "bulletpunch", "bugbite", "superpower", "uturn", "protect", "feint", "knockoff"], requiredItem: "Scizorite", tier: "OU", }, smoochum: { randomBattleMoves: ["icebeam", "psychic", "hiddenpowerfighting", "trick", "shadowball", "grassknot"], randomDoubleBattleMoves: ["icebeam", "psychic", "hiddenpowerfighting", "trick", "shadowball", "grassknot", "fakeout", "protect"], tier: "LC", }, jynx: { randomBattleMoves: ["icebeam", "psychic", "focusblast", "trick", "nastyplot", "lovelykiss", "substitute", "psyshock"], randomDoubleBattleMoves: ["icebeam", "psychic", "hiddenpowerfighting", "shadowball", "protect", "lovelykiss", "substitute", "psyshock"], tier: "PU", }, elekid: { randomBattleMoves: ["thunderbolt", "crosschop", "voltswitch", "substitute", "icepunch", "psychic", "hiddenpowergrass"], randomDoubleBattleMoves: ["thunderbolt", "crosschop", "voltswitch", "substitute", "icepunch", "psychic", "hiddenpowergrass", "protect"], eventPokemon: [ {"generation": 3, "level": 20, "moves":["icepunch", "firepunch", "thunderpunch", "crosschop"]}, ], tier: "LC", }, electabuzz: { randomBattleMoves: ["thunderbolt", "voltswitch", "substitute", "hiddenpowerice", "hiddenpowergrass", "focusblast", "psychic"], randomDoubleBattleMoves: ["thunderbolt", "crosschop", "voltswitch", "substitute", "icepunch", "psychic", "hiddenpowergrass", "protect", "focusblast", "discharge"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["quickattack", "leer", "thunderpunch"]}, {"generation": 3, "level": 43, "moves":["followme", "crosschop", "thunderwave", "thunderbolt"]}, {"generation": 4, "level": 30, "gender": "M", "nature": "Naughty", "moves":["lowkick", "shockwave", "lightscreen", "thunderpunch"]}, {"generation": 5, "level": 30, "isHidden": false, "moves":["lowkick", "swift", "shockwave", "lightscreen"], "pokeball": "cherishball"}, {"generation": 6, "level": 30, "gender": "M", "isHidden": true, "moves":["lowkick", "shockwave", "lightscreen", "thunderpunch"], "pokeball": "cherishball"}, ], tier: "NFE", }, electivire: { randomBattleMoves: ["wildcharge", "crosschop", "icepunch", "flamethrower", "earthquake", "voltswitch"], randomDoubleBattleMoves: ["wildcharge", "crosschop", "icepunch", "substitute", "flamethrower", "earthquake", "protect", "followme"], eventPokemon: [ {"generation": 4, "level": 50, "gender": "M", "nature": "Adamant", "moves":["thunderpunch", "icepunch", "crosschop", "earthquake"]}, {"generation": 4, "level": 50, "gender": "M", "nature": "Serious", "moves":["lightscreen", "thunderpunch", "discharge", "thunderbolt"], "pokeball": "cherishball"}, ], tier: "PU", }, magby: { randomBattleMoves: ["flareblitz", "substitute", "fireblast", "hiddenpowergrass", "hiddenpowerice", "crosschop", "thunderpunch", "overheat"], tier: "LC", }, magmar: { randomBattleMoves: ["flareblitz", "substitute", "fireblast", "hiddenpowergrass", "hiddenpowerice", "crosschop", "thunderpunch", "focusblast"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["leer", "smog", "firepunch", "leer"]}, {"generation": 3, "level": 36, "moves":["followme", "fireblast", "crosschop", "thunderpunch"]}, {"generation": 4, "level": 30, "gender": "M", "nature": "Quiet", "moves":["smokescreen", "firespin", "confuseray", "firepunch"]}, {"generation": 5, "level": 30, "isHidden": false, "moves":["smokescreen", "feintattack", "firespin", "confuseray"], "pokeball": "cherishball"}, {"generation": 6, "level": 30, "gender": "M", "isHidden": true, "moves":["smokescreen", "firespin", "confuseray", "firepunch"], "pokeball": "cherishball"}, ], tier: "NFE", }, magmortar: { randomBattleMoves: ["fireblast", "focusblast", "hiddenpowergrass", "hiddenpowerice", "thunderbolt", "earthquake", "substitute"], randomDoubleBattleMoves: ["fireblast", "taunt", "focusblast", "hiddenpowergrass", "hiddenpowerice", "thunderbolt", "heatwave", "willowisp", "protect", "followme"], eventPokemon: [ {"generation": 4, "level": 50, "gender": "F", "nature": "Modest", "moves":["flamethrower", "psychic", "hyperbeam", "solarbeam"]}, {"generation": 4, "level": 50, "gender": "M", "nature": "Hardy", "moves":["confuseray", "firepunch", "lavaplume", "flamethrower"], "pokeball": "cherishball"}, ], tier: "PU", }, pinsir: { randomBattleMoves: ["earthquake", "xscissor", "closecombat", "stoneedge", "stealthrock", "knockoff"], randomDoubleBattleMoves: ["protect", "swordsdance", "xscissor", "earthquake", "closecombat", "substitute", "rockslide"], eventPokemon: [ {"generation": 3, "level": 35, "abilities":["hypercutter"], "moves":["helpinghand", "guillotine", "falseswipe", "submission"]}, {"generation": 6, "level": 50, "gender": "F", "nature": "Adamant", "isHidden": false, "moves":["xscissor", "earthquake", "stoneedge", "return"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "nature": "Jolly", "isHidden": true, "moves":["earthquake", "swordsdance", "feint", "quickattack"], "pokeball": "cherishball"}, ], tier: "PU", }, pinsirmega: { randomBattleMoves: ["swordsdance", "earthquake", "closecombat", "quickattack", "return"], randomDoubleBattleMoves: ["feint", "protect", "swordsdance", "xscissor", "earthquake", "closecombat", "substitute", "quickattack", "return", "rockslide"], requiredItem: "Pinsirite", tier: "OU", }, tauros: { randomBattleMoves: ["rockclimb", "earthquake", "zenheadbutt", "rockslide", "doubleedge"], randomDoubleBattleMoves: ["return", "earthquake", "zenheadbutt", "rockslide", "stoneedge", "protect", "doubleedge"], eventPokemon: [ {"generation": 3, "level": 25, "nature": "Docile", "ivs": {"hp": 14, "atk": 19, "def": 12, "spa": 17, "spd": 5, "spe": 26}, "abilities":["intimidate"], "moves":["rage", "hornattack", "scaryface", "pursuit"], "pokeball": "safariball"}, {"generation": 3, "level": 10, "abilities":["intimidate"], "moves":["tackle", "tailwhip", "rage", "hornattack"]}, {"generation": 3, "level": 46, "abilities":["intimidate"], "moves":["refresh", "earthquake", "tailwhip", "bodyslam"]}, ], tier: "BL4", }, magikarp: { randomBattleMoves: ["bounce", "flail", "tackle", "hydropump"], eventPokemon: [ {"generation": 4, "level": 5, "gender": "M", "nature": "Relaxed", "moves":["splash"]}, {"generation": 4, "level": 6, "gender": "F", "nature": "Rash", "moves":["splash"]}, {"generation": 4, "level": 7, "gender": "F", "nature": "Hardy", "moves":["splash"]}, {"generation": 4, "level": 5, "gender": "F", "nature": "Lonely", "moves":["splash"]}, {"generation": 4, "level": 4, "gender": "M", "nature": "Modest", "moves":["splash"]}, {"generation": 5, "level": 99, "shiny": true, "gender": "M", "isHidden": false, "moves":["flail", "hydropump", "bounce", "splash"], "pokeball": "cherishball"}, {"generation": 6, "level": 1, "shiny": 1, "isHidden": false, "moves":["splash", "celebrate", "happyhour"], "pokeball": "cherishball"}, {"generation": 7, "level": 19, "shiny": true, "isHidden": false, "moves":["splash", "bounce"], "pokeball": "cherishball"}, ], tier: "LC", }, gyarados: { randomBattleMoves: ["dragondance", "waterfall", "earthquake", "bounce", "rest", "sleeptalk", "dragontail", "stoneedge", "substitute"], randomDoubleBattleMoves: ["dragondance", "waterfall", "earthquake", "bounce", "taunt", "protect", "thunderwave", "stoneedge", "substitute", "icefang"], eventPokemon: [ {"generation": 6, "level": 50, "isHidden": false, "moves":["waterfall", "earthquake", "icefang", "dragondance"], "pokeball": "cherishball"}, {"generation": 6, "level": 20, "shiny": true, "isHidden": false, "moves":["waterfall", "bite", "icefang", "ironhead"], "pokeball": "cherishball"}, ], tier: "BL", }, gyaradosmega: { randomBattleMoves: ["dragondance", "waterfall", "earthquake", "substitute", "icefang", "crunch"], randomDoubleBattleMoves: ["dragondance", "waterfall", "earthquake", "bounce", "taunt", "protect", "thunderwave", "stoneedge", "substitute", "icefang", "crunch"], requiredItem: "Gyaradosite", tier: "OU", }, lapras: { randomBattleMoves: ["icebeam", "thunderbolt", "healbell", "toxic", "hydropump", "substitute"], randomDoubleBattleMoves: ["icebeam", "thunderbolt", "hydropump", "surf", "substitute", "protect", "iceshard", "icywind"], eventPokemon: [ {"generation": 3, "level": 44, "moves":["hydropump", "raindance", "blizzard", "healbell"]}, ], tier: "PU", }, ditto: { randomBattleMoves: ["transform"], eventPokemon: [ {"generation": 7, "level": 10, "isHidden": false, "moves":["transform"], "pokeball": "cherishball"}, ], tier: "PU", }, eevee: { randomBattleMoves: ["quickattack", "return", "bite", "batonpass", "irontail", "yawn", "protect", "wish"], randomDoubleBattleMoves: ["quickattack", "return", "bite", "helpinghand", "irontail", "yawn", "protect", "wish"], eventPokemon: [ {"generation": 4, "level": 10, "gender": "F", "nature": "Lonely", "abilities":["adaptability"], "moves":["covet", "bite", "helpinghand", "attract"], "pokeball": "cherishball"}, {"generation": 4, "level": 50, "shiny": true, "gender": "M", "nature": "Hardy", "abilities":["adaptability"], "moves":["irontail", "trumpcard", "flail", "quickattack"], "pokeball": "cherishball"}, {"generation": 5, "level": 50, "gender": "F", "nature": "Hardy", "isHidden": false, "abilities":["adaptability"], "moves":["sing", "return", "echoedvoice", "attract"], "pokeball": "cherishball"}, {"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "sandattack", "babydolleyes", "swift"], "pokeball": "cherishball"}, {"generation": 6, "level": 15, "shiny": true, "isHidden": true, "moves":["swift", "quickattack", "babydolleyes", "helpinghand"], "pokeball": "cherishball"}, {"generation": 7, "level": 10, "nature": "Jolly", "isHidden": false, "moves":["celebrate", "sandattack", "babydolleyes"], "pokeball": "cherishball"}, ], tier: "LC", }, vaporeon: { randomBattleMoves: ["wish", "protect", "scald", "roar", "icebeam", "healbell", "batonpass"], randomDoubleBattleMoves: ["helpinghand", "wish", "protect", "scald", "muddywater", "icebeam", "toxic", "hydropump"], eventPokemon: [ {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]}, {"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "watergun"], "pokeball": "cherishball"}, {"generation": 7, "level": 50, "gender": "F", "isHidden": true, "moves":["scald", "icebeam", "raindance", "rest"], "pokeball": "cherishball"}, ], tier: "NU", }, jolteon: { randomBattleMoves: ["thunderbolt", "voltswitch", "hiddenpowerice", "batonpass", "substitute", "signalbeam"], randomDoubleBattleMoves: ["thunderbolt", "voltswitch", "hiddenpowergrass", "hiddenpowerice", "helpinghand", "protect", "substitute", "signalbeam"], eventPokemon: [ {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]}, {"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "thundershock"], "pokeball": "cherishball"}, {"generation": 7, "level": 50, "gender": "F", "isHidden": false, "moves":["thunderbolt", "shadowball", "lightscreen", "voltswitch"], "pokeball": "cherishball"}, ], tier: "RU", }, flareon: { randomBattleMoves: ["flamecharge", "facade", "flareblitz", "superpower", "quickattack", "batonpass"], randomDoubleBattleMoves: ["flamecharge", "facade", "flareblitz", "superpower", "wish", "protect", "helpinghand"], eventPokemon: [ {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]}, {"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "ember"], "pokeball": "cherishball"}, {"generation": 7, "level": 50, "gender": "F", "isHidden": true, "moves":["flareblitz", "facade", "willowisp", "quickattack"], "pokeball": "cherishball"}, ], tier: "PU", }, espeon: { randomBattleMoves: ["psychic", "psyshock", "substitute", "shadowball", "calmmind", "morningsun", "batonpass", "dazzlinggleam"], randomDoubleBattleMoves: ["psychic", "psyshock", "substitute", "wish", "shadowball", "hiddenpowerfighting", "helpinghand", "protect", "dazzlinggleam"], eventPokemon: [ {"generation": 3, "level": 70, "moves":["psybeam", "psychup", "psychic", "morningsun"]}, {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]}, {"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "confusion"], "pokeball": "cherishball"}, {"generation": 7, "level": 50, "gender": "F", "isHidden": true, "moves":["psychic", "dazzlinggleam", "shadowball", "reflect"], "pokeball": "cherishball"}, ], tier: "RU", }, umbreon: { randomBattleMoves: ["wish", "protect", "healbell", "toxic", "foulplay"], randomDoubleBattleMoves: ["moonlight", "wish", "protect", "healbell", "snarl", "foulplay", "helpinghand"], eventPokemon: [ {"generation": 3, "level": 70, "moves":["feintattack", "meanlook", "screech", "moonlight"]}, {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]}, {"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "pursuit"], "pokeball": "cherishball"}, {"generation": 7, "level": 50, "gender": "F", "isHidden": false, "moves":["snarl", "toxic", "protect", "moonlight"], "pokeball": "cherishball"}, ], tier: "RU", }, leafeon: { randomBattleMoves: ["swordsdance", "leafblade", "substitute", "xscissor", "synthesis", "batonpass", "knockoff"], randomDoubleBattleMoves: ["swordsdance", "leafblade", "substitute", "xscissor", "protect", "helpinghand", "knockoff"], eventPokemon: [ {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]}, {"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "razorleaf"], "pokeball": "cherishball"}, {"generation": 7, "level": 50, "gender": "F", "isHidden": true, "moves":["leafblade", "swordsdance", "sunnyday", "synthesis"], "pokeball": "cherishball"}, ], tier: "PU", }, glaceon: { randomBattleMoves: ["icebeam", "hiddenpowerground", "shadowball", "healbell", "wish", "protect", "toxic"], randomDoubleBattleMoves: ["icebeam", "hiddenpowerground", "shadowball", "wish", "protect", "healbell", "helpinghand"], eventPokemon: [ {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]}, {"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "icywind"], "pokeball": "cherishball"}, {"generation": 7, "level": 50, "gender": "F", "isHidden": false, "moves":["blizzard", "shadowball", "hail", "auroraveil"], "pokeball": "cherishball"}, ], tier: "PU", }, porygon: { randomBattleMoves: ["triattack", "icebeam", "recover", "toxic", "thunderwave", "discharge", "trick"], eventPokemon: [ {"generation": 5, "level": 10, "isHidden": true, "moves":["tackle", "conversion", "sharpen", "psybeam"]}, ], tier: "LC Uber", }, porygon2: { randomBattleMoves: ["triattack", "icebeam", "recover", "toxic", "thunderwave", "thunderbolt"], randomDoubleBattleMoves: ["triattack", "icebeam", "discharge", "shadowball", "thunderbolt", "protect", "recover"], tier: "RU", }, porygonz: { randomBattleMoves: ["triattack", "shadowball", "icebeam", "thunderbolt", "conversion", "trick", "nastyplot"], randomDoubleBattleMoves: ["protect", "triattack", "darkpulse", "hiddenpowerfighting", "icebeam", "thunderbolt", "agility", "trick", "nastyplot"], tier: "BL", }, omanyte: { randomBattleMoves: ["shellsmash", "surf", "icebeam", "earthpower", "hiddenpowerelectric", "spikes", "toxicspikes", "stealthrock", "hydropump"], eventPokemon: [ {"generation": 5, "level": 15, "gender": "M", "isHidden": false, "abilities":["swiftswim"], "moves":["bubblebeam", "supersonic", "withdraw", "bite"], "pokeball": "cherishball"}, ], tier: "LC", }, omastar: { randomBattleMoves: ["shellsmash", "scald", "icebeam", "earthpower", "spikes", "stealthrock", "hydropump"], randomDoubleBattleMoves: ["shellsmash", "muddywater", "icebeam", "earthpower", "hiddenpowerelectric", "protect", "hydropump"], tier: "NU", }, kabuto: { randomBattleMoves: ["aquajet", "rockslide", "rapidspin", "stealthrock", "honeclaws", "waterfall", "toxic"], eventPokemon: [ {"generation": 5, "level": 15, "gender": "M", "isHidden": false, "abilities":["battlearmor"], "moves":["confuseray", "dig", "scratch", "harden"], "pokeball": "cherishball"}, ], tier: "LC", }, kabutops: { randomBattleMoves: ["aquajet", "stoneedge", "rapidspin", "swordsdance", "waterfall", "knockoff"], randomDoubleBattleMoves: ["aquajet", "stoneedge", "protect", "rockslide", "swordsdance", "waterfall", "superpower", "knockoff"], tier: "PU", }, aerodactyl: { randomBattleMoves: ["stealthrock", "taunt", "stoneedge", "earthquake", "defog", "roost", "doubleedge"], randomDoubleBattleMoves: ["wideguard", "taunt", "stoneedge", "rockslide", "earthquake", "aquatail", "protect", "icefang", "skydrop", "tailwind"], eventPokemon: [ {"generation": 5, "level": 15, "gender": "M", "isHidden": false, "abilities":["pressure"], "moves":["steelwing", "icefang", "firefang", "thunderfang"], "pokeball": "cherishball"}, ], tier: "RU", }, aerodactylmega: { randomBattleMoves: ["aquatail", "pursuit", "honeclaws", "stoneedge", "firefang", "aerialace", "roost"], randomDoubleBattleMoves: ["wideguard", "taunt", "stoneedge", "rockslide", "earthquake", "ironhead", "aerialace", "protect", "icefang", "skydrop", "tailwind"], requiredItem: "Aerodactylite", tier: "UU", }, munchlax: { randomBattleMoves: ["rest", "curse", "sleeptalk", "bodyslam", "earthquake", "return", "firepunch", "icepunch", "whirlwind", "toxic"], eventPokemon: [ {"generation": 4, "level": 5, "moves":["metronome", "tackle", "defensecurl", "selfdestruct"]}, {"generation": 4, "level": 5, "gender": "F", "nature": "Relaxed", "abilities":["thickfat"], "moves":["metronome", "odorsleuth", "tackle", "curse"], "pokeball": "cherishball"}, {"generation": 7, "level": 5, "isHidden": false, "abilities":["thickfat"], "moves":["tackle", "metronome", "holdback", "happyhour"], "pokeball": "cherishball"}, ], tier: "LC", }, snorlax: { randomBattleMoves: ["rest", "curse", "sleeptalk", "bodyslam", "earthquake", "return", "firepunch", "crunch", "pursuit", "whirlwind"], randomDoubleBattleMoves: ["curse", "protect", "bodyslam", "earthquake", "return", "firepunch", "icepunch", "crunch", "selfdestruct"], eventPokemon: [ {"generation": 3, "level": 43, "moves":["refresh", "fissure", "curse", "bodyslam"]}, ], tier: "RU", }, articuno: { randomBattleMoves: ["icebeam", "roost", "freezedry", "toxic", "substitute", "hurricane"], randomDoubleBattleMoves: ["freezedry", "roost", "protect", "substitute", "hurricane", "tailwind"], eventPokemon: [ {"generation": 3, "level": 50, "shiny": 1, "moves":["mist", "agility", "mindreader", "icebeam"]}, {"generation": 3, "level": 70, "moves":["agility", "mindreader", "icebeam", "reflect"]}, {"generation": 3, "level": 50, "moves":["icebeam", "healbell", "extrasensory", "haze"]}, {"generation": 4, "level": 60, "shiny": 1, "moves":["agility", "icebeam", "reflect", "roost"]}, {"generation": 4, "level": 50, "shiny": 1, "moves":["mist", "agility", "mindreader", "icebeam"]}, {"generation": 6, "level": 70, "isHidden": false, "moves":["icebeam", "reflect", "hail", "tailwind"]}, {"generation": 6, "level": 70, "isHidden": true, "moves":["freezedry", "icebeam", "hail", "reflect"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "PU", }, zapdos: { randomBattleMoves: ["thunderbolt", "heatwave", "hiddenpowerice", "roost", "toxic", "uturn", "defog"], randomDoubleBattleMoves: ["thunderbolt", "heatwave", "hiddenpowergrass", "hiddenpowerice", "tailwind", "protect", "discharge"], eventPokemon: [ {"generation": 3, "level": 50, "shiny": 1, "moves":["thunderwave", "agility", "detect", "drillpeck"]}, {"generation": 3, "level": 70, "moves":["agility", "detect", "drillpeck", "charge"]}, {"generation": 3, "level": 50, "moves":["thunderbolt", "extrasensory", "batonpass", "metalsound"]}, {"generation": 4, "level": 60, "shiny": 1, "moves":["charge", "agility", "discharge", "roost"]}, {"generation": 4, "level": 50, "shiny": 1, "moves":["thunderwave", "agility", "detect", "drillpeck"]}, {"generation": 6, "level": 70, "isHidden": false, "moves":["agility", "discharge", "raindance", "lightscreen"]}, {"generation": 6, "level": 70, "isHidden": true, "moves":["discharge", "thundershock", "raindance", "agility"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "OU", }, moltres: { randomBattleMoves: ["fireblast", "hiddenpowergrass", "roost", "substitute", "toxic", "willowisp", "hurricane"], randomDoubleBattleMoves: ["fireblast", "hiddenpowergrass", "airslash", "roost", "substitute", "protect", "uturn", "willowisp", "hurricane", "heatwave", "tailwind"], eventPokemon: [ {"generation": 3, "level": 50, "shiny": 1, "moves":["firespin", "agility", "endure", "flamethrower"]}, {"generation": 3, "level": 70, "moves":["agility", "endure", "flamethrower", "safeguard"]}, {"generation": 3, "level": 50, "moves":["extrasensory", "morningsun", "willowisp", "flamethrower"]}, {"generation": 4, "level": 60, "shiny": 1, "moves":["flamethrower", "safeguard", "airslash", "roost"]}, {"generation": 4, "level": 50, "shiny": 1, "moves":["firespin", "agility", "endure", "flamethrower"]}, {"generation": 6, "level": 70, "isHidden": false, "moves":["safeguard", "airslash", "sunnyday", "heatwave"]}, {"generation": 6, "level": 70, "isHidden": true, "moves":["skyattack", "heatwave", "sunnyday", "safeguard"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "RU", }, dratini: { randomBattleMoves: ["dragondance", "outrage", "waterfall", "fireblast", "extremespeed", "dracometeor", "substitute"], tier: "LC", }, dragonair: { randomBattleMoves: ["dragondance", "outrage", "waterfall", "fireblast", "extremespeed", "dracometeor", "substitute"], tier: "NFE", }, dragonite: { randomBattleMoves: ["dragondance", "outrage", "firepunch", "extremespeed", "earthquake", "roost"], randomDoubleBattleMoves: ["dragondance", "firepunch", "extremespeed", "dragonclaw", "earthquake", "roost", "substitute", "superpower", "dracometeor", "protect", "skydrop"], eventPokemon: [ {"generation": 3, "level": 70, "moves":["agility", "safeguard", "wingattack", "outrage"]}, {"generation": 3, "level": 55, "moves":["healbell", "hyperbeam", "dragondance", "earthquake"]}, {"generation": 4, "level": 50, "gender": "M", "nature": "Mild", "moves":["dracometeor", "thunderbolt", "outrage", "dragondance"], "pokeball": "cherishball"}, {"generation": 5, "level": 100, "gender": "M", "isHidden": true, "moves":["extremespeed", "firepunch", "dragondance", "outrage"], "pokeball": "cherishball"}, {"generation": 5, "level": 55, "gender": "M", "isHidden": true, "moves":["dragonrush", "safeguard", "wingattack", "thunderpunch"]}, {"generation": 5, "level": 55, "gender": "M", "isHidden": true, "moves":["dragonrush", "safeguard", "wingattack", "extremespeed"]}, {"generation": 5, "level": 50, "gender": "M", "nature": "Brave", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "moves":["fireblast", "safeguard", "outrage", "hyperbeam"], "pokeball": "cherishball"}, {"generation": 6, "level": 55, "gender": "M", "isHidden": true, "moves":["dragondance", "outrage", "hurricane", "extremespeed"], "pokeball": "cherishball"}, {"generation": 6, "level": 62, "gender": "M", "ivs": {"hp": 31, "def": 31, "spa": 31, "spd": 31}, "isHidden": false, "moves":["agility", "slam", "barrier", "hyperbeam"], "pokeball": "cherishball"}, ], tier: "OU", }, mewtwo: { randomBattleMoves: ["psystrike", "aurasphere", "fireblast", "icebeam", "calmmind", "recover"], randomDoubleBattleMoves: ["psystrike", "aurasphere", "fireblast", "icebeam", "calmmind", "substitute", "recover", "thunderbolt", "willowisp", "taunt", "protect"], eventPokemon: [ {"generation": 3, "level": 70, "shiny": 1, "moves":["swift", "recover", "safeguard", "psychic"]}, {"generation": 4, "level": 70, "shiny": 1, "moves":["psychocut", "amnesia", "powerswap", "guardswap"]}, {"generation": 5, "level": 70, "isHidden": false, "moves":["psystrike", "shadowball", "aurasphere", "electroball"], "pokeball": "cherishball"}, {"generation": 5, "level": 100, "nature": "Timid", "ivs": {"spa": 31, "spe": 31}, "isHidden": true, "moves":["psystrike", "icebeam", "healpulse", "hurricane"], "pokeball": "cherishball"}, {"generation": 6, "level": 70, "isHidden": false, "moves":["recover", "psychic", "barrier", "aurasphere"]}, {"generation": 6, "level": 100, "shiny": true, "isHidden": true, "moves":["psystrike", "psychic", "recover", "aurasphere"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "Uber", }, mewtwomegax: { randomBattleMoves: ["bulkup", "drainpunch", "earthquake", "taunt", "stoneedge", "zenheadbutt", "icebeam"], randomDoubleBattleMoves: ["bulkup", "drainpunch", "earthquake", "taunt", "stoneedge", "zenheadbutt", "icebeam"], requiredItem: "Mewtwonite X", tier: "Uber", }, mewtwomegay: { randomBattleMoves: ["psystrike", "aurasphere", "shadowball", "fireblast", "icebeam", "calmmind", "recover", "willowisp", "taunt"], randomDoubleBattleMoves: ["psystrike", "aurasphere", "shadowball", "fireblast", "icebeam", "calmmind", "recover", "willowisp", "taunt"], requiredItem: "Mewtwonite Y", tier: "Uber", }, mew: { randomBattleMoves: ["defog", "roost", "willowisp", "knockoff", "taunt", "icebeam", "earthpower", "aurasphere", "stealthrock", "nastyplot", "psyshock", "batonpass"], randomDoubleBattleMoves: ["taunt", "willowisp", "transform", "roost", "psyshock", "nastyplot", "aurasphere", "fireblast", "icebeam", "thunderbolt", "protect", "fakeout", "helpinghand", "tailwind"], eventPokemon: [ {"generation": 3, "level": 30, "shiny": 1, "moves":["pound", "transform", "megapunch", "metronome"]}, {"generation": 3, "level": 10, "moves":["pound", "transform"]}, {"generation": 3, "level": 30, "shiny": 1, "moves":["fakeout"]}, {"generation": 3, "level": 10, "moves":["fakeout"]}, {"generation": 3, "level": 30, "shiny": 1, "moves":["feintattack"]}, {"generation": 3, "level": 10, "moves":["feintattack"]}, {"generation": 3, "level": 30, "shiny": 1, "moves":["hypnosis"]}, {"generation": 3, "level": 10, "moves":["hypnosis"]}, {"generation": 3, "level": 30, "shiny": 1, "moves":["nightshade"]}, {"generation": 3, "level": 10, "moves":["nightshade"]}, {"generation": 3, "level": 30, "shiny": 1, "moves":["roleplay"]}, {"generation": 3, "level": 10, "moves":["roleplay"]}, {"generation": 3, "level": 30, "shiny": 1, "moves":["zapcannon"]}, {"generation": 3, "level": 10, "moves":["zapcannon"]}, {"generation": 4, "level": 50, "moves":["ancientpower", "metronome", "teleport", "aurasphere"], "pokeball": "cherishball"}, {"generation": 4, "level": 50, "moves":["barrier", "metronome", "teleport", "aurasphere"], "pokeball": "cherishball"}, {"generation": 4, "level": 50, "moves":["megapunch", "metronome", "teleport", "aurasphere"], "pokeball": "cherishball"}, {"generation": 4, "level": 50, "moves":["amnesia", "metronome", "teleport", "aurasphere"], "pokeball": "cherishball"}, {"generation": 4, "level": 50, "moves":["transform", "metronome", "teleport", "aurasphere"], "pokeball": "cherishball"}, {"generation": 4, "level": 50, "moves":["psychic", "metronome", "teleport", "aurasphere"], "pokeball": "cherishball"}, {"generation": 4, "level": 50, "moves":["synthesis", "return", "hypnosis", "teleport"], "pokeball": "cherishball"}, {"generation": 4, "level": 5, "moves":["pound"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "moves":["pound"], "pokeball": "cherishball"}, {"generation": 7, "level": 5, "moves":["pound"], "pokeball": "cherishball"}, {"generation": 7, "level": 50, "moves":["psychic", "barrier", "metronome", "transform"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "OU", }, chikorita: { randomBattleMoves: ["reflect", "lightscreen", "aromatherapy", "grasswhistle", "leechseed", "toxic", "gigadrain", "synthesis"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "growl", "razorleaf"]}, {"generation": 3, "level": 5, "moves":["tackle", "growl", "ancientpower", "frenzyplant"]}, {"generation": 6, "level": 5, "isHidden": false, "moves":["tackle", "growl"], "pokeball": "cherishball"}, ], tier: "LC", }, bayleef: { randomBattleMoves: ["reflect", "lightscreen", "aromatherapy", "grasswhistle", "leechseed", "toxic", "gigadrain", "synthesis"], tier: "NFE", }, meganium: { randomBattleMoves: ["reflect", "lightscreen", "aromatherapy", "leechseed", "toxic", "gigadrain", "synthesis", "dragontail"], randomDoubleBattleMoves: ["reflect", "lightscreen", "leechseed", "leafstorm", "gigadrain", "synthesis", "dragontail", "healpulse", "toxic", "protect"], eventPokemon: [ {"generation": 6, "level": 50, "isHidden": true, "moves":["solarbeam", "sunnyday", "synthesis", "bodyslam"]}, ], tier: "PU", }, cyndaquil: { randomBattleMoves: ["eruption", "fireblast", "flamethrower", "hiddenpowergrass", "hiddenpowerice"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "leer", "smokescreen"]}, {"generation": 3, "level": 5, "moves":["tackle", "leer", "reversal", "blastburn"]}, {"generation": 6, "level": 5, "isHidden": false, "moves":["tackle", "leer"], "pokeball": "cherishball"}, ], tier: "LC", }, quilava: { randomBattleMoves: ["eruption", "fireblast", "flamethrower", "hiddenpowergrass", "hiddenpowerice"], tier: "NFE", }, typhlosion: { randomBattleMoves: ["eruption", "fireblast", "hiddenpowergrass", "extrasensory", "focusblast"], randomDoubleBattleMoves: ["eruption", "fireblast", "hiddenpowergrass", "extrasensory", "focusblast", "heatwave", "protect"], eventPokemon: [ {"generation": 3, "level": 70, "moves":["quickattack", "flamewheel", "swift", "flamethrower"]}, {"generation": 6, "level": 50, "isHidden": true, "moves":["overheat", "flamewheel", "flamecharge", "swift"]}, ], tier: "NU", }, totodile: { randomBattleMoves: ["aquajet", "waterfall", "crunch", "icepunch", "superpower", "dragondance", "swordsdance"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "leer", "rage"]}, {"generation": 3, "level": 5, "moves":["scratch", "leer", "crunch", "hydrocannon"]}, {"generation": 6, "level": 5, "isHidden": false, "moves":["scratch", "leer"], "pokeball": "cherishball"}, ], tier: "LC", }, croconaw: { randomBattleMoves: ["aquajet", "waterfall", "crunch", "icepunch", "superpower", "dragondance", "swordsdance"], tier: "NFE", }, feraligatr: { randomBattleMoves: ["aquajet", "waterfall", "crunch", "icepunch", "dragondance", "swordsdance", "earthquake"], randomDoubleBattleMoves: ["aquajet", "waterfall", "crunch", "icepunch", "dragondance", "swordsdance", "earthquake", "protect"], eventPokemon: [ {"generation": 6, "level": 50, "isHidden": true, "moves":["icepunch", "crunch", "waterfall", "screech"]}, ], tier: "RU", }, sentret: { randomBattleMoves: ["superfang", "trick", "toxic", "uturn", "knockoff"], tier: "LC", }, furret: { randomBattleMoves: ["uturn", "trick", "aquatail", "firepunch", "knockoff", "doubleedge"], randomDoubleBattleMoves: ["uturn", "suckerpunch", "icepunch", "firepunch", "knockoff", "doubleedge", "superfang", "followme", "helpinghand", "protect"], tier: "PU", }, hoothoot: { randomBattleMoves: ["reflect", "toxic", "roost", "whirlwind", "nightshade", "magiccoat"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "growl", "foresight"]}, ], tier: "LC", }, noctowl: { randomBattleMoves: ["roost", "whirlwind", "airslash", "nightshade", "toxic", "defog"], randomDoubleBattleMoves: ["roost", "tailwind", "airslash", "hypervoice", "heatwave", "protect", "hypnosis"], tier: "PU", }, ledyba: { randomBattleMoves: ["roost", "agility", "lightscreen", "encore", "reflect", "knockoff", "swordsdance", "batonpass", "toxic"], eventPokemon: [ {"generation": 3, "level": 10, "moves":["refresh", "psybeam", "aerialace", "supersonic"]}, ], tier: "LC", }, ledian: { randomBattleMoves: ["roost", "lightscreen", "encore", "reflect", "knockoff", "toxic", "uturn"], randomDoubleBattleMoves: ["protect", "lightscreen", "encore", "reflect", "knockoff", "bugbuzz", "uturn", "tailwind"], tier: "PU", }, spinarak: { randomBattleMoves: ["agility", "toxic", "xscissor", "toxicspikes", "poisonjab", "batonpass", "stickyweb"], eventPokemon: [ {"generation": 3, "level": 14, "moves":["refresh", "dig", "signalbeam", "nightshade"]}, ], tier: "LC", }, ariados: { randomBattleMoves: ["megahorn", "toxicspikes", "poisonjab", "suckerpunch", "stickyweb"], randomDoubleBattleMoves: ["protect", "megahorn", "stringshot", "poisonjab", "stickyweb", "ragepowder"], tier: "PU", }, chinchou: { randomBattleMoves: ["voltswitch", "thunderbolt", "hiddenpowergrass", "hydropump", "icebeam", "surf", "thunderwave", "scald", "discharge", "healbell"], tier: "LC", }, lanturn: { randomBattleMoves: ["voltswitch", "hiddenpowergrass", "hydropump", "icebeam", "thunderwave", "scald", "thunderbolt", "healbell", "toxic"], randomDoubleBattleMoves: ["thunderbolt", "hiddenpowergrass", "hydropump", "icebeam", "thunderwave", "scald", "discharge", "protect", "surf"], tier: "PU", }, togepi: { randomBattleMoves: ["protect", "fireblast", "toxic", "thunderwave", "softboiled", "dazzlinggleam"], eventPokemon: [ {"generation": 3, "level": 20, "gender": "F", "abilities":["serenegrace"], "moves":["metronome", "charm", "sweetkiss", "yawn"]}, {"generation": 3, "level": 25, "moves":["triattack", "followme", "ancientpower", "helpinghand"]}, ], tier: "LC", }, togetic: { randomBattleMoves: ["nastyplot", "dazzlinggleam", "fireblast", "batonpass", "roost", "defog", "toxic", "thunderwave", "healbell"], tier: "NFE", }, togekiss: { randomBattleMoves: ["roost", "thunderwave", "nastyplot", "airslash", "aurasphere", "batonpass", "healbell", "defog"], randomDoubleBattleMoves: ["roost", "thunderwave", "nastyplot", "airslash", "followme", "dazzlinggleam", "tailwind", "protect"], eventPokemon: [ {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["extremespeed", "aurasphere", "airslash", "present"]}, ], tier: "UU", }, natu: { randomBattleMoves: ["thunderwave", "roost", "toxic", "reflect", "lightscreen", "uturn", "wish", "psychic", "nightshade"], eventPokemon: [ {"generation": 3, "level": 22, "moves":["batonpass", "futuresight", "nightshade", "aerialace"]}, ], tier: "LC", }, xatu: { randomBattleMoves: ["thunderwave", "toxic", "roost", "psychic", "uturn", "reflect", "calmmind", "nightshade", "heatwave"], randomDoubleBattleMoves: ["thunderwave", "tailwind", "roost", "psychic", "uturn", "reflect", "lightscreen", "grassknot", "heatwave", "protect"], tier: "NU", }, mareep: { randomBattleMoves: ["reflect", "lightscreen", "thunderbolt", "discharge", "thunderwave", "toxic", "hiddenpowerice", "cottonguard", "powergem"], eventPokemon: [ {"generation": 3, "level": 37, "gender": "F", "moves":["thunder", "thundershock", "thunderwave", "cottonspore"]}, {"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "growl", "thundershock"]}, {"generation": 3, "level": 17, "moves":["healbell", "thundershock", "thunderwave", "bodyslam"]}, {"generation": 6, "level": 10, "isHidden": false, "moves":["holdback", "tackle", "thunderwave", "thundershock"], "pokeball": "cherishball"}, ], tier: "LC", }, flaaffy: { randomBattleMoves: ["reflect", "lightscreen", "thunderbolt", "discharge", "thunderwave", "toxic", "hiddenpowerice", "cottonguard", "powergem"], tier: "NFE", }, ampharos: { randomBattleMoves: ["voltswitch", "reflect", "lightscreen", "focusblast", "thunderbolt", "toxic", "healbell", "hiddenpowerice"], randomDoubleBattleMoves: ["focusblast", "hiddenpowerice", "hiddenpowergrass", "thunderbolt", "discharge", "dragonpulse", "protect"], tier: "PU", }, ampharosmega: { randomBattleMoves: ["voltswitch", "focusblast", "agility", "thunderbolt", "healbell", "dragonpulse"], randomDoubleBattleMoves: ["focusblast", "hiddenpowerice", "hiddenpowergrass", "thunderbolt", "discharge", "dragonpulse", "protect"], requiredItem: "Ampharosite", tier: "UU", }, azurill: { randomBattleMoves: ["scald", "return", "bodyslam", "encore", "toxic", "protect", "knockoff"], tier: "LC", }, marill: { randomBattleMoves: ["waterfall", "knockoff", "encore", "toxic", "aquajet", "superpower", "icepunch", "protect", "playrough", "poweruppunch"], tier: "NFE", }, azumarill: { randomBattleMoves: ["waterfall", "aquajet", "playrough", "superpower", "bellydrum", "knockoff"], randomDoubleBattleMoves: ["waterfall", "aquajet", "playrough", "superpower", "bellydrum", "knockoff", "protect"], tier: "BL", }, bonsly: { randomBattleMoves: ["rockslide", "brickbreak", "doubleedge", "toxic", "stealthrock", "suckerpunch", "explosion"], tier: "LC", }, sudowoodo: { randomBattleMoves: ["headsmash", "earthquake", "suckerpunch", "woodhammer", "toxic", "stealthrock"], randomDoubleBattleMoves: ["headsmash", "earthquake", "suckerpunch", "woodhammer", "explosion", "stealthrock", "rockslide", "helpinghand", "protect"], tier: "PU", }, hoppip: { randomBattleMoves: ["encore", "sleeppowder", "uturn", "toxic", "leechseed", "substitute", "protect"], tier: "LC", }, skiploom: { randomBattleMoves: ["encore", "sleeppowder", "uturn", "toxic", "leechseed", "substitute", "protect"], tier: "NFE", }, jumpluff: { randomBattleMoves: ["swordsdance", "sleeppowder", "uturn", "encore", "toxic", "acrobatics", "leechseed", "seedbomb", "substitute"], randomDoubleBattleMoves: ["encore", "sleeppowder", "uturn", "helpinghand", "leechseed", "gigadrain", "ragepowder", "protect"], eventPokemon: [ {"generation": 5, "level": 27, "gender": "M", "isHidden": true, "moves":["falseswipe", "sleeppowder", "bulletseed", "leechseed"]}, ], tier: "PU", }, aipom: { randomBattleMoves: ["fakeout", "return", "brickbreak", "seedbomb", "knockoff", "uturn", "icepunch", "irontail"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "tailwhip", "sandattack"]}, ], tier: "LC", }, ambipom: { randomBattleMoves: ["fakeout", "return", "knockoff", "uturn", "switcheroo", "seedbomb", "lowkick"], randomDoubleBattleMoves: ["fakeout", "return", "knockoff", "uturn", "doublehit", "icepunch", "lowkick", "protect"], tier: "NU", }, sunkern: { randomBattleMoves: ["sunnyday", "gigadrain", "solarbeam", "hiddenpowerfire", "toxic", "earthpower", "leechseed"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "abilities":["chlorophyll"], "moves":["absorb", "growth"]}, ], tier: "LC", }, sunflora: { randomBattleMoves: ["sunnyday", "gigadrain", "solarbeam", "hiddenpowerfire", "earthpower"], randomDoubleBattleMoves: ["sunnyday", "gigadrain", "solarbeam", "hiddenpowerfire", "hiddenpowerice", "earthpower", "protect", "encore"], tier: "PU", }, yanma: { randomBattleMoves: ["bugbuzz", "airslash", "hiddenpowerground", "uturn", "protect", "gigadrain", "ancientpower"], tier: "LC Uber", }, yanmega: { randomBattleMoves: ["bugbuzz", "airslash", "ancientpower", "uturn", "protect", "gigadrain"], tier: "BL3", }, wooper: { randomBattleMoves: ["recover", "earthquake", "scald", "toxic", "stockpile", "yawn", "protect"], tier: "LC", }, quagsire: { randomBattleMoves: ["recover", "earthquake", "scald", "toxic", "encore", "icebeam"], randomDoubleBattleMoves: ["icywind", "earthquake", "waterfall", "scald", "rockslide", "curse", "yawn", "icepunch", "protect"], tier: "RU", }, murkrow: { randomBattleMoves: ["substitute", "suckerpunch", "bravebird", "heatwave", "roost", "darkpulse", "thunderwave"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "abilities":["insomnia"], "moves":["peck", "astonish"]}, ], tier: "LC Uber", }, honchkrow: { randomBattleMoves: ["substitute", "superpower", "suckerpunch", "bravebird", "roost", "heatwave", "pursuit"], randomDoubleBattleMoves: ["substitute", "superpower", "suckerpunch", "bravebird", "roost", "heatwave", "protect"], tier: "RU", }, misdreavus: { randomBattleMoves: ["nastyplot", "thunderbolt", "dazzlinggleam", "willowisp", "shadowball", "taunt", "painsplit"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["growl", "psywave", "spite"]}, ], tier: "LC Uber", }, mismagius: { randomBattleMoves: ["nastyplot", "substitute", "willowisp", "shadowball", "thunderbolt", "dazzlinggleam", "taunt", "painsplit", "destinybond"], randomDoubleBattleMoves: ["nastyplot", "substitute", "willowisp", "shadowball", "thunderbolt", "dazzlinggleam", "taunt", "protect"], tier: "NU", }, unown: { randomBattleMoves: ["hiddenpowerpsychic"], tier: "PU", }, wynaut: { randomBattleMoves: ["destinybond", "counter", "mirrorcoat", "encore"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["splash", "charm", "encore", "tickle"]}, ], tier: "LC", }, wobbuffet: { randomBattleMoves: ["counter", "mirrorcoat", "encore", "destinybond", "safeguard"], randomDoubleBattleMoves: ["counter", "mirrorcoat", "encore", "destinybond", "safeguard"], eventPokemon: [ {"generation": 3, "level": 5, "moves":["counter", "mirrorcoat", "safeguard", "destinybond"]}, {"generation": 3, "level": 10, "gender": "M", "moves":["counter", "mirrorcoat", "safeguard", "destinybond"]}, {"generation": 6, "level": 10, "gender": "M", "isHidden": false, "moves":["counter"], "pokeball": "cherishball"}, {"generation": 6, "level": 15, "gender": "M", "isHidden": false, "moves":["counter", "mirrorcoat"], "pokeball": "cherishball"}, ], tier: "PU", }, girafarig: { randomBattleMoves: ["psychic", "psyshock", "thunderbolt", "nastyplot", "batonpass", "substitute", "hypervoice"], randomDoubleBattleMoves: ["psychic", "psyshock", "thunderbolt", "nastyplot", "protect", "agility", "hypervoice"], tier: "PU", }, pineco: { randomBattleMoves: ["rapidspin", "toxicspikes", "spikes", "bugbite", "stealthrock"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "protect", "selfdestruct"]}, {"generation": 3, "level": 20, "moves":["refresh", "pinmissile", "spikes", "counter"]}, ], tier: "LC", }, forretress: { randomBattleMoves: ["rapidspin", "toxic", "spikes", "voltswitch", "stealthrock", "gyroball"], randomDoubleBattleMoves: ["rockslide", "drillrun", "toxic", "voltswitch", "stealthrock", "gyroball", "protect"], tier: "UU", }, dunsparce: { randomBattleMoves: ["coil", "rockslide", "bite", "headbutt", "glare", "bodyslam", "roost"], randomDoubleBattleMoves: ["coil", "rockslide", "bite", "headbutt", "glare", "bodyslam", "protect"], tier: "PU", }, gligar: { randomBattleMoves: ["stealthrock", "toxic", "roost", "defog", "earthquake", "uturn", "knockoff"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["poisonsting", "sandattack"]}, ], tier: "RU", }, gliscor: { randomBattleMoves: ["roost", "substitute", "taunt", "earthquake", "protect", "toxic", "stealthrock", "knockoff"], randomDoubleBattleMoves: ["tailwind", "substitute", "taunt", "earthquake", "protect", "stoneedge", "knockoff"], tier: "UU", }, snubbull: { randomBattleMoves: ["thunderwave", "firepunch", "crunch", "closecombat", "icepunch", "earthquake", "playrough"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "scaryface", "tailwhip", "charm"]}, ], tier: "LC", }, granbull: { randomBattleMoves: ["thunderwave", "playrough", "crunch", "earthquake", "healbell"], randomDoubleBattleMoves: ["thunderwave", "playrough", "crunch", "earthquake", "snarl", "rockslide", "protect"], tier: "PU", }, qwilfish: { randomBattleMoves: ["toxicspikes", "waterfall", "spikes", "painsplit", "thunderwave", "taunt", "destinybond"], randomDoubleBattleMoves: ["poisonjab", "waterfall", "swordsdance", "protect", "thunderwave", "taunt", "destinybond"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "poisonsting", "harden", "minimize"]}, ], tier: "PU", }, shuckle: { randomBattleMoves: ["toxic", "encore", "stealthrock", "knockoff", "stickyweb", "infestation"], randomDoubleBattleMoves: ["encore", "stealthrock", "knockoff", "stickyweb", "guardsplit", "powersplit", "toxic", "helpinghand"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "abilities":["sturdy"], "moves":["constrict", "withdraw", "wrap"]}, {"generation": 3, "level": 20, "abilities":["sturdy"], "moves":["substitute", "toxic", "sludgebomb", "encore"]}, ], tier: "NU", }, heracross: { randomBattleMoves: ["closecombat", "megahorn", "stoneedge", "swordsdance", "knockoff", "earthquake"], randomDoubleBattleMoves: ["closecombat", "megahorn", "stoneedge", "swordsdance", "knockoff", "earthquake", "protect"], eventPokemon: [ {"generation": 6, "level": 50, "gender": "F", "nature": "Adamant", "isHidden": false, "moves":["bulletseed", "pinmissile", "closecombat", "megahorn"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "nature": "Adamant", "isHidden": false, "abilities":["guts"], "moves":["pinmissile", "bulletseed", "earthquake", "rockblast"], "pokeball": "cherishball"}, ], tier: "UU", }, heracrossmega: { randomBattleMoves: ["closecombat", "pinmissile", "rockblast", "swordsdance", "bulletseed", "substitute"], randomDoubleBattleMoves: ["closecombat", "pinmissile", "rockblast", "swordsdance", "bulletseed", "knockoff", "earthquake", "protect"], requiredItem: "Heracronite", tier: "BL", }, sneasel: { randomBattleMoves: ["iceshard", "iciclecrash", "lowkick", "pursuit", "swordsdance", "knockoff"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "leer", "taunt", "quickattack"]}, ], tier: "NU", }, weavile: { randomBattleMoves: ["iceshard", "iciclecrash", "knockoff", "pursuit", "swordsdance", "lowkick"], randomDoubleBattleMoves: ["iceshard", "iciclecrash", "knockoff", "fakeout", "swordsdance", "lowkick", "taunt", "protect", "feint"], eventPokemon: [ {"generation": 4, "level": 30, "gender": "M", "nature": "Jolly", "moves":["fakeout", "iceshard", "nightslash", "brickbreak"], "pokeball": "cherishball"}, {"generation": 6, "level": 48, "gender": "M", "perfectIVs": 2, "isHidden": false, "moves":["nightslash", "icepunch", "brickbreak", "xscissor"], "pokeball": "cherishball"}, ], tier: "UU", }, teddiursa: { randomBattleMoves: ["swordsdance", "protect", "facade", "closecombat", "firepunch", "crunch", "playrough", "gunkshot"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "abilities":["pickup"], "moves":["scratch", "leer", "lick"]}, {"generation": 3, "level": 11, "abilities":["pickup"], "moves":["refresh", "metalclaw", "lick", "return"]}, ], tier: "LC", }, ursaring: { randomBattleMoves: ["swordsdance", "facade", "closecombat", "crunch", "protect"], randomDoubleBattleMoves: ["swordsdance", "facade", "closecombat", "earthquake", "crunch", "protect"], tier: "PU", }, slugma: { randomBattleMoves: ["stockpile", "recover", "lavaplume", "willowisp", "toxic", "hiddenpowergrass", "earthpower", "memento"], tier: "LC", }, magcargo: { randomBattleMoves: ["recover", "lavaplume", "toxic", "hiddenpowergrass", "stealthrock", "fireblast", "earthpower", "shellsmash", "ancientpower"], randomDoubleBattleMoves: ["protect", "heatwave", "willowisp", "shellsmash", "hiddenpowergrass", "ancientpower", "stealthrock", "fireblast", "earthpower"], eventPokemon: [ {"generation": 3, "level": 38, "moves":["refresh", "heatwave", "earthquake", "flamethrower"]}, ], tier: "PU", }, swinub: { randomBattleMoves: ["earthquake", "iciclecrash", "iceshard", "superpower", "endeavor", "stealthrock"], eventPokemon: [ {"generation": 3, "level": 22, "abilities":["oblivious"], "moves":["charm", "ancientpower", "mist", "mudshot"]}, ], tier: "LC", }, piloswine: { randomBattleMoves: ["earthquake", "iciclecrash", "iceshard", "endeavor", "stealthrock"], tier: "NFE", }, mamoswine: { randomBattleMoves: ["iceshard", "earthquake", "endeavor", "iciclecrash", "stealthrock", "superpower", "knockoff"], randomDoubleBattleMoves: ["iceshard", "earthquake", "rockslide", "iciclecrash", "protect", "superpower", "knockoff"], eventPokemon: [ {"generation": 5, "level": 34, "gender": "M", "isHidden": true, "moves":["hail", "icefang", "takedown", "doublehit"]}, {"generation": 6, "level": 50, "shiny": true, "gender": "M", "nature": "Adamant", "isHidden": true, "moves":["iciclespear", "earthquake", "iciclecrash", "rockslide"]}, ], tier: "UU", }, corsola: { randomBattleMoves: ["recover", "toxic", "powergem", "scald", "stealthrock"], randomDoubleBattleMoves: ["protect", "icywind", "powergem", "scald", "stealthrock", "earthpower", "icebeam"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["tackle", "mudsport"]}, ], tier: "PU", }, remoraid: { randomBattleMoves: ["waterspout", "hydropump", "fireblast", "hiddenpowerground", "icebeam", "seedbomb", "rockblast"], tier: "LC", }, octillery: { randomBattleMoves: ["hydropump", "fireblast", "icebeam", "energyball", "rockblast", "gunkshot", "scald"], randomDoubleBattleMoves: ["hydropump", "surf", "fireblast", "icebeam", "energyball", "chargebeam", "protect"], eventPokemon: [ {"generation": 4, "level": 50, "gender": "F", "nature": "Serious", "abilities":["suctioncups"], "moves":["octazooka", "icebeam", "signalbeam", "hyperbeam"], "pokeball": "cherishball"}, ], tier: "PU", }, delibird: { randomBattleMoves: ["rapidspin", "iceshard", "icepunch", "aerialace", "spikes", "destinybond"], randomDoubleBattleMoves: ["fakeout", "iceshard", "icepunch", "aerialace", "brickbreak", "protect"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["present"]}, {"generation": 6, "level": 10, "isHidden": false, "abilities":["vitalspirit"], "moves":["present", "happyhour"], "pokeball": "cherishball"}, ], tier: "PU", }, mantyke: { randomBattleMoves: ["raindance", "hydropump", "scald", "airslash", "icebeam", "rest", "sleeptalk", "toxic"], tier: "LC", }, mantine: { randomBattleMoves: ["scald", "airslash", "roost", "toxic", "defog"], randomDoubleBattleMoves: ["raindance", "scald", "airslash", "icebeam", "tailwind", "wideguard", "helpinghand", "protect", "surf"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "bubble", "supersonic"]}, ], tier: "UU", }, skarmory: { randomBattleMoves: ["whirlwind", "bravebird", "roost", "spikes", "stealthrock", "defog"], randomDoubleBattleMoves: ["skydrop", "bravebird", "tailwind", "taunt", "feint", "protect", "ironhead"], tier: "OU", }, houndour: { randomBattleMoves: ["pursuit", "suckerpunch", "fireblast", "darkpulse", "hiddenpowerfighting", "nastyplot"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["leer", "ember", "howl"]}, {"generation": 3, "level": 17, "moves":["charm", "feintattack", "ember", "roar"]}, ], tier: "LC", }, houndoom: { randomBattleMoves: ["nastyplot", "darkpulse", "suckerpunch", "fireblast", "hiddenpowergrass"], randomDoubleBattleMoves: ["nastyplot", "darkpulse", "suckerpunch", "heatwave", "hiddenpowerfighting", "protect"], eventPokemon: [ {"generation": 6, "level": 50, "nature": "Timid", "isHidden": false, "abilities":["flashfire"], "moves":["flamethrower", "darkpulse", "solarbeam", "sludgebomb"], "pokeball": "cherishball"}, ], tier: "NU", }, houndoommega: { randomBattleMoves: ["nastyplot", "darkpulse", "taunt", "fireblast", "hiddenpowergrass"], randomDoubleBattleMoves: ["nastyplot", "darkpulse", "taunt", "heatwave", "hiddenpowergrass", "protect"], requiredItem: "Houndoominite", tier: "BL", }, phanpy: { randomBattleMoves: ["stealthrock", "earthquake", "iceshard", "headsmash", "knockoff", "seedbomb", "superpower", "playrough"], tier: "LC", }, donphan: { randomBattleMoves: ["stealthrock", "rapidspin", "iceshard", "earthquake", "knockoff", "stoneedge"], randomDoubleBattleMoves: ["stealthrock", "knockoff", "iceshard", "earthquake", "rockslide", "protect"], tier: "RU", }, stantler: { randomBattleMoves: ["doubleedge", "megahorn", "jumpkick", "earthquake", "suckerpunch"], randomDoubleBattleMoves: ["return", "megahorn", "jumpkick", "earthquake", "suckerpunch", "protect"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "abilities":["intimidate"], "moves":["tackle", "leer"]}, ], tier: "PU", }, smeargle: { randomBattleMoves: ["spore", "spikes", "stealthrock", "destinybond", "whirlwind", "stickyweb"], randomDoubleBattleMoves: ["spore", "fakeout", "wideguard", "helpinghand", "followme", "tailwind", "kingsshield", "transform"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "abilities":["owntempo"], "moves":["sketch"]}, {"generation": 5, "level": 50, "gender": "F", "nature": "Jolly", "ivs": {"atk": 31, "spe": 31}, "isHidden": false, "abilities":["technician"], "moves":["falseswipe", "spore", "odorsleuth", "meanlook"], "pokeball": "cherishball"}, ], tier: "UU", }, pokestarsmeargle: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 60, "gender": "M", "abilities":["owntempo"], "moves":["mindreader", "guillotine", "tailwhip", "gastroacid"]}, {"generation": 5, "level": 30, "gender": "M", "abilities":["owntempo"], "moves":["outrage", "magiccoat"]}, {"generation": 5, "level": 99, "gender": "M", "abilities":["owntempo"], "moves":["nastyplot", "sheercold", "attract", "shadowball"]}, ], gen: 5, tier: "Illegal", }, miltank: { randomBattleMoves: ["milkdrink", "stealthrock", "bodyslam", "healbell", "curse", "earthquake", "toxic"], randomDoubleBattleMoves: ["protect", "helpinghand", "bodyslam", "milkdrink", "curse", "earthquake", "thunderwave"], eventPokemon: [ {"generation": 6, "level": 20, "perfectIVs": 3, "isHidden": false, "abilities":["scrappy"], "moves":["rollout", "attract", "stomp", "milkdrink"], "pokeball": "cherishball"}, ], tier: "PU", }, raikou: { randomBattleMoves: ["thunderbolt", "hiddenpowerice", "aurasphere", "calmmind", "substitute", "voltswitch", "extrasensory"], randomDoubleBattleMoves: ["thunderbolt", "hiddenpowerice", "extrasensory", "calmmind", "substitute", "snarl", "protect"], eventPokemon: [ {"generation": 3, "level": 50, "shiny": 1, "moves":["thundershock", "roar", "quickattack", "spark"]}, {"generation": 3, "level": 70, "moves":["quickattack", "spark", "reflect", "crunch"]}, {"generation": 4, "level": 40, "shiny": 1, "moves":["roar", "quickattack", "spark", "reflect"]}, {"generation": 4, "level": 30, "shiny": true, "nature": "Rash", "moves":["zapcannon", "aurasphere", "extremespeed", "weatherball"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "shiny": 1, "moves":["spark", "reflect", "crunch", "thunderfang"]}, ], eventOnly: true, unreleasedHidden: true, tier: "UU", }, entei: { randomBattleMoves: ["extremespeed", "flareblitz", "bulldoze", "stoneedge", "sacredfire"], randomDoubleBattleMoves: ["extremespeed", "flareblitz", "ironhead", "bulldoze", "stoneedge", "sacredfire", "protect"], eventPokemon: [ {"generation": 3, "level": 50, "shiny": 1, "moves":["ember", "roar", "firespin", "stomp"]}, {"generation": 3, "level": 70, "moves":["firespin", "stomp", "flamethrower", "swagger"]}, {"generation": 4, "level": 40, "shiny": 1, "moves":["roar", "firespin", "stomp", "flamethrower"]}, {"generation": 4, "level": 30, "shiny": true, "nature": "Adamant", "moves":["flareblitz", "howl", "extremespeed", "crushclaw"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "shiny": 1, "moves":["stomp", "flamethrower", "swagger", "firefang"]}, ], eventOnly: true, unreleasedHidden: true, tier: "UU", }, suicune: { randomBattleMoves: ["hydropump", "icebeam", "scald", "hiddenpowergrass", "rest", "sleeptalk", "calmmind"], randomDoubleBattleMoves: ["hydropump", "icebeam", "scald", "hiddenpowergrass", "snarl", "tailwind", "protect", "calmmind"], eventPokemon: [ {"generation": 3, "level": 50, "shiny": 1, "moves":["bubblebeam", "raindance", "gust", "aurorabeam"]}, {"generation": 3, "level": 70, "moves":["gust", "aurorabeam", "mist", "mirrorcoat"]}, {"generation": 4, "level": 40, "shiny": 1, "moves":["raindance", "gust", "aurorabeam", "mist"]}, {"generation": 4, "level": 30, "shiny": true, "nature": "Relaxed", "moves":["sheercold", "airslash", "extremespeed", "aquaring"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "shiny": 1, "moves":["aurorabeam", "mist", "mirrorcoat", "icefang"]}, ], eventOnly: true, unreleasedHidden: true, tier: "UU", }, larvitar: { randomBattleMoves: ["earthquake", "stoneedge", "facade", "dragondance", "superpower", "crunch"], eventPokemon: [ {"generation": 3, "level": 20, "moves":["sandstorm", "dragondance", "bite", "outrage"]}, {"generation": 5, "level": 5, "shiny": true, "gender": "M", "isHidden": false, "moves":["bite", "leer", "sandstorm", "superpower"], "pokeball": "cherishball"}, ], tier: "LC", }, pupitar: { randomBattleMoves: ["earthquake", "stoneedge", "crunch", "dragondance", "superpower", "stealthrock"], tier: "NFE", }, tyranitar: { randomBattleMoves: ["crunch", "stoneedge", "pursuit", "earthquake", "fireblast", "icebeam", "stealthrock"], randomDoubleBattleMoves: ["crunch", "stoneedge", "rockslide", "earthquake", "firepunch", "icepunch", "stealthrock", "protect"], eventPokemon: [ {"generation": 3, "level": 70, "moves":["thrash", "scaryface", "crunch", "earthquake"]}, {"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["fireblast", "icebeam", "stoneedge", "crunch"], "pokeball": "cherishball"}, {"generation": 5, "level": 55, "gender": "M", "isHidden": true, "moves":["payback", "crunch", "earthquake", "seismictoss"]}, {"generation": 6, "level": 50, "isHidden": false, "moves":["stoneedge", "crunch", "earthquake", "icepunch"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "nature": "Jolly", "isHidden": false, "moves":["rockslide", "earthquake", "crunch", "stoneedge"], "pokeball": "cherishball"}, {"generation": 6, "level": 55, "shiny": true, "nature": "Adamant", "ivs": {"hp": 31, "atk": 31, "def": 31, "spa": 14, "spd": 31, "spe": 0}, "isHidden": false, "moves":["crunch", "rockslide", "lowkick", "protect"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "isHidden": false, "moves":["rockslide", "crunch", "icepunch", "lowkick"], "pokeball": "cherishball"}, ], tier: "OU", }, tyranitarmega: { randomBattleMoves: ["crunch", "stoneedge", "earthquake", "icepunch", "dragondance"], randomDoubleBattleMoves: ["crunch", "stoneedge", "earthquake", "icepunch", "dragondance", "rockslide", "protect"], requiredItem: "Tyranitarite", tier: "OU", }, lugia: { randomBattleMoves: ["toxic", "roost", "substitute", "whirlwind", "thunderwave", "dragontail", "aeroblast"], randomDoubleBattleMoves: ["aeroblast", "roost", "substitute", "tailwind", "icebeam", "psychic", "calmmind", "skydrop", "protect"], eventPokemon: [ {"generation": 3, "level": 70, "shiny": 1, "moves":["recover", "hydropump", "raindance", "swift"]}, {"generation": 3, "level": 50, "moves":["psychoboost", "earthquake", "hydropump", "featherdance"]}, {"generation": 4, "level": 45, "shiny": 1, "moves":["extrasensory", "raindance", "hydropump", "aeroblast"]}, {"generation": 4, "level": 70, "shiny": 1, "moves":["aeroblast", "punishment", "ancientpower", "safeguard"]}, {"generation": 5, "level": 5, "isHidden": true, "moves":["whirlwind", "weatherball"], "pokeball": "dreamball"}, {"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["raindance", "hydropump", "aeroblast", "punishment"]}, {"generation": 6, "level": 50, "nature": "Timid", "isHidden": false, "moves":["aeroblast", "hydropump", "dragonrush", "icebeam"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "Uber", }, hooh: { randomBattleMoves: ["substitute", "sacredfire", "bravebird", "earthquake", "roost", "toxic", "flamecharge"], randomDoubleBattleMoves: ["substitute", "sacredfire", "bravebird", "earthquake", "roost", "toxic", "tailwind", "skydrop", "protect"], eventPokemon: [ {"generation": 3, "level": 70, "shiny": 1, "moves":["recover", "fireblast", "sunnyday", "swift"]}, {"generation": 4, "level": 45, "shiny": 1, "moves":["extrasensory", "sunnyday", "fireblast", "sacredfire"]}, {"generation": 4, "level": 70, "shiny": 1, "moves":["sacredfire", "punishment", "ancientpower", "safeguard"]}, {"generation": 5, "level": 5, "isHidden": true, "moves":["whirlwind", "weatherball"], "pokeball": "dreamball"}, {"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["sunnyday", "fireblast", "sacredfire", "punishment"]}, {"generation": 6, "level": 50, "shiny": true, "isHidden": false, "moves":["sacredfire", "bravebird", "recover", "celebrate"], "pokeball": "cherishball"}, {"generation": 7, "level": 100, "isHidden": false, "moves":["sacredfire", "bravebird", "recover", "safeguard"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "Uber", }, celebi: { randomBattleMoves: ["nastyplot", "psychic", "gigadrain", "recover", "healbell", "batonpass", "earthpower", "hiddenpowerfire", "leafstorm", "uturn", "thunderwave"], randomDoubleBattleMoves: ["protect", "psychic", "gigadrain", "leechseed", "recover", "earthpower", "hiddenpowerfire", "nastyplot", "leafstorm", "uturn", "thunderwave"], eventPokemon: [ {"generation": 3, "level": 10, "moves":["confusion", "recover", "healbell", "safeguard"]}, {"generation": 3, "level": 70, "moves":["ancientpower", "futuresight", "batonpass", "perishsong"]}, {"generation": 3, "level": 10, "moves":["leechseed", "recover", "healbell", "safeguard"]}, {"generation": 3, "level": 30, "moves":["healbell", "safeguard", "ancientpower", "futuresight"]}, {"generation": 4, "level": 50, "moves":["leafstorm", "recover", "nastyplot", "healingwish"], "pokeball": "cherishball"}, {"generation": 6, "level": 10, "moves":["recover", "healbell", "safeguard", "holdback"], "pokeball": "luxuryball"}, {"generation": 6, "level": 100, "moves":["confusion", "recover", "healbell", "safeguard"], "pokeball": "cherishball"}, {"generation": 7, "level": 30, "moves":["healbell", "safeguard", "ancientpower", "futuresight"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "UU", }, treecko: { randomBattleMoves: ["substitute", "leechseed", "leafstorm", "hiddenpowerice", "hiddenpowerrock", "endeavor"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["pound", "leer", "absorb"]}, {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["pound", "leer", "absorb"]}, ], tier: "LC", }, grovyle: { randomBattleMoves: ["substitute", "leechseed", "gigadrain", "leafstorm", "hiddenpowerice", "hiddenpowerrock", "endeavor"], tier: "NFE", }, sceptile: { randomBattleMoves: ["gigadrain", "leafstorm", "hiddenpowerice", "focusblast", "hiddenpowerflying"], randomDoubleBattleMoves: ["gigadrain", "leafstorm", "hiddenpowerice", "focusblast", "hiddenpowerfire", "protect"], eventPokemon: [ {"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "moves":["leafstorm", "dragonpulse", "focusblast", "rockslide"], "pokeball": "cherishball"}, ], tier: "NU", }, sceptilemega: { randomBattleMoves: ["substitute", "gigadrain", "dragonpulse", "focusblast", "swordsdance", "outrage", "leafblade", "earthquake", "hiddenpowerfire"], randomDoubleBattleMoves: ["substitute", "gigadrain", "leafstorm", "hiddenpowerice", "focusblast", "dragonpulse", "hiddenpowerfire", "protect"], requiredItem: "Sceptilite", tier: "UU", }, torchic: { randomBattleMoves: ["protect", "batonpass", "substitute", "hiddenpowergrass", "swordsdance", "firepledge"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "growl", "focusenergy", "ember"]}, {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["scratch", "growl", "focusenergy", "ember"]}, {"generation": 6, "level": 10, "gender": "M", "isHidden": true, "moves":["scratch", "growl", "focusenergy", "ember"], "pokeball": "cherishball"}, ], tier: "LC", }, combusken: { randomBattleMoves: ["flareblitz", "skyuppercut", "protect", "swordsdance", "substitute", "batonpass", "shadowclaw"], tier: "NFE", }, blaziken: { randomBattleMoves: ["flareblitz", "highjumpkick", "protect", "swordsdance", "substitute", "batonpass", "stoneedge", "knockoff"], eventPokemon: [ {"generation": 3, "level": 70, "moves":["blazekick", "slash", "mirrormove", "skyuppercut"]}, {"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "moves":["flareblitz", "highjumpkick", "thunderpunch", "stoneedge"], "pokeball": "cherishball"}, ], tier: "Uber", }, blazikenmega: { randomBattleMoves: ["flareblitz", "highjumpkick", "protect", "swordsdance", "substitute", "batonpass", "stoneedge", "knockoff"], requiredItem: "Blazikenite", tier: "Uber", }, mudkip: { randomBattleMoves: ["hydropump", "earthpower", "hiddenpowerelectric", "icebeam", "sludgewave"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "growl", "mudslap", "watergun"]}, {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tackle", "growl", "mudslap", "watergun"]}, ], tier: "LC", }, marshtomp: { randomBattleMoves: ["waterfall", "earthquake", "superpower", "icepunch", "rockslide", "stealthrock"], tier: "NFE", }, swampert: { randomBattleMoves: ["stealthrock", "earthquake", "scald", "icebeam", "roar", "toxic", "protect"], randomDoubleBattleMoves: ["waterfall", "earthquake", "icebeam", "stealthrock", "wideguard", "scald", "rockslide", "muddywater", "protect", "icywind"], eventPokemon: [ {"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "moves":["earthquake", "icebeam", "hydropump", "hammerarm"], "pokeball": "cherishball"}, ], tier: "UU", }, swampertmega: { randomBattleMoves: ["raindance", "waterfall", "earthquake", "icepunch", "superpower"], randomDoubleBattleMoves: ["waterfall", "earthquake", "raindance", "icepunch", "superpower", "protect"], requiredItem: "Swampertite", tier: "OU", }, poochyena: { randomBattleMoves: ["superfang", "foulplay", "suckerpunch", "toxic", "crunch", "firefang", "icefang", "poisonfang"], eventPokemon: [ {"generation": 3, "level": 10, "abilities":["runaway"], "moves":["healbell", "dig", "poisonfang", "howl"]}, ], tier: "LC", }, mightyena: { randomBattleMoves: ["crunch", "suckerpunch", "playrough", "firefang", "irontail"], randomDoubleBattleMoves: ["suckerpunch", "crunch", "playrough", "firefang", "taunt", "protect"], tier: "PU", }, zigzagoon: { randomBattleMoves: ["trick", "thunderwave", "icebeam", "thunderbolt", "gunkshot", "lastresort"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": true, "abilities":["pickup"], "moves":["tackle", "growl", "tailwhip"]}, {"generation": 3, "level": 5, "shiny": 1, "abilities":["pickup"], "moves":["tackle", "growl", "tailwhip", "extremespeed"]}, ], tier: "LC", }, linoone: { randomBattleMoves: ["bellydrum", "extremespeed", "seedbomb", "shadowclaw"], randomDoubleBattleMoves: ["bellydrum", "extremespeed", "seedbomb", "protect", "shadowclaw"], eventPokemon: [ {"generation": 6, "level": 50, "isHidden": false, "moves":["extremespeed", "helpinghand", "babydolleyes", "protect"], "pokeball": "cherishball"}, ], tier: "RU", }, wurmple: { randomBattleMoves: ["bugbite", "poisonsting", "tackle", "electroweb"], tier: "LC", }, silcoon: { randomBattleMoves: ["bugbite", "poisonsting", "tackle", "electroweb"], tier: "NFE", }, beautifly: { randomBattleMoves: ["quiverdance", "bugbuzz", "aircutter", "psychic", "gigadrain", "hiddenpowerrock"], randomDoubleBattleMoves: ["quiverdance", "bugbuzz", "gigadrain", "hiddenpowerrock", "aircutter", "tailwind", "stringshot", "protect"], tier: "PU", }, cascoon: { randomBattleMoves: ["bugbite", "poisonsting", "tackle", "electroweb"], tier: "NFE", }, dustox: { randomBattleMoves: ["roost", "defog", "bugbuzz", "sludgebomb", "quiverdance", "uturn", "shadowball"], randomDoubleBattleMoves: ["tailwind", "stringshot", "strugglebug", "bugbuzz", "protect", "sludgebomb", "quiverdance", "shadowball"], tier: "PU", }, lotad: { randomBattleMoves: ["gigadrain", "icebeam", "scald", "naturepower", "raindance"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["astonish", "growl", "absorb"]}, ], tier: "LC", }, lombre: { randomBattleMoves: ["fakeout", "swordsdance", "waterfall", "seedbomb", "icepunch", "firepunch", "thunderpunch", "poweruppunch", "gigadrain", "icebeam"], tier: "NFE", }, ludicolo: { randomBattleMoves: ["raindance", "hydropump", "scald", "gigadrain", "icebeam", "focusblast"], randomDoubleBattleMoves: ["raindance", "hydropump", "surf", "gigadrain", "icebeam", "fakeout", "protect"], eventPokemon: [ {"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "abilities":["swiftswim"], "moves":["fakeout", "hydropump", "icebeam", "gigadrain"], "pokeball": "cherishball"}, {"generation": 5, "level": 30, "gender": "M", "nature": "Calm", "isHidden": false, "abilities":["swiftswim"], "moves":["scald", "gigadrain", "icebeam", "sunnyday"]}, ], tier: "PU", }, seedot: { randomBattleMoves: ["defog", "naturepower", "seedbomb", "explosion", "foulplay"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["bide", "harden", "growth"]}, {"generation": 3, "level": 17, "moves":["refresh", "gigadrain", "bulletseed", "secretpower"]}, ], tier: "LC", }, nuzleaf: { randomBattleMoves: ["naturepower", "seedbomb", "explosion", "swordsdance", "rockslide", "lowsweep"], tier: "NFE", }, shiftry: { randomBattleMoves: ["leafstorm", "swordsdance", "leafblade", "suckerpunch", "defog", "lowkick", "knockoff"], randomDoubleBattleMoves: ["leafstorm", "swordsdance", "leafblade", "suckerpunch", "knockoff", "lowkick", "fakeout", "protect"], tier: "PU", }, taillow: { randomBattleMoves: ["bravebird", "facade", "quickattack", "uturn", "protect"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["peck", "growl", "focusenergy", "featherdance"]}, ], tier: "LC", }, swellow: { randomBattleMoves: ["protect", "facade", "bravebird", "uturn", "quickattack"], randomDoubleBattleMoves: ["bravebird", "facade", "quickattack", "uturn", "protect"], eventPokemon: [ {"generation": 3, "level": 43, "moves":["batonpass", "skyattack", "agility", "facade"]}, ], tier: "RU", }, wingull: { randomBattleMoves: ["scald", "icebeam", "tailwind", "uturn", "airslash", "knockoff", "defog"], tier: "LC", }, pelipper: { randomBattleMoves: ["scald", "uturn", "hurricane", "toxic", "roost", "defog", "knockoff"], randomDoubleBattleMoves: ["scald", "surf", "hurricane", "wideguard", "protect", "tailwind", "knockoff"], tier: "OU", }, ralts: { randomBattleMoves: ["trickroom", "destinybond", "psychic", "willowisp", "hypnosis", "dazzlinggleam", "substitute", "trick"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["growl", "wish"]}, {"generation": 3, "level": 5, "shiny": 1, "moves":["growl", "charm"]}, {"generation": 3, "level": 20, "moves":["sing", "shockwave", "reflect", "confusion"]}, {"generation": 6, "level": 1, "isHidden": true, "moves":["growl", "encore"]}, ], tier: "LC", }, kirlia: { randomBattleMoves: ["trick", "dazzlinggleam", "psychic", "willowisp", "signalbeam", "thunderbolt", "destinybond", "substitute"], tier: "NFE", }, gardevoir: { randomBattleMoves: ["psychic", "thunderbolt", "focusblast", "shadowball", "moonblast", "calmmind", "substitute", "willowisp"], randomDoubleBattleMoves: ["psyshock", "focusblast", "shadowball", "moonblast", "taunt", "willowisp", "thunderbolt", "trickroom", "helpinghand", "protect", "dazzlinggleam"], eventPokemon: [ {"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "abilities":["trace"], "moves":["hypnosis", "thunderbolt", "focusblast", "psychic"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "shiny": true, "gender": "F", "isHidden": false, "abilities":["synchronize"], "moves":["dazzlinggleam", "moonblast", "storedpower", "calmmind"], "pokeball": "cherishball"}, ], tier: "RU", }, gardevoirmega: { randomBattleMoves: ["calmmind", "hypervoice", "psyshock", "focusblast", "substitute", "taunt", "willowisp"], randomDoubleBattleMoves: ["psyshock", "focusblast", "shadowball", "calmmind", "thunderbolt", "hypervoice", "protect"], requiredItem: "Gardevoirite", tier: "UU", }, gallade: { randomBattleMoves: ["bulkup", "drainpunch", "icepunch", "shadowsneak", "closecombat", "zenheadbutt", "knockoff", "trick"], randomDoubleBattleMoves: ["closecombat", "trick", "stoneedge", "shadowsneak", "drainpunch", "icepunch", "zenheadbutt", "knockoff", "trickroom", "protect", "helpinghand"], tier: "BL4", }, gallademega: { randomBattleMoves: ["swordsdance", "closecombat", "drainpunch", "knockoff", "zenheadbutt", "substitute"], randomDoubleBattleMoves: ["closecombat", "stoneedge", "drainpunch", "icepunch", "zenheadbutt", "swordsdance", "knockoff", "protect"], requiredItem: "Galladite", tier: "BL", }, surskit: { randomBattleMoves: ["hydropump", "signalbeam", "hiddenpowerfire", "stickyweb", "gigadrain", "powersplit"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["bubble", "mudsport"]}, {"generation": 3, "level": 10, "gender": "M", "moves":["bubble", "quickattack"]}, ], tier: "LC", }, masquerain: { randomBattleMoves: ["quiverdance", "bugbuzz", "airslash", "hydropump", "roost", "batonpass", "stickyweb"], randomDoubleBattleMoves: ["hydropump", "bugbuzz", "airslash", "quiverdance", "tailwind", "roost", "strugglebug", "protect"], tier: "PU", }, shroomish: { randomBattleMoves: ["spore", "substitute", "leechseed", "gigadrain", "protect", "toxic", "stunspore"], eventPokemon: [ {"generation": 3, "level": 15, "abilities":["effectspore"], "moves":["refresh", "falseswipe", "megadrain", "stunspore"]}, ], tier: "LC", }, breloom: { randomBattleMoves: ["spore", "machpunch", "bulletseed", "rocktomb", "swordsdance"], randomDoubleBattleMoves: ["spore", "helpinghand", "machpunch", "bulletseed", "rocktomb", "protect", "drainpunch"], tier: "BL", }, slakoth: { randomBattleMoves: ["doubleedge", "hammerarm", "firepunch", "counter", "retaliate", "toxic"], tier: "LC", }, vigoroth: { randomBattleMoves: ["bulkup", "return", "earthquake", "firepunch", "suckerpunch", "slackoff", "icepunch", "lowkick"], tier: "NFE", }, slaking: { randomBattleMoves: ["earthquake", "pursuit", "nightslash", "doubleedge", "retaliate"], randomDoubleBattleMoves: ["earthquake", "nightslash", "doubleedge", "retaliate", "hammerarm", "rockslide"], eventPokemon: [ {"generation": 4, "level": 50, "gender": "M", "nature": "Adamant", "moves":["gigaimpact", "return", "shadowclaw", "aerialace"], "pokeball": "cherishball"}, ], tier: "PU", }, nincada: { randomBattleMoves: ["xscissor", "dig", "aerialace", "nightslash"], tier: "LC", }, ninjask: { randomBattleMoves: ["batonpass", "swordsdance", "substitute", "protect", "leechlife"], randomDoubleBattleMoves: ["batonpass", "swordsdance", "substitute", "protect", "leechlife", "aerialace"], tier: "PU", }, shedinja: { randomBattleMoves: ["swordsdance", "willowisp", "xscissor", "shadowsneak", "shadowclaw", "batonpass"], randomDoubleBattleMoves: ["swordsdance", "willowisp", "xscissor", "shadowsneak", "shadowclaw", "protect"], eventPokemon: [ {"generation": 3, "level": 50, "moves":["spite", "confuseray", "shadowball", "grudge"]}, {"generation": 3, "level": 20, "shiny": 1, "moves":["doubleteam", "furycutter", "screech"]}, {"generation": 3, "level": 25, "shiny": 1, "moves":["swordsdance"]}, {"generation": 3, "level": 31, "shiny": 1, "moves":["slash"]}, {"generation": 3, "level": 38, "shiny": 1, "moves":["agility"]}, {"generation": 3, "level": 45, "shiny": 1, "moves":["batonpass"]}, {"generation": 4, "level": 52, "shiny": 1, "moves":["xscissor"]}, ], tier: "PU", }, whismur: { randomBattleMoves: ["hypervoice", "fireblast", "shadowball", "icebeam", "extrasensory"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["pound", "uproar", "teeterdance"]}, ], tier: "LC", }, loudred: { randomBattleMoves: ["hypervoice", "fireblast", "shadowball", "icebeam", "circlethrow", "bodyslam"], tier: "NFE", }, exploud: { randomBattleMoves: ["boomburst", "fireblast", "icebeam", "surf", "focusblast"], randomDoubleBattleMoves: ["boomburst", "fireblast", "icebeam", "surf", "focusblast", "protect", "hypervoice"], eventPokemon: [ {"generation": 3, "level": 100, "moves":["roar", "rest", "sleeptalk", "hypervoice"]}, {"generation": 3, "level": 50, "moves":["stomp", "screech", "hyperbeam", "roar"]}, ], tier: "BL3", }, makuhita: { randomBattleMoves: ["crosschop", "bulletpunch", "closecombat", "icepunch", "bulkup", "fakeout", "earthquake"], eventPokemon: [ {"generation": 3, "level": 18, "moves":["refresh", "brickbreak", "armthrust", "rocktomb"]}, ], tier: "LC", }, hariyama: { randomBattleMoves: ["bulletpunch", "closecombat", "icepunch", "stoneedge", "bulkup", "knockoff"], randomDoubleBattleMoves: ["bulletpunch", "closecombat", "icepunch", "stoneedge", "fakeout", "knockoff", "helpinghand", "wideguard", "protect"], tier: "BL4", }, nosepass: { randomBattleMoves: ["powergem", "thunderwave", "stealthrock", "painsplit", "explosion", "voltswitch"], eventPokemon: [ {"generation": 3, "level": 26, "moves":["helpinghand", "thunderbolt", "thunderwave", "rockslide"]}, ], tier: "LC", }, probopass: { randomBattleMoves: ["stealthrock", "thunderwave", "toxic", "flashcannon", "powergem", "voltswitch", "painsplit"], randomDoubleBattleMoves: ["stealthrock", "thunderwave", "helpinghand", "earthpower", "powergem", "wideguard", "protect", "flashcannon"], tier: "PU", }, skitty: { randomBattleMoves: ["doubleedge", "zenheadbutt", "thunderwave", "fakeout", "playrough", "healbell"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "abilities":["cutecharm"], "moves":["tackle", "growl", "tailwhip", "payday"]}, {"generation": 3, "level": 5, "shiny": 1, "abilities":["cutecharm"], "moves":["growl", "tackle", "tailwhip", "rollout"]}, {"generation": 3, "level": 10, "gender": "M", "abilities":["cutecharm"], "moves":["growl", "tackle", "tailwhip", "attract"]}, ], tier: "LC", }, delcatty: { randomBattleMoves: ["doubleedge", "suckerpunch", "wildcharge", "fakeout", "thunderwave", "healbell"], randomDoubleBattleMoves: ["doubleedge", "suckerpunch", "playrough", "wildcharge", "fakeout", "thunderwave", "protect", "helpinghand"], eventPokemon: [ {"generation": 3, "level": 18, "abilities":["cutecharm"], "moves":["sweetkiss", "secretpower", "attract", "shockwave"]}, ], tier: "PU", }, sableye: { randomBattleMoves: ["recover", "willowisp", "taunt", "toxic", "knockoff", "foulplay"], randomDoubleBattleMoves: ["recover", "willowisp", "taunt", "fakeout", "knockoff", "foulplay", "helpinghand", "snarl", "protect"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "abilities":["keeneye"], "moves":["leer", "scratch", "foresight", "nightshade"]}, {"generation": 3, "level": 33, "abilities":["keeneye"], "moves":["helpinghand", "shadowball", "feintattack", "recover"]}, {"generation": 5, "level": 50, "gender": "M", "isHidden": true, "moves":["foulplay", "octazooka", "tickle", "trick"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "nature": "Relaxed", "ivs": {"hp": 31, "spa": 31}, "isHidden": true, "moves":["calmmind", "willowisp", "recover", "shadowball"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "nature": "Bold", "isHidden": true, "moves":["willowisp", "recover", "taunt", "shockwave"], "pokeball": "cherishball"}, ], tier: "PU", }, sableyemega: { randomBattleMoves: ["recover", "willowisp", "darkpulse", "calmmind", "shadowball"], randomDoubleBattleMoves: ["fakeout", "knockoff", "darkpulse", "shadowball", "willowisp", "protect"], requiredItem: "Sablenite", tier: "OU", }, mawile: { randomBattleMoves: ["swordsdance", "ironhead", "substitute", "playrough", "suckerpunch", "batonpass"], randomDoubleBattleMoves: ["swordsdance", "ironhead", "firefang", "substitute", "playrough", "suckerpunch", "knockoff", "protect"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["astonish", "faketears"]}, {"generation": 3, "level": 22, "moves":["sing", "falseswipe", "vicegrip", "irondefense"]}, {"generation": 6, "level": 50, "isHidden": false, "abilities":["intimidate"], "moves":["ironhead", "playrough", "firefang", "suckerpunch"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "isHidden": false, "abilities":["intimidate"], "moves":["suckerpunch", "protect", "playrough", "ironhead"], "pokeball": "cherishball"}, ], tier: "PU", }, mawilemega: { randomBattleMoves: ["swordsdance", "ironhead", "firefang", "substitute", "playrough", "suckerpunch", "knockoff", "focuspunch"], randomDoubleBattleMoves: ["swordsdance", "ironhead", "firefang", "substitute", "playrough", "suckerpunch", "knockoff", "protect"], requiredItem: "Mawilite", tier: "OU", }, aron: { randomBattleMoves: ["headsmash", "ironhead", "earthquake", "superpower", "stealthrock", "endeavor"], tier: "LC", }, lairon: { randomBattleMoves: ["headsmash", "ironhead", "earthquake", "superpower", "stealthrock"], tier: "NFE", }, aggron: { randomBattleMoves: ["autotomize", "headsmash", "earthquake", "lowkick", "heavyslam", "aquatail", "stealthrock"], randomDoubleBattleMoves: ["rockslide", "headsmash", "earthquake", "lowkick", "heavyslam", "aquatail", "stealthrock", "protect"], eventPokemon: [ {"generation": 3, "level": 100, "moves":["irontail", "protect", "metalsound", "doubleedge"]}, {"generation": 3, "level": 50, "moves":["takedown", "irontail", "protect", "metalsound"]}, {"generation": 6, "level": 50, "nature": "Brave", "isHidden": false, "abilities":["rockhead"], "moves":["ironhead", "earthquake", "headsmash", "rockslide"], "pokeball": "cherishball"}, ], tier: "PU", }, aggronmega: { randomBattleMoves: ["earthquake", "heavyslam", "icepunch", "stealthrock", "thunderwave", "roar", "toxic"], randomDoubleBattleMoves: ["rockslide", "earthquake", "lowkick", "heavyslam", "aquatail", "protect"], requiredItem: "Aggronite", tier: "UU", }, meditite: { randomBattleMoves: ["highjumpkick", "psychocut", "icepunch", "thunderpunch", "trick", "fakeout", "bulletpunch", "drainpunch", "zenheadbutt"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["bide", "meditate", "confusion"]}, {"generation": 3, "level": 20, "moves":["dynamicpunch", "confusion", "shadowball", "detect"]}, ], tier: "LC Uber", }, medicham: { randomBattleMoves: ["highjumpkick", "drainpunch", "zenheadbutt", "icepunch", "bulletpunch"], randomDoubleBattleMoves: ["highjumpkick", "drainpunch", "zenheadbutt", "icepunch", "bulletpunch", "protect", "fakeout"], tier: "BL4", }, medichammega: { randomBattleMoves: ["highjumpkick", "drainpunch", "icepunch", "fakeout", "zenheadbutt"], randomDoubleBattleMoves: ["highjumpkick", "drainpunch", "zenheadbutt", "icepunch", "bulletpunch", "protect", "fakeout"], requiredItem: "Medichamite", tier: "OU", }, electrike: { randomBattleMoves: ["voltswitch", "thunderbolt", "hiddenpowerice", "switcheroo", "flamethrower", "hiddenpowergrass"], tier: "LC", }, manectric: { randomBattleMoves: ["voltswitch", "thunderbolt", "hiddenpowerice", "hiddenpowergrass", "overheat", "flamethrower"], randomDoubleBattleMoves: ["voltswitch", "thunderbolt", "hiddenpowerice", "hiddenpowergrass", "overheat", "flamethrower", "snarl", "protect"], eventPokemon: [ {"generation": 3, "level": 44, "moves":["refresh", "thunder", "raindance", "bite"]}, {"generation": 6, "level": 50, "nature": "Timid", "isHidden": false, "abilities":["lightningrod"], "moves":["overheat", "thunderbolt", "voltswitch", "protect"], "pokeball": "cherishball"}, ], tier: "PU", }, manectricmega: { randomBattleMoves: ["voltswitch", "thunderbolt", "hiddenpowerice", "hiddenpowergrass", "overheat"], randomDoubleBattleMoves: ["voltswitch", "thunderbolt", "hiddenpowerice", "hiddenpowergrass", "overheat", "flamethrower", "snarl", "protect"], requiredItem: "Manectite", tier: "UU", }, plusle: { randomBattleMoves: ["nastyplot", "thunderbolt", "substitute", "batonpass", "hiddenpowerice", "encore"], randomDoubleBattleMoves: ["nastyplot", "thunderbolt", "substitute", "protect", "hiddenpowerice", "encore", "helpinghand"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["growl", "thunderwave", "mudsport"]}, {"generation": 3, "level": 10, "gender": "M", "moves":["growl", "thunderwave", "quickattack"]}, ], tier: "PU", }, minun: { randomBattleMoves: ["nastyplot", "thunderbolt", "substitute", "batonpass", "hiddenpowerice", "encore"], randomDoubleBattleMoves: ["nastyplot", "thunderbolt", "substitute", "protect", "hiddenpowerice", "encore", "helpinghand"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["growl", "thunderwave", "watersport"]}, {"generation": 3, "level": 10, "gender": "M", "moves":["growl", "thunderwave", "quickattack"]}, ], tier: "PU", }, volbeat: { randomBattleMoves: ["tailglow", "batonpass", "substitute", "bugbuzz", "thunderwave", "encore", "tailwind"], randomDoubleBattleMoves: ["stringshot", "strugglebug", "helpinghand", "bugbuzz", "thunderwave", "encore", "tailwind", "protect"], tier: "PU", }, illumise: { randomBattleMoves: ["substitute", "batonpass", "bugbuzz", "encore", "thunderbolt", "tailwind", "uturn", "thunderwave"], randomDoubleBattleMoves: ["protect", "helpinghand", "bugbuzz", "encore", "thunderbolt", "tailwind", "uturn"], tier: "PU", }, budew: { randomBattleMoves: ["spikes", "sludgebomb", "sleeppowder", "gigadrain", "stunspore", "rest"], tier: "LC", }, roselia: { randomBattleMoves: ["spikes", "toxicspikes", "sleeppowder", "gigadrain", "stunspore", "rest", "sludgebomb", "synthesis"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["absorb", "growth", "poisonsting"]}, {"generation": 3, "level": 22, "moves":["sweetkiss", "magicalleaf", "leechseed", "grasswhistle"]}, ], tier: "NFE", }, roserade: { randomBattleMoves: ["sludgebomb", "gigadrain", "sleeppowder", "leafstorm", "spikes", "toxicspikes", "rest", "synthesis", "hiddenpowerfire"], randomDoubleBattleMoves: ["sludgebomb", "gigadrain", "sleeppowder", "leafstorm", "protect", "hiddenpowerfire"], tier: "RU", }, gulpin: { randomBattleMoves: ["stockpile", "sludgebomb", "sludgewave", "icebeam", "toxic", "painsplit", "yawn", "encore"], eventPokemon: [ {"generation": 3, "level": 17, "moves":["sing", "shockwave", "sludge", "toxic"]}, ], tier: "LC", }, swalot: { randomBattleMoves: ["sludgebomb", "icebeam", "toxic", "yawn", "encore", "painsplit", "earthquake"], randomDoubleBattleMoves: ["sludgebomb", "icebeam", "protect", "yawn", "encore", "gunkshot", "earthquake"], tier: "PU", }, carvanha: { randomBattleMoves: ["protect", "hydropump", "icebeam", "waterfall", "crunch", "aquajet", "destinybond"], eventPokemon: [ {"generation": 3, "level": 15, "moves":["refresh", "waterpulse", "bite", "scaryface"]}, {"generation": 6, "level": 1, "isHidden": true, "moves":["leer", "bite", "hydropump"]}, ], tier: "LC", }, sharpedo: { randomBattleMoves: ["protect", "icebeam", "crunch", "earthquake", "waterfall"], randomDoubleBattleMoves: ["protect", "icebeam", "crunch", "earthquake", "waterfall"], eventPokemon: [ {"generation": 6, "level": 50, "nature": "Adamant", "isHidden": true, "moves":["aquajet", "crunch", "icefang", "destinybond"], "pokeball": "cherishball"}, {"generation": 6, "level": 43, "gender": "M", "perfectIVs": 2, "isHidden": false, "moves":["scaryface", "slash", "poisonfang", "crunch"], "pokeball": "cherishball"}, ], tier: "BL2", }, sharpedomega: { randomBattleMoves: ["protect", "crunch", "waterfall", "icefang", "psychicfangs", "destinybond"], randomDoubleBattleMoves: ["protect", "icefang", "crunch", "waterfall", "psychicfangs"], requiredItem: "Sharpedonite", tier: "UU", }, wailmer: { randomBattleMoves: ["waterspout", "surf", "hydropump", "icebeam", "hiddenpowergrass", "hiddenpowerelectric"], tier: "LC", }, wailord: { randomBattleMoves: ["waterspout", "hydropump", "icebeam", "hiddenpowergrass", "hiddenpowerfire"], randomDoubleBattleMoves: ["waterspout", "hydropump", "icebeam", "hiddenpowergrass", "hiddenpowerfire", "protect"], eventPokemon: [ {"generation": 3, "level": 100, "moves":["rest", "waterspout", "amnesia", "hydropump"]}, {"generation": 3, "level": 50, "moves":["waterpulse", "mist", "rest", "waterspout"]}, ], tier: "PU", }, numel: { randomBattleMoves: ["curse", "earthquake", "rockslide", "fireblast", "flamecharge", "rest", "sleeptalk", "stockpile", "hiddenpowerelectric", "earthpower", "lavaplume"], eventPokemon: [ {"generation": 3, "level": 14, "abilities":["oblivious"], "moves":["charm", "takedown", "dig", "ember"]}, {"generation": 6, "level": 1, "isHidden": false, "moves":["growl", "tackle", "ironhead"]}, ], tier: "LC", }, camerupt: { randomBattleMoves: ["rockpolish", "fireblast", "earthpower", "lavaplume", "stealthrock", "hiddenpowergrass", "roar", "stoneedge"], randomDoubleBattleMoves: ["rockpolish", "fireblast", "earthpower", "heatwave", "eruption", "hiddenpowergrass", "protect"], eventPokemon: [ {"generation": 6, "level": 43, "gender": "M", "perfectIVs": 2, "isHidden": false, "abilities":["solidrock"], "moves":["curse", "takedown", "rockslide", "yawn"], "pokeball": "cherishball"}, ], tier: "PU", }, cameruptmega: { randomBattleMoves: ["stealthrock", "fireblast", "earthpower", "ancientpower", "willowisp", "toxic"], randomDoubleBattleMoves: ["fireblast", "earthpower", "heatwave", "eruption", "rockslide", "protect"], requiredItem: "Cameruptite", tier: "RU", }, torkoal: { randomBattleMoves: ["shellsmash", "fireblast", "earthpower", "solarbeam", "stealthrock", "rapidspin", "yawn", "lavaplume"], randomDoubleBattleMoves: ["protect", "heatwave", "earthpower", "willowisp", "shellsmash", "fireblast", "solarbeam"], tier: "RU", }, spoink: { randomBattleMoves: ["psychic", "reflect", "lightscreen", "thunderwave", "trick", "healbell", "calmmind", "hiddenpowerfighting", "shadowball"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "abilities":["owntempo"], "moves":["splash", "uproar"]}, ], tier: "LC", }, grumpig: { randomBattleMoves: ["psychic", "thunderwave", "healbell", "whirlwind", "toxic", "focusblast", "reflect", "lightscreen"], randomDoubleBattleMoves: ["psychic", "psyshock", "thunderwave", "trickroom", "taunt", "protect", "focusblast", "reflect", "lightscreen"], tier: "PU", }, spinda: { randomBattleMoves: ["return", "superpower", "suckerpunch", "trickroom"], randomDoubleBattleMoves: ["doubleedge", "return", "superpower", "suckerpunch", "trickroom", "fakeout", "protect"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["tackle", "uproar", "sing"]}, ], tier: "PU", }, trapinch: { randomBattleMoves: ["earthquake", "rockslide", "crunch", "quickattack", "superpower"], eventPokemon: [ {"generation": 5, "level": 1, "shiny": true, "isHidden": false, "moves":["bite"]}, ], tier: "LC", }, vibrava: { randomBattleMoves: ["substitute", "earthquake", "outrage", "roost", "uturn", "superpower", "defog"], tier: "NFE", }, flygon: { randomBattleMoves: ["earthquake", "outrage", "uturn", "roost", "defog", "firepunch", "dragondance"], randomDoubleBattleMoves: ["earthquake", "protect", "dragonclaw", "uturn", "rockslide", "firepunch", "fireblast", "tailwind", "dragondance"], eventPokemon: [ {"generation": 3, "level": 45, "moves":["sandtomb", "crunch", "dragonbreath", "screech"]}, {"generation": 4, "level": 50, "gender": "M", "nature": "Naive", "moves":["dracometeor", "uturn", "earthquake", "dragonclaw"], "pokeball": "cherishball"}, ], tier: "RU", }, cacnea: { randomBattleMoves: ["swordsdance", "spikes", "suckerpunch", "seedbomb", "drainpunch"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["poisonsting", "leer", "absorb", "encore"]}, ], tier: "LC", }, cacturne: { randomBattleMoves: ["swordsdance", "spikes", "suckerpunch", "seedbomb", "drainpunch", "substitute"], randomDoubleBattleMoves: ["swordsdance", "spikyshield", "suckerpunch", "seedbomb", "drainpunch", "substitute"], eventPokemon: [ {"generation": 3, "level": 45, "moves":["ingrain", "feintattack", "spikes", "needlearm"]}, ], tier: "PU", }, swablu: { randomBattleMoves: ["roost", "toxic", "cottonguard", "pluck", "hypervoice", "return"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["peck", "growl", "falseswipe"]}, {"generation": 5, "level": 1, "shiny": true, "isHidden": false, "moves":["peck", "growl"]}, {"generation": 6, "level": 1, "isHidden": true, "moves":["peck", "growl", "hypervoice"]}, ], tier: "LC", }, altaria: { randomBattleMoves: ["dragondance", "dracometeor", "outrage", "dragonclaw", "earthquake", "roost", "fireblast", "healbell"], randomDoubleBattleMoves: ["dragondance", "dracometeor", "protect", "dragonclaw", "earthquake", "fireblast", "tailwind"], eventPokemon: [ {"generation": 3, "level": 45, "moves":["takedown", "dragonbreath", "dragondance", "refresh"]}, {"generation": 3, "level": 36, "moves":["healbell", "dragonbreath", "solarbeam", "aerialace"]}, {"generation": 5, "level": 35, "gender": "M", "isHidden": true, "moves":["takedown", "naturalgift", "dragonbreath", "falseswipe"]}, {"generation": 6, "level": 100, "nature": "Modest", "isHidden": true, "moves":["hypervoice", "fireblast", "protect", "agility"], "pokeball": "cherishball"}, ], tier: "PU", }, altariamega: { randomBattleMoves: ["dragondance", "return", "hypervoice", "healbell", "earthquake", "roost", "dracometeor", "fireblast"], randomDoubleBattleMoves: ["dragondance", "return", "doubleedge", "dragonclaw", "earthquake", "protect", "fireblast"], requiredItem: "Altarianite", tier: "UU", }, zangoose: { randomBattleMoves: ["swordsdance", "closecombat", "knockoff", "quickattack", "facade"], randomDoubleBattleMoves: ["protect", "closecombat", "knockoff", "quickattack", "facade"], eventPokemon: [ {"generation": 3, "level": 18, "moves":["leer", "quickattack", "swordsdance", "furycutter"]}, {"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "leer", "quickattack", "swordsdance"]}, {"generation": 3, "level": 28, "moves":["refresh", "brickbreak", "counter", "crushclaw"]}, ], tier: "PU", }, seviper: { randomBattleMoves: ["flamethrower", "sludgewave", "gigadrain", "darkpulse", "switcheroo", "coil", "earthquake", "poisonjab", "suckerpunch"], randomDoubleBattleMoves: ["flamethrower", "gigadrain", "earthquake", "suckerpunch", "aquatail", "protect", "glare", "poisonjab", "sludgebomb"], eventPokemon: [ {"generation": 3, "level": 18, "moves":["wrap", "lick", "bite", "poisontail"]}, {"generation": 3, "level": 30, "moves":["poisontail", "screech", "glare", "crunch"]}, {"generation": 3, "level": 10, "gender": "M", "moves":["wrap", "lick", "bite"]}, ], tier: "PU", }, lunatone: { randomBattleMoves: ["psychic", "earthpower", "stealthrock", "rockpolish", "batonpass", "calmmind", "icebeam", "powergem", "moonlight", "toxic"], randomDoubleBattleMoves: ["psychic", "earthpower", "rockpolish", "calmmind", "helpinghand", "icebeam", "powergem", "moonlight", "trickroom", "protect"], eventPokemon: [ {"generation": 3, "level": 10, "moves":["tackle", "harden", "confusion"]}, {"generation": 3, "level": 25, "moves":["batonpass", "psychic", "raindance", "rocktomb"]}, {"generation": 7, "level": 30, "moves":["cosmicpower", "hiddenpower", "moonblast", "powergem"], "pokeball": "cherishball"}, ], tier: "PU", }, solrock: { randomBattleMoves: ["stealthrock", "explosion", "rockslide", "reflect", "lightscreen", "willowisp", "morningsun"], randomDoubleBattleMoves: ["protect", "helpinghand", "stoneedge", "zenheadbutt", "willowisp", "trickroom", "rockslide"], eventPokemon: [ {"generation": 3, "level": 10, "moves":["tackle", "harden", "confusion"]}, {"generation": 3, "level": 41, "moves":["batonpass", "psychic", "sunnyday", "cosmicpower"]}, {"generation": 7, "level": 30, "moves":["cosmicpower", "hiddenpower", "solarbeam", "stoneedge"], "pokeball": "cherishball"}, ], tier: "PU", }, barboach: { randomBattleMoves: ["dragondance", "waterfall", "earthquake", "return", "bounce"], tier: "LC", }, whiscash: { randomBattleMoves: ["dragondance", "waterfall", "earthquake", "stoneedge", "zenheadbutt"], randomDoubleBattleMoves: ["dragondance", "waterfall", "earthquake", "stoneedge", "zenheadbutt", "protect"], eventPokemon: [ {"generation": 4, "level": 51, "gender": "F", "nature": "Gentle", "abilities":["oblivious"], "moves":["earthquake", "aquatail", "zenheadbutt", "gigaimpact"], "pokeball": "cherishball"}, ], tier: "PU", }, corphish: { randomBattleMoves: ["dragondance", "waterfall", "crunch", "superpower", "swordsdance", "knockoff", "aquajet"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["bubble", "watersport"]}, ], tier: "LC", }, crawdaunt: { randomBattleMoves: ["dragondance", "crabhammer", "superpower", "swordsdance", "knockoff", "aquajet"], randomDoubleBattleMoves: ["dragondance", "crabhammer", "crunch", "superpower", "swordsdance", "knockoff", "aquajet", "protect"], eventPokemon: [ {"generation": 3, "level": 100, "moves":["taunt", "crabhammer", "swordsdance", "guillotine"]}, {"generation": 3, "level": 50, "moves":["knockoff", "taunt", "crabhammer", "swordsdance"]}, ], tier: "UU", }, baltoy: { randomBattleMoves: ["stealthrock", "earthquake", "toxic", "psychic", "reflect", "lightscreen", "icebeam", "rapidspin"], eventPokemon: [ {"generation": 3, "level": 17, "moves":["refresh", "rocktomb", "mudslap", "psybeam"]}, ], tier: "LC", }, claydol: { randomBattleMoves: ["stealthrock", "toxic", "psychic", "icebeam", "earthquake", "rapidspin"], randomDoubleBattleMoves: ["earthpower", "trickroom", "psychic", "icebeam", "earthquake", "protect"], tier: "NU", }, lileep: { randomBattleMoves: ["stealthrock", "recover", "ancientpower", "hiddenpowerfire", "gigadrain", "stockpile"], eventPokemon: [ {"generation": 5, "level": 15, "gender": "M", "isHidden": false, "moves":["recover", "rockslide", "constrict", "acid"], "pokeball": "cherishball"}, ], tier: "LC", }, cradily: { randomBattleMoves: ["stealthrock", "recover", "gigadrain", "toxic", "seedbomb", "rockslide", "curse"], randomDoubleBattleMoves: ["protect", "recover", "seedbomb", "rockslide", "earthquake", "curse", "swordsdance"], tier: "PU", }, anorith: { randomBattleMoves: ["stealthrock", "brickbreak", "toxic", "xscissor", "rockslide", "swordsdance", "rockpolish"], eventPokemon: [ {"generation": 5, "level": 15, "gender": "M", "isHidden": false, "moves":["harden", "mudsport", "watergun", "crosspoison"], "pokeball": "cherishball"}, ], tier: "LC", }, armaldo: { randomBattleMoves: ["stealthrock", "stoneedge", "toxic", "xscissor", "knockoff", "rapidspin", "earthquake"], randomDoubleBattleMoves: ["rockslide", "stoneedge", "stringshot", "xscissor", "swordsdance", "knockoff", "protect"], tier: "PU", }, feebas: { randomBattleMoves: ["protect", "confuseray", "hypnosis", "scald", "toxic"], eventPokemon: [ {"generation": 4, "level": 5, "gender": "F", "nature": "Calm", "moves":["splash", "mirrorcoat"], "pokeball": "cherishball"}, ], tier: "LC", }, milotic: { randomBattleMoves: ["recover", "scald", "toxic", "icebeam", "dragontail", "rest", "sleeptalk"], randomDoubleBattleMoves: ["recover", "scald", "hydropump", "icebeam", "dragontail", "hypnosis", "protect", "hiddenpowergrass"], eventPokemon: [ {"generation": 3, "level": 35, "moves":["waterpulse", "twister", "recover", "raindance"]}, {"generation": 4, "level": 50, "gender": "F", "nature": "Bold", "moves":["recover", "raindance", "icebeam", "hydropump"], "pokeball": "cherishball"}, {"generation": 4, "level": 50, "shiny": true, "gender": "M", "nature": "Timid", "moves":["raindance", "recover", "hydropump", "icywind"], "pokeball": "cherishball"}, {"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "moves":["recover", "hydropump", "icebeam", "mirrorcoat"], "pokeball": "cherishball"}, {"generation": 5, "level": 58, "gender": "M", "nature": "Lax", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "moves":["recover", "surf", "icebeam", "toxic"], "pokeball": "cherishball"}, ], tier: "RU", }, castform: { tier: "PU", }, castformsunny: { randomBattleMoves: ["sunnyday", "weatherball", "solarbeam", "icebeam"], battleOnly: true, }, castformrainy: { randomBattleMoves: ["raindance", "weatherball", "thunder", "hurricane"], battleOnly: true, }, castformsnowy: { battleOnly: true, }, kecleon: { randomBattleMoves: ["fakeout", "knockoff", "drainpunch", "suckerpunch", "shadowsneak", "stealthrock", "recover"], randomDoubleBattleMoves: ["knockoff", "fakeout", "trickroom", "recover", "drainpunch", "suckerpunch", "shadowsneak", "protect"], tier: "PU", }, shuppet: { randomBattleMoves: ["trickroom", "destinybond", "taunt", "shadowsneak", "suckerpunch", "willowisp"], eventPokemon: [ {"generation": 3, "level": 45, "abilities":["insomnia"], "moves":["spite", "willowisp", "feintattack", "shadowball"]}, ], tier: "LC", }, banette: { randomBattleMoves: ["destinybond", "taunt", "shadowclaw", "suckerpunch", "willowisp", "shadowsneak", "knockoff"], randomDoubleBattleMoves: ["shadowclaw", "suckerpunch", "willowisp", "shadowsneak", "knockoff", "protect"], eventPokemon: [ {"generation": 3, "level": 37, "abilities":["insomnia"], "moves":["helpinghand", "feintattack", "shadowball", "curse"]}, {"generation": 5, "level": 37, "gender": "F", "isHidden": true, "moves":["feintattack", "hex", "shadowball", "cottonguard"]}, ], tier: "PU", }, banettemega: { randomBattleMoves: ["destinybond", "taunt", "shadowclaw", "suckerpunch", "willowisp", "knockoff"], randomDoubleBattleMoves: ["destinybond", "taunt", "shadowclaw", "suckerpunch", "willowisp", "knockoff", "protect"], requiredItem: "Banettite", tier: "RU", }, duskull: { randomBattleMoves: ["willowisp", "shadowsneak", "painsplit", "substitute", "nightshade", "destinybond", "trickroom"], eventPokemon: [ {"generation": 3, "level": 45, "moves":["pursuit", "curse", "willowisp", "meanlook"]}, {"generation": 3, "level": 19, "moves":["helpinghand", "shadowball", "astonish", "confuseray"]}, ], tier: "LC", }, dusclops: { randomBattleMoves: ["willowisp", "shadowsneak", "icebeam", "painsplit", "substitute", "seismictoss", "toxic", "trickroom"], tier: "NFE", }, dusknoir: { randomBattleMoves: ["willowisp", "shadowsneak", "icepunch", "painsplit", "substitute", "earthquake", "focuspunch"], randomDoubleBattleMoves: ["willowisp", "shadowsneak", "icepunch", "painsplit", "protect", "earthquake", "helpinghand", "trickroom"], tier: "PU", }, tropius: { randomBattleMoves: ["leechseed", "substitute", "airslash", "gigadrain", "toxic", "protect"], randomDoubleBattleMoves: ["leechseed", "protect", "airslash", "gigadrain", "earthquake", "hiddenpowerfire", "tailwind", "sunnyday", "roost"], eventPokemon: [ {"generation": 4, "level": 53, "gender": "F", "nature": "Jolly", "abilities":["chlorophyll"], "moves":["airslash", "synthesis", "sunnyday", "solarbeam"], "pokeball": "cherishball"}, ], tier: "PU", }, chingling: { randomBattleMoves: ["hypnosis", "reflect", "lightscreen", "toxic", "recover", "psychic", "signalbeam", "healbell"], tier: "LC", }, chimecho: { randomBattleMoves: ["psychic", "yawn", "recover", "calmmind", "shadowball", "healingwish", "healbell", "taunt"], randomDoubleBattleMoves: ["protect", "psychic", "thunderwave", "recover", "shadowball", "dazzlinggleam", "trickroom", "helpinghand", "taunt"], eventPokemon: [ {"generation": 3, "level": 10, "gender": "M", "moves":["wrap", "growl", "astonish"]}, ], tier: "PU", }, absol: { randomBattleMoves: ["swordsdance", "suckerpunch", "knockoff", "superpower", "pursuit", "playrough"], randomDoubleBattleMoves: ["swordsdance", "suckerpunch", "knockoff", "fireblast", "superpower", "protect", "playrough"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "abilities":["pressure"], "moves":["scratch", "leer", "wish"]}, {"generation": 3, "level": 5, "shiny": 1, "abilities":["pressure"], "moves":["scratch", "leer", "spite"]}, {"generation": 3, "level": 35, "abilities":["pressure"], "moves":["razorwind", "bite", "swordsdance", "spite"]}, {"generation": 3, "level": 70, "abilities":["pressure"], "moves":["doubleteam", "slash", "futuresight", "perishsong"]}, ], tier: "PU", }, absolmega: { randomBattleMoves: ["swordsdance", "suckerpunch", "knockoff", "fireblast", "superpower", "pursuit", "playrough", "icebeam"], randomDoubleBattleMoves: ["swordsdance", "suckerpunch", "knockoff", "fireblast", "superpower", "protect", "playrough"], requiredItem: "Absolite", tier: "BL2", }, snorunt: { randomBattleMoves: ["spikes", "icebeam", "iceshard", "shadowball", "toxic"], eventPokemon: [ {"generation": 3, "level": 20, "abilities":["innerfocus"], "moves":["sing", "waterpulse", "bite", "icywind"]}, ], tier: "LC", }, glalie: { randomBattleMoves: ["spikes", "icebeam", "iceshard", "taunt", "earthquake", "explosion", "superfang"], randomDoubleBattleMoves: ["icebeam", "iceshard", "taunt", "earthquake", "freezedry", "protect"], tier: "PU", }, glaliemega: { randomBattleMoves: ["freezedry", "iceshard", "earthquake", "explosion", "return", "spikes"], randomDoubleBattleMoves: ["crunch", "iceshard", "freezedry", "earthquake", "explosion", "protect", "return"], requiredItem: "Glalitite", tier: "RU", }, froslass: { randomBattleMoves: ["icebeam", "spikes", "destinybond", "shadowball", "taunt", "thunderwave"], randomDoubleBattleMoves: ["icebeam", "protect", "destinybond", "shadowball", "taunt", "thunderwave"], tier: "NU", }, spheal: { randomBattleMoves: ["substitute", "protect", "toxic", "surf", "icebeam", "yawn", "superfang"], eventPokemon: [ {"generation": 3, "level": 17, "abilities":["thickfat"], "moves":["charm", "aurorabeam", "watergun", "mudslap"]}, ], tier: "LC", }, sealeo: { randomBattleMoves: ["substitute", "protect", "toxic", "surf", "icebeam", "yawn", "superfang"], tier: "NFE", }, walrein: { randomBattleMoves: ["superfang", "protect", "toxic", "surf", "icebeam", "roar"], randomDoubleBattleMoves: ["protect", "icywind", "surf", "icebeam", "superfang", "roar"], eventPokemon: [ {"generation": 5, "level": 50, "isHidden": false, "abilities":["thickfat"], "moves":["icebeam", "brine", "hail", "sheercold"], "pokeball": "cherishball"}, ], tier: "PU", }, clamperl: { randomBattleMoves: ["shellsmash", "icebeam", "surf", "hiddenpowergrass", "hiddenpowerelectric", "substitute"], tier: "LC", }, huntail: { randomBattleMoves: ["shellsmash", "waterfall", "icebeam", "batonpass", "suckerpunch"], randomDoubleBattleMoves: ["shellsmash", "waterfall", "icefang", "batonpass", "suckerpunch", "protect"], tier: "PU", }, gorebyss: { randomBattleMoves: ["shellsmash", "batonpass", "hydropump", "icebeam", "hiddenpowergrass", "substitute"], randomDoubleBattleMoves: ["shellsmash", "batonpass", "surf", "icebeam", "hiddenpowergrass", "substitute", "protect"], tier: "PU", }, relicanth: { randomBattleMoves: ["headsmash", "waterfall", "earthquake", "doubleedge", "stealthrock", "toxic"], randomDoubleBattleMoves: ["headsmash", "waterfall", "earthquake", "doubleedge", "rockslide", "protect"], tier: "PU", }, luvdisc: { randomBattleMoves: ["icebeam", "toxic", "sweetkiss", "protect", "scald"], randomDoubleBattleMoves: ["icebeam", "toxic", "sweetkiss", "protect", "scald", "icywind", "healpulse"], tier: "PU", }, bagon: { randomBattleMoves: ["outrage", "dragondance", "firefang", "rockslide", "dragonclaw"], eventPokemon: [ {"generation": 3, "level": 5, "shiny": 1, "moves":["rage", "bite", "wish"]}, {"generation": 3, "level": 5, "shiny": 1, "moves":["rage", "bite", "irondefense"]}, {"generation": 5, "level": 1, "shiny": true, "isHidden": false, "moves":["rage"]}, {"generation": 6, "level": 1, "isHidden": false, "moves":["rage", "thrash"]}, ], tier: "LC", }, shelgon: { randomBattleMoves: ["outrage", "brickbreak", "dragonclaw", "dragondance", "crunch", "zenheadbutt"], tier: "NFE", }, salamence: { randomBattleMoves: ["outrage", "fireblast", "earthquake", "dracometeor", "dragondance", "dragonclaw", "fly"], randomDoubleBattleMoves: ["protect", "fireblast", "earthquake", "dracometeor", "tailwind", "dragondance", "dragonclaw", "hydropump", "rockslide"], eventPokemon: [ {"generation": 3, "level": 50, "moves":["protect", "dragonbreath", "scaryface", "fly"]}, {"generation": 3, "level": 50, "moves":["refresh", "dragonclaw", "dragondance", "aerialace"]}, {"generation": 4, "level": 50, "gender": "M", "nature": "Naughty", "moves":["hydropump", "stoneedge", "fireblast", "dragonclaw"], "pokeball": "cherishball"}, {"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "moves":["dragondance", "dragonclaw", "outrage", "aerialace"], "pokeball": "cherishball"}, ], tier: "BL", }, salamencemega: { randomBattleMoves: ["doubleedge", "return", "fireblast", "earthquake", "dracometeor", "roost", "dragondance"], randomDoubleBattleMoves: ["doubleedge", "return", "fireblast", "earthquake", "dracometeor", "protect", "dragondance", "dragonclaw"], requiredItem: "Salamencite", tier: "Uber", }, beldum: { randomBattleMoves: ["ironhead", "zenheadbutt", "headbutt", "irondefense"], eventPokemon: [ {"generation": 6, "level": 5, "shiny": true, "isHidden": false, "moves":["holdback", "ironhead", "zenheadbutt", "irondefense"], "pokeball": "cherishball"}, ], tier: "LC", }, metang: { randomBattleMoves: ["stealthrock", "meteormash", "toxic", "earthquake", "bulletpunch", "zenheadbutt"], eventPokemon: [ {"generation": 3, "level": 30, "moves":["takedown", "confusion", "metalclaw", "refresh"]}, ], tier: "NFE", }, metagross: { randomBattleMoves: ["meteormash", "earthquake", "agility", "stealthrock", "zenheadbutt", "bulletpunch", "thunderpunch", "explosion", "icepunch"], randomDoubleBattleMoves: ["meteormash", "earthquake", "protect", "zenheadbutt", "bulletpunch", "thunderpunch", "explosion", "icepunch", "hammerarm"], eventPokemon: [ {"generation": 4, "level": 62, "nature": "Brave", "moves":["bulletpunch", "meteormash", "hammerarm", "zenheadbutt"], "pokeball": "cherishball"}, {"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "moves":["meteormash", "earthquake", "bulletpunch", "hammerarm"], "pokeball": "cherishball"}, {"generation": 5, "level": 100, "isHidden": false, "moves":["bulletpunch", "zenheadbutt", "hammerarm", "icepunch"], "pokeball": "cherishball"}, {"generation": 5, "level": 45, "isHidden": false, "moves":["earthquake", "zenheadbutt", "protect", "meteormash"]}, {"generation": 5, "level": 45, "isHidden": true, "moves":["irondefense", "agility", "hammerarm", "doubleedge"]}, {"generation": 5, "level": 45, "isHidden": true, "moves":["psychic", "meteormash", "hammerarm", "doubleedge"]}, {"generation": 5, "level": 58, "nature": "Serious", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "moves":["earthquake", "hyperbeam", "psychic", "meteormash"], "pokeball": "cherishball"}, ], tier: "UU", }, metagrossmega: { randomBattleMoves: ["meteormash", "earthquake", "agility", "zenheadbutt", "hammerarm", "icepunch"], randomDoubleBattleMoves: ["meteormash", "earthquake", "protect", "zenheadbutt", "thunderpunch", "icepunch"], requiredItem: "Metagrossite", tier: "Uber", }, regirock: { randomBattleMoves: ["stealthrock", "thunderwave", "stoneedge", "drainpunch", "curse", "rest", "rockslide", "toxic"], randomDoubleBattleMoves: ["stealthrock", "thunderwave", "stoneedge", "drainpunch", "curse", "rockslide", "protect"], eventPokemon: [ {"generation": 3, "level": 40, "shiny": 1, "moves":["rockthrow", "curse", "superpower", "ancientpower"]}, {"generation": 3, "level": 40, "moves":["curse", "superpower", "ancientpower", "hyperbeam"]}, {"generation": 4, "level": 30, "shiny": 1, "moves":["stomp", "rockthrow", "curse", "superpower"]}, {"generation": 5, "level": 65, "shiny": 1, "moves":["irondefense", "chargebeam", "lockon", "zapcannon"]}, {"generation": 6, "level": 40, "shiny": 1, "isHidden": false, "moves":["bulldoze", "curse", "ancientpower", "irondefense"]}, {"generation": 6, "level": 50, "isHidden": true, "moves":["explosion", "icepunch", "stoneedge", "hammerarm"]}, ], eventOnly: true, tier: "PU", }, regice: { randomBattleMoves: ["thunderwave", "icebeam", "thunderbolt", "rest", "sleeptalk", "focusblast", "rockpolish"], randomDoubleBattleMoves: ["thunderwave", "icebeam", "thunderbolt", "icywind", "protect", "focusblast", "rockpolish"], eventPokemon: [ {"generation": 3, "level": 40, "shiny": 1, "moves":["icywind", "curse", "superpower", "ancientpower"]}, {"generation": 3, "level": 40, "moves":["curse", "superpower", "ancientpower", "hyperbeam"]}, {"generation": 4, "level": 30, "shiny": 1, "moves":["stomp", "icywind", "curse", "superpower"]}, {"generation": 5, "level": 65, "shiny": 1, "moves":["amnesia", "chargebeam", "lockon", "zapcannon"]}, {"generation": 6, "level": 40, "shiny": 1, "isHidden": false, "moves":["bulldoze", "curse", "ancientpower", "amnesia"]}, {"generation": 6, "level": 50, "isHidden": true, "moves":["thunderbolt", "amnesia", "icebeam", "hail"]}, ], eventOnly: true, tier: "PU", }, registeel: { randomBattleMoves: ["stealthrock", "thunderwave", "toxic", "protect", "seismictoss", "curse", "ironhead", "rest", "sleeptalk"], randomDoubleBattleMoves: ["stealthrock", "ironhead", "curse", "rest", "thunderwave", "protect", "seismictoss"], eventPokemon: [ {"generation": 3, "level": 40, "shiny": 1, "moves":["metalclaw", "curse", "superpower", "ancientpower"]}, {"generation": 3, "level": 40, "moves":["curse", "superpower", "ancientpower", "hyperbeam"]}, {"generation": 4, "level": 30, "shiny": 1, "moves":["stomp", "metalclaw", "curse", "superpower"]}, {"generation": 5, "level": 65, "shiny": 1, "moves":["amnesia", "chargebeam", "lockon", "zapcannon"]}, {"generation": 6, "level": 40, "shiny": 1, "isHidden": false, "moves":["curse", "ancientpower", "irondefense", "amnesia"]}, {"generation": 6, "level": 50, "isHidden": true, "moves":["ironhead", "rockslide", "gravity", "irondefense"]}, ], eventOnly: true, tier: "RU", }, latias: { randomBattleMoves: ["dracometeor", "psyshock", "hiddenpowerfire", "roost", "thunderbolt", "healingwish", "defog"], randomDoubleBattleMoves: ["dragonpulse", "psychic", "tailwind", "helpinghand", "healpulse", "lightscreen", "reflect", "protect"], eventPokemon: [ {"generation": 3, "level": 40, "shiny": 1, "moves":["watersport", "refresh", "mistball", "psychic"]}, {"generation": 3, "level": 50, "shiny": 1, "moves":["mistball", "psychic", "recover", "charm"]}, {"generation": 3, "level": 70, "moves":["mistball", "psychic", "recover", "charm"]}, {"generation": 4, "level": 35, "shiny": 1, "moves":["dragonbreath", "watersport", "refresh", "mistball"]}, {"generation": 4, "level": 40, "shiny": 1, "moves":["watersport", "refresh", "mistball", "zenheadbutt"]}, {"generation": 5, "level": 68, "shiny": 1, "moves":["psychoshift", "charm", "psychic", "healpulse"]}, {"generation": 6, "level": 30, "shiny": 1, "moves":["healpulse", "dragonbreath", "mistball", "psychoshift"]}, ], eventOnly: true, tier: "UU", }, latiasmega: { randomBattleMoves: ["calmmind", "dragonpulse", "surf", "dracometeor", "roost", "hiddenpowerfire", "substitute", "psyshock"], randomDoubleBattleMoves: ["dragonpulse", "psychic", "tailwind", "helpinghand", "healpulse", "lightscreen", "reflect", "protect"], requiredItem: "Latiasite", tier: "UU", }, latios: { randomBattleMoves: ["dracometeor", "hiddenpowerfire", "surf", "thunderbolt", "psyshock", "roost", "trick", "defog"], randomDoubleBattleMoves: ["dracometeor", "dragonpulse", "surf", "thunderbolt", "psyshock", "substitute", "trick", "tailwind", "protect", "hiddenpowerfire"], eventPokemon: [ {"generation": 3, "level": 40, "shiny": 1, "moves":["protect", "refresh", "lusterpurge", "psychic"]}, {"generation": 3, "level": 50, "shiny": 1, "moves":["lusterpurge", "psychic", "recover", "dragondance"]}, {"generation": 3, "level": 70, "moves":["lusterpurge", "psychic", "recover", "dragondance"]}, {"generation": 4, "level": 35, "shiny": 1, "moves":["dragonbreath", "protect", "refresh", "lusterpurge"]}, {"generation": 4, "level": 40, "shiny": 1, "moves":["protect", "refresh", "lusterpurge", "zenheadbutt"]}, {"generation": 5, "level": 68, "shiny": 1, "moves":["psychoshift", "dragondance", "psychic", "healpulse"]}, {"generation": 6, "level": 30, "shiny": 1, "moves":["healpulse", "dragonbreath", "lusterpurge", "psychoshift"]}, {"generation": 6, "level": 50, "nature": "Modest", "moves":["dragonpulse", "lusterpurge", "psychic", "healpulse"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "OU", }, latiosmega: { randomBattleMoves: ["calmmind", "dracometeor", "hiddenpowerfire", "psyshock", "roost", "defog"], randomDoubleBattleMoves: ["dracometeor", "dragonpulse", "surf", "thunderbolt", "psyshock", "substitute", "tailwind", "protect", "hiddenpowerfire"], requiredItem: "Latiosite", tier: "(OU)", }, kyogre: { randomBattleMoves: ["waterspout", "originpulse", "scald", "thunder", "icebeam"], randomDoubleBattleMoves: ["waterspout", "muddywater", "originpulse", "thunder", "icebeam", "calmmind", "rest", "sleeptalk", "protect"], eventPokemon: [ {"generation": 3, "level": 45, "shiny": 1, "moves":["bodyslam", "calmmind", "icebeam", "hydropump"]}, {"generation": 3, "level": 70, "shiny": 1, "moves":["hydropump", "rest", "sheercold", "doubleedge"]}, {"generation": 4, "level": 50, "shiny": 1, "moves":["aquaring", "icebeam", "ancientpower", "waterspout"]}, {"generation": 5, "level": 80, "shiny": 1, "moves":["icebeam", "ancientpower", "waterspout", "thunder"], "pokeball": "cherishball"}, {"generation": 5, "level": 100, "moves":["waterspout", "thunder", "icebeam", "sheercold"], "pokeball": "cherishball"}, {"generation": 6, "level": 45, "moves":["bodyslam", "aquaring", "icebeam", "originpulse"]}, {"generation": 6, "level": 100, "nature": "Timid", "moves":["waterspout", "thunder", "sheercold", "icebeam"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "Uber", }, kyogreprimal: { randomBattleMoves: ["calmmind", "waterspout", "originpulse", "scald", "thunder", "icebeam", "rest", "sleeptalk"], randomDoubleBattleMoves: ["waterspout", "originpulse", "muddywater", "thunder", "icebeam", "calmmind", "rest", "sleeptalk", "protect"], requiredItem: "Blue Orb", }, groudon: { randomBattleMoves: ["earthquake", "stealthrock", "lavaplume", "stoneedge", "roar", "toxic", "thunderwave", "dragonclaw", "firepunch"], randomDoubleBattleMoves: ["precipiceblades", "rockslide", "protect", "stoneedge", "swordsdance", "rockpolish", "dragonclaw", "firepunch"], eventPokemon: [ {"generation": 3, "level": 45, "shiny": 1, "moves":["slash", "bulkup", "earthquake", "fireblast"]}, {"generation": 3, "level": 70, "shiny": 1, "moves":["fireblast", "rest", "fissure", "solarbeam"]}, {"generation": 4, "level": 50, "shiny": 1, "moves":["rest", "earthquake", "ancientpower", "eruption"]}, {"generation": 5, "level": 80, "shiny": 1, "moves":["earthquake", "ancientpower", "eruption", "solarbeam"], "pokeball": "cherishball"}, {"generation": 5, "level": 100, "moves":["eruption", "hammerarm", "earthpower", "solarbeam"], "pokeball": "cherishball"}, {"generation": 6, "level": 45, "moves":["lavaplume", "rest", "earthquake", "precipiceblades"]}, {"generation": 6, "level": 100, "nature": "Adamant", "moves":["firepunch", "solarbeam", "hammerarm", "rockslide"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "Uber", }, groudonprimal: { randomBattleMoves: ["stealthrock", "precipiceblades", "lavaplume", "stoneedge", "dragontail", "rockpolish", "swordsdance", "firepunch"], randomDoubleBattleMoves: ["precipiceblades", "lavaplume", "rockslide", "stoneedge", "swordsdance", "overheat", "rockpolish", "firepunch", "protect"], requiredItem: "Red Orb", }, rayquaza: { randomBattleMoves: ["outrage", "vcreate", "extremespeed", "dragondance", "earthquake", "dracometeor", "dragonclaw"], randomDoubleBattleMoves: ["tailwind", "vcreate", "extremespeed", "dragondance", "earthquake", "dracometeor", "dragonclaw", "protect"], eventPokemon: [ {"generation": 3, "level": 70, "shiny": 1, "moves":["fly", "rest", "extremespeed", "outrage"]}, {"generation": 4, "level": 50, "shiny": 1, "moves":["rest", "airslash", "ancientpower", "outrage"]}, {"generation": 5, "level": 70, "shiny": true, "moves":["dragonpulse", "ancientpower", "outrage", "dragondance"], "pokeball": "cherishball"}, {"generation": 5, "level": 100, "moves":["extremespeed", "hyperbeam", "dragonpulse", "vcreate"], "pokeball": "cherishball"}, {"generation": 6, "level": 70, "moves":["extremespeed", "dragonpulse", "dragondance", "dragonascent"]}, {"generation": 6, "level": 70, "shiny": true, "moves":["dragonpulse", "thunder", "twister", "extremespeed"], "pokeball": "cherishball"}, {"generation": 6, "level": 70, "shiny": true, "moves":["dragonascent", "dragonclaw", "extremespeed", "dragondance"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "shiny": true, "moves":["dragonascent", "dracometeor", "fly", "celebrate"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "Uber", }, rayquazamega: { // randomBattleMoves: ["vcreate", "extremespeed", "swordsdance", "earthquake", "dragonascent", "dragonclaw", "dragondance"], randomDoubleBattleMoves: ["vcreate", "extremespeed", "swordsdance", "earthquake", "dragonascent", "dragonclaw", "dragondance", "protect"], requiredMove: "Dragon Ascent", tier: "AG", }, jirachi: { randomBattleMoves: ["ironhead", "uturn", "firepunch", "icepunch", "trick", "stealthrock", "bodyslam", "toxic", "wish", "substitute"], randomDoubleBattleMoves: ["bodyslam", "ironhead", "icywind", "thunderwave", "helpinghand", "trickroom", "uturn", "followme", "zenheadbutt", "protect"], eventPokemon: [ {"generation": 3, "level": 5, "moves":["wish", "confusion", "rest"]}, {"generation": 3, "level": 5, "shiny": true, "nature": "Bashful", "ivs": {"hp": 24, "atk": 3, "def": 30, "spa": 12, "spd": 16, "spe": 11}, "moves":["wish", "confusion", "rest"]}, {"generation": 3, "level": 5, "shiny": true, "nature": "Careful", "ivs": {"hp": 10, "atk": 0, "def": 10, "spa": 10, "spd": 26, "spe": 12}, "moves":["wish", "confusion", "rest"]}, {"generation": 3, "level": 5, "shiny": true, "nature": "Docile", "ivs": {"hp": 19, "atk": 7, "def": 10, "spa": 19, "spd": 10, "spe": 16}, "moves":["wish", "confusion", "rest"]}, {"generation": 3, "level": 5, "shiny": true, "nature": "Hasty", "ivs": {"hp": 3, "atk": 12, "def": 12, "spa": 7, "spd": 11, "spe": 9}, "moves":["wish", "confusion", "rest"]}, {"generation": 3, "level": 5, "shiny": true, "nature": "Jolly", "ivs": {"hp": 11, "atk": 8, "def": 6, "spa": 14, "spd": 5, "spe": 20}, "moves":["wish", "confusion", "rest"]}, {"generation": 3, "level": 5, "shiny": true, "nature": "Lonely", "ivs": {"hp": 31, "atk": 23, "def": 26, "spa": 29, "spd": 18, "spe": 5}, "moves":["wish", "confusion", "rest"]}, {"generation": 3, "level": 5, "shiny": true, "nature": "Naughty", "ivs": {"hp": 21, "atk": 31, "def": 31, "spa": 18, "spd": 24, "spe": 19}, "moves":["wish", "confusion", "rest"]}, {"generation": 3, "level": 5, "shiny": true, "nature": "Serious", "ivs": {"hp": 29, "atk": 10, "def": 31, "spa": 25, "spd": 23, "spe": 21}, "moves":["wish", "confusion", "rest"]}, {"generation": 3, "level": 5, "shiny": true, "nature": "Timid", "ivs": {"hp": 15, "atk": 28, "def": 29, "spa": 3, "spd": 0, "spe": 7}, "moves":["wish", "confusion", "rest"]}, {"generation": 3, "level": 30, "moves":["helpinghand", "psychic", "refresh", "rest"]}, {"generation": 4, "level": 5, "moves":["wish", "confusion", "rest"], "pokeball": "cherishball"}, {"generation": 4, "level": 5, "moves":["wish", "confusion", "rest", "dracometeor"], "pokeball": "cherishball"}, {"generation": 5, "level": 50, "moves":["healingwish", "psychic", "swift", "meteormash"], "pokeball": "cherishball"}, {"generation": 5, "level": 50, "moves":["dracometeor", "meteormash", "wish", "followme"], "pokeball": "cherishball"}, {"generation": 5, "level": 50, "moves":["wish", "healingwish", "cosmicpower", "meteormash"], "pokeball": "cherishball"}, {"generation": 5, "level": 50, "moves":["wish", "healingwish", "swift", "return"], "pokeball": "cherishball"}, {"generation": 6, "level": 10, "shiny": true, "moves":["wish", "swift", "healingwish", "moonblast"], "pokeball": "cherishball"}, {"generation": 6, "level": 15, "shiny": true, "moves":["wish", "confusion", "helpinghand", "return"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "moves":["heartstamp", "playrough", "wish", "cosmicpower"], "pokeball": "cherishball"}, {"generation": 6, "level": 25, "shiny": true, "moves":["wish", "confusion", "swift", "happyhour"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "moves":["wish", "confusion", "rest"], "pokeball": "cherishball"}, {"generation": 7, "level": 15, "moves":["swift", "wish", "healingwish", "rest"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "BL", }, deoxys: { randomBattleMoves: ["psychoboost", "stealthrock", "spikes", "firepunch", "superpower", "extremespeed", "knockoff", "taunt"], randomDoubleBattleMoves: ["psychoboost", "superpower", "extremespeed", "icebeam", "thunderbolt", "firepunch", "protect", "knockoff", "psyshock"], eventPokemon: [ {"generation": 3, "level": 30, "shiny": 1, "moves":["taunt", "pursuit", "psychic", "superpower"]}, {"generation": 3, "level": 30, "shiny": 1, "moves":["knockoff", "spikes", "psychic", "snatch"]}, {"generation": 3, "level": 30, "shiny": 1, "moves":["knockoff", "pursuit", "psychic", "swift"]}, {"generation": 3, "level": 70, "moves":["cosmicpower", "recover", "psychoboost", "hyperbeam"]}, {"generation": 4, "level": 50, "moves":["psychoboost", "zapcannon", "irondefense", "extremespeed"], "pokeball": "cherishball"}, {"generation": 4, "level": 50, "moves":["psychoboost", "swift", "doubleteam", "extremespeed"]}, {"generation": 4, "level": 50, "moves":["psychoboost", "detect", "counter", "mirrorcoat"]}, {"generation": 4, "level": 50, "moves":["psychoboost", "meteormash", "superpower", "hyperbeam"]}, {"generation": 4, "level": 50, "moves":["psychoboost", "leer", "wrap", "nightshade"]}, {"generation": 5, "level": 100, "moves":["nastyplot", "darkpulse", "recover", "psychoboost"], "pokeball": "duskball"}, {"generation": 6, "level": 80, "moves":["cosmicpower", "recover", "psychoboost", "hyperbeam"]}, ], eventOnly: true, tier: "Uber", }, deoxysattack: { randomBattleMoves: ["psychoboost", "superpower", "icebeam", "knockoff", "extremespeed", "firepunch", "stealthrock"], randomDoubleBattleMoves: ["psychoboost", "superpower", "extremespeed", "icebeam", "thunderbolt", "firepunch", "protect", "knockoff"], eventOnly: true, tier: "Uber", }, deoxysdefense: { randomBattleMoves: ["spikes", "stealthrock", "recover", "taunt", "toxic", "seismictoss", "knockoff"], randomDoubleBattleMoves: ["protect", "stealthrock", "recover", "taunt", "reflect", "seismictoss", "lightscreen", "trickroom", "psychic"], eventOnly: true, tier: "Uber", }, deoxysspeed: { randomBattleMoves: ["spikes", "stealthrock", "superpower", "psychoboost", "taunt", "magiccoat", "knockoff"], randomDoubleBattleMoves: ["superpower", "icebeam", "psychoboost", "taunt", "lightscreen", "reflect", "protect", "knockoff"], eventOnly: true, tier: "Uber", }, turtwig: { randomBattleMoves: ["reflect", "lightscreen", "stealthrock", "seedbomb", "substitute", "leechseed", "toxic"], eventPokemon: [ {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tackle", "withdraw", "absorb"]}, {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tackle", "withdraw", "absorb", "stockpile"]}, ], tier: "LC", }, grotle: { randomBattleMoves: ["reflect", "lightscreen", "stealthrock", "seedbomb", "substitute", "leechseed", "toxic"], tier: "NFE", }, torterra: { randomBattleMoves: ["stealthrock", "earthquake", "woodhammer", "stoneedge", "synthesis", "rockpolish"], randomDoubleBattleMoves: ["protect", "earthquake", "woodhammer", "stoneedge", "rockslide", "wideguard", "rockpolish"], eventPokemon: [ {"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["woodhammer", "earthquake", "outrage", "stoneedge"], "pokeball": "cherishball"}, ], tier: "PU", }, chimchar: { randomBattleMoves: ["stealthrock", "overheat", "hiddenpowergrass", "fakeout", "uturn", "gunkshot"], eventPokemon: [ {"generation": 4, "level": 40, "gender": "M", "nature": "Mild", "moves":["flamethrower", "thunderpunch", "grassknot", "helpinghand"], "pokeball": "cherishball"}, {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["scratch", "leer", "ember", "taunt"]}, {"generation": 4, "level": 40, "gender": "M", "nature": "Hardy", "moves":["flamethrower", "thunderpunch", "grassknot", "helpinghand"], "pokeball": "cherishball"}, {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["leer", "ember", "taunt", "fakeout"]}, ], tier: "LC", }, monferno: { randomBattleMoves: ["stealthrock", "overheat", "hiddenpowergrass", "fakeout", "vacuumwave", "uturn", "gunkshot"], tier: "NFE", }, infernape: { randomBattleMoves: ["stealthrock", "uturn", "earthquake", "closecombat", "flareblitz", "stoneedge", "machpunch", "nastyplot", "fireblast", "vacuumwave", "grassknot", "hiddenpowerice"], randomDoubleBattleMoves: ["fakeout", "heatwave", "closecombat", "uturn", "grassknot", "stoneedge", "machpunch", "feint", "taunt", "flareblitz", "hiddenpowerice", "thunderpunch", "protect"], eventPokemon: [ {"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["fireblast", "closecombat", "uturn", "grassknot"], "pokeball": "cherishball"}, {"generation": 6, "level": 88, "isHidden": true, "moves":["fireblast", "closecombat", "firepunch", "focuspunch"], "pokeball": "cherishball"}, ], tier: "UU", }, piplup: { randomBattleMoves: ["stealthrock", "hydropump", "scald", "icebeam", "hiddenpowerelectric", "hiddenpowerfire", "yawn", "defog"], eventPokemon: [ {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["pound", "growl", "bubble"]}, {"generation": 5, "level": 15, "shiny": 1, "isHidden": false, "moves":["hydropump", "featherdance", "watersport", "peck"], "pokeball": "cherishball"}, {"generation": 5, "level": 15, "gender": "M", "isHidden": false, "moves":["sing", "round", "featherdance", "peck"], "pokeball": "cherishball"}, {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["pound", "growl", "bubble", "featherdance"]}, {"generation": 6, "level": 7, "isHidden": false, "moves":["pound", "growl", "return"], "pokeball": "cherishball"}, {"generation": 7, "level": 30, "gender": "M", "nature": "Hardy", "isHidden": false, "moves":["hydropump", "bubblebeam", "whirlpool", "drillpeck"], "pokeball": "pokeball"}, ], tier: "LC", }, prinplup: { randomBattleMoves: ["stealthrock", "hydropump", "scald", "icebeam", "hiddenpowerelectric", "hiddenpowerfire", "yawn", "defog"], tier: "NFE", }, empoleon: { randomBattleMoves: ["hydropump", "flashcannon", "grassknot", "hiddenpowerfire", "icebeam", "scald", "toxic", "roar", "stealthrock"], randomDoubleBattleMoves: ["icywind", "scald", "surf", "icebeam", "hiddenpowerelectric", "protect", "grassknot", "flashcannon"], eventPokemon: [ {"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["hydropump", "icebeam", "aquajet", "grassknot"], "pokeball": "cherishball"}, ], tier: "UU", }, starly: { randomBattleMoves: ["bravebird", "return", "uturn", "pursuit"], eventPokemon: [ {"generation": 4, "level": 1, "gender": "M", "nature": "Mild", "moves":["tackle", "growl"]}, ], tier: "LC", }, staravia: { randomBattleMoves: ["bravebird", "return", "uturn", "pursuit", "defog"], tier: "NFE", }, staraptor: { randomBattleMoves: ["bravebird", "closecombat", "uturn", "quickattack", "roost", "doubleedge"], randomDoubleBattleMoves: ["bravebird", "closecombat", "uturn", "quickattack", "doubleedge", "tailwind", "protect"], tier: "BL", }, bidoof: { randomBattleMoves: ["return", "aquatail", "curse", "quickattack", "stealthrock", "superfang"], eventPokemon: [ {"generation": 4, "level": 1, "gender": "M", "nature": "Lonely", "abilities":["simple"], "moves":["tackle"]}, ], tier: "LC", }, bibarel: { randomBattleMoves: ["return", "waterfall", "swordsdance", "quickattack", "aquajet"], randomDoubleBattleMoves: ["return", "waterfall", "curse", "aquajet", "quickattack", "protect", "rest"], tier: "PU", }, kricketot: { randomBattleMoves: ["endeavor", "mudslap", "bugbite", "strugglebug"], tier: "LC", }, kricketune: { randomBattleMoves: ["leechlife", "endeavor", "taunt", "toxic", "stickyweb", "knockoff"], randomDoubleBattleMoves: ["leechlife", "protect", "taunt", "stickyweb", "knockoff"], tier: "PU", }, shinx: { randomBattleMoves: ["wildcharge", "icefang", "firefang", "crunch"], tier: "LC", }, luxio: { randomBattleMoves: ["wildcharge", "icefang", "firefang", "crunch"], tier: "NFE", }, luxray: { randomBattleMoves: ["wildcharge", "icefang", "voltswitch", "crunch", "superpower", "facade"], randomDoubleBattleMoves: ["wildcharge", "icefang", "voltswitch", "crunch", "superpower", "facade", "protect"], tier: "PU", }, cranidos: { randomBattleMoves: ["headsmash", "rockslide", "earthquake", "zenheadbutt", "firepunch", "rockpolish", "crunch"], eventPokemon: [ {"generation": 5, "level": 15, "gender": "M", "isHidden": false, "moves":["pursuit", "takedown", "crunch", "headbutt"], "pokeball": "cherishball"}, ], tier: "LC", }, rampardos: { randomBattleMoves: ["headsmash", "earthquake", "rockpolish", "crunch", "rockslide", "firepunch"], randomDoubleBattleMoves: ["headsmash", "earthquake", "zenheadbutt", "rockslide", "crunch", "stoneedge", "protect"], tier: "PU", }, shieldon: { randomBattleMoves: ["stealthrock", "metalburst", "fireblast", "icebeam", "protect", "toxic", "roar"], eventPokemon: [ {"generation": 5, "level": 15, "gender": "M", "isHidden": false, "moves":["metalsound", "takedown", "bodyslam", "protect"], "pokeball": "cherishball"}, ], tier: "LC", }, bastiodon: { randomBattleMoves: ["stealthrock", "rockblast", "metalburst", "protect", "toxic", "roar"], randomDoubleBattleMoves: ["stealthrock", "stoneedge", "metalburst", "protect", "wideguard", "guardsplit"], tier: "PU", }, burmy: { randomBattleMoves: ["bugbite", "hiddenpowerice", "electroweb", "protect"], tier: "LC", }, wormadam: { randomBattleMoves: ["gigadrain", "bugbuzz", "quiverdance", "hiddenpowerrock", "leafstorm"], randomDoubleBattleMoves: ["leafstorm", "gigadrain", "bugbuzz", "hiddenpowerice", "hiddenpowerrock", "stringshot", "protect"], tier: "PU", }, wormadamsandy: { randomBattleMoves: ["earthquake", "toxic", "protect", "stealthrock"], randomDoubleBattleMoves: ["earthquake", "suckerpunch", "rockblast", "protect", "stringshot"], tier: "PU", }, wormadamtrash: { randomBattleMoves: ["stealthrock", "toxic", "gyroball", "protect"], randomDoubleBattleMoves: ["strugglebug", "stringshot", "gyroball", "bugbuzz", "flashcannon", "suckerpunch", "protect"], tier: "PU", }, mothim: { randomBattleMoves: ["quiverdance", "bugbuzz", "airslash", "gigadrain", "hiddenpowerground", "uturn"], randomDoubleBattleMoves: ["quiverdance", "bugbuzz", "airslash", "gigadrain", "roost", "protect"], tier: "PU", }, combee: { randomBattleMoves: ["bugbuzz", "aircutter", "endeavor", "ominouswind", "tailwind"], tier: "LC", }, vespiquen: { randomBattleMoves: ["substitute", "healorder", "toxic", "attackorder", "defendorder", "infestation"], randomDoubleBattleMoves: ["tailwind", "healorder", "stringshot", "attackorder", "strugglebug", "protect"], tier: "PU", }, pachirisu: { randomBattleMoves: ["nuzzle", "thunderbolt", "superfang", "toxic", "uturn"], randomDoubleBattleMoves: ["nuzzle", "thunderbolt", "superfang", "followme", "uturn", "helpinghand", "protect"], eventPokemon: [ {"generation": 6, "level": 50, "nature": "Impish", "ivs": {"hp": 31, "atk": 31, "def": 31, "spa": 14, "spd": 31, "spe": 31}, "isHidden": true, "moves":["nuzzle", "superfang", "followme", "protect"], "pokeball": "cherishball"}, ], tier: "PU", }, buizel: { randomBattleMoves: ["waterfall", "aquajet", "switcheroo", "brickbreak", "bulkup", "batonpass", "icepunch"], tier: "LC", }, floatzel: { randomBattleMoves: ["bulkup", "batonpass", "waterfall", "icepunch", "substitute", "taunt", "aquajet", "brickbreak"], randomDoubleBattleMoves: ["waterfall", "aquajet", "switcheroo", "raindance", "protect", "icepunch", "crunch", "taunt"], tier: "PU", }, cherubi: { randomBattleMoves: ["sunnyday", "solarbeam", "weatherball", "hiddenpowerice", "aromatherapy", "dazzlinggleam"], tier: "LC", }, cherrim: { randomBattleMoves: ["energyball", "dazzlinggleam", "hiddenpowerfire", "synthesis", "healingwish"], randomDoubleBattleMoves: ["sunnyday", "solarbeam", "weatherball", "gigadrain", "protect"], tier: "PU", }, cherrimsunshine: { randomBattleMoves: ["sunnyday", "solarbeam", "gigadrain", "weatherball", "hiddenpowerice"], randomDoubleBattleMoves: ["sunnyday", "solarbeam", "gigadrain", "weatherball", "protect"], battleOnly: true, }, shellos: { randomBattleMoves: ["scald", "clearsmog", "recover", "toxic", "icebeam", "stockpile"], tier: "LC", }, gastrodon: { randomBattleMoves: ["earthquake", "icebeam", "scald", "toxic", "recover", "clearsmog"], randomDoubleBattleMoves: ["earthpower", "icebeam", "scald", "muddywater", "recover", "icywind", "protect"], tier: "PU", }, drifloon: { randomBattleMoves: ["shadowball", "substitute", "calmmind", "hypnosis", "hiddenpowerfighting", "thunderbolt", "destinybond", "willowisp"], tier: "LC Uber", }, drifblim: { randomBattleMoves: ["acrobatics", "willowisp", "substitute", "destinybond", "shadowball", "hex"], randomDoubleBattleMoves: ["shadowball", "substitute", "hypnosis", "hiddenpowerfighting", "thunderbolt", "destinybond", "willowisp", "protect"], tier: "PU", }, buneary: { randomBattleMoves: ["fakeout", "return", "switcheroo", "thunderpunch", "jumpkick", "firepunch", "icepunch", "healingwish"], tier: "LC", }, lopunny: { randomBattleMoves: ["return", "switcheroo", "highjumpkick", "icepunch", "healingwish"], randomDoubleBattleMoves: ["return", "switcheroo", "highjumpkick", "firepunch", "icepunch", "fakeout", "protect", "encore"], tier: "PU", }, lopunnymega: { randomBattleMoves: ["return", "highjumpkick", "substitute", "fakeout", "icepunch"], randomDoubleBattleMoves: ["return", "highjumpkick", "protect", "fakeout", "icepunch", "encore"], requiredItem: "Lopunnite", tier: "OU", }, glameow: { randomBattleMoves: ["fakeout", "uturn", "suckerpunch", "hypnosis", "quickattack", "return", "foulplay"], tier: "LC", }, purugly: { randomBattleMoves: ["fakeout", "uturn", "suckerpunch", "quickattack", "return", "knockoff"], randomDoubleBattleMoves: ["fakeout", "uturn", "suckerpunch", "quickattack", "return", "knockoff", "protect"], tier: "PU", }, stunky: { randomBattleMoves: ["pursuit", "suckerpunch", "crunch", "fireblast", "explosion", "taunt", "playrough", "defog"], tier: "LC", }, skuntank: { randomBattleMoves: ["pursuit", "suckerpunch", "crunch", "fireblast", "taunt", "poisonjab", "defog"], randomDoubleBattleMoves: ["protect", "suckerpunch", "crunch", "fireblast", "taunt", "poisonjab", "playrough", "snarl"], tier: "PU", }, bronzor: { randomBattleMoves: ["stealthrock", "psychic", "toxic", "hypnosis", "reflect", "lightscreen", "trickroom", "trick"], tier: "LC", }, bronzong: { randomBattleMoves: ["stealthrock", "earthquake", "toxic", "reflect", "lightscreen", "trickroom", "explosion", "gyroball"], randomDoubleBattleMoves: ["earthquake", "protect", "reflect", "lightscreen", "trickroom", "explosion", "gyroball"], tier: "RU", }, chatot: { randomBattleMoves: ["nastyplot", "boomburst", "heatwave", "hiddenpowerground", "substitute", "chatter", "uturn"], randomDoubleBattleMoves: ["nastyplot", "heatwave", "encore", "substitute", "chatter", "uturn", "protect", "hypervoice", "boomburst"], eventPokemon: [ {"generation": 4, "level": 25, "gender": "M", "nature": "Jolly", "abilities":["keeneye"], "moves":["mirrormove", "furyattack", "chatter", "taunt"]}, ], tier: "PU", }, spiritomb: { randomBattleMoves: ["shadowsneak", "suckerpunch", "pursuit", "willowisp", "darkpulse", "rest", "sleeptalk", "foulplay", "painsplit", "calmmind"], randomDoubleBattleMoves: ["shadowsneak", "suckerpunch", "icywind", "willowisp", "snarl", "darkpulse", "protect", "foulplay", "painsplit"], eventPokemon: [ {"generation": 5, "level": 61, "gender": "F", "nature": "Quiet", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "moves":["darkpulse", "psychic", "silverwind", "embargo"], "pokeball": "cherishball"}, ], tier: "NU", }, gible: { randomBattleMoves: ["outrage", "dragonclaw", "earthquake", "fireblast", "stoneedge", "stealthrock"], tier: "LC", }, gabite: { randomBattleMoves: ["outrage", "dragonclaw", "earthquake", "fireblast", "stoneedge", "stealthrock"], tier: "NFE", }, garchomp: { randomBattleMoves: ["outrage", "dragonclaw", "earthquake", "stoneedge", "fireblast", "swordsdance", "stealthrock", "firefang"], randomDoubleBattleMoves: ["substitute", "dragonclaw", "earthquake", "stoneedge", "rockslide", "swordsdance", "protect", "firefang"], eventPokemon: [ {"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["outrage", "earthquake", "swordsdance", "stoneedge"], "pokeball": "cherishball"}, {"generation": 5, "level": 48, "gender": "M", "isHidden": true, "moves":["dragonclaw", "dig", "crunch", "outrage"]}, {"generation": 6, "level": 48, "gender": "M", "isHidden": false, "moves":["dracometeor", "dragonclaw", "dig", "crunch"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "gender": "M", "isHidden": false, "moves":["slash", "dragonclaw", "dig", "crunch"], "pokeball": "cherishball"}, {"generation": 6, "level": 66, "gender": "F", "perfectIVs": 3, "isHidden": false, "moves":["dragonrush", "earthquake", "brickbreak", "gigaimpact"], "pokeball": "cherishball"}, ], tier: "OU", }, garchompmega: { randomBattleMoves: ["outrage", "dracometeor", "earthquake", "stoneedge", "fireblast", "swordsdance"], randomDoubleBattleMoves: ["substitute", "dragonclaw", "earthquake", "stoneedge", "rockslide", "swordsdance", "protect", "fireblast"], requiredItem: "Garchompite", tier: "(OU)", }, riolu: { randomBattleMoves: ["crunch", "rockslide", "copycat", "drainpunch", "highjumpkick", "icepunch", "swordsdance"], eventPokemon: [ {"generation": 4, "level": 30, "gender": "M", "nature": "Serious", "abilities":["steadfast"], "moves":["aurasphere", "shadowclaw", "bulletpunch", "drainpunch"]}, ], tier: "LC", }, lucario: { randomBattleMoves: ["swordsdance", "closecombat", "crunch", "extremespeed", "icepunch", "nastyplot", "aurasphere", "darkpulse", "vacuumwave", "flashcannon"], randomDoubleBattleMoves: ["followme", "closecombat", "crunch", "extremespeed", "icepunch", "bulletpunch", "aurasphere", "darkpulse", "vacuumwave", "flashcannon", "protect"], eventPokemon: [ {"generation": 4, "level": 50, "gender": "M", "nature": "Modest", "abilities":["steadfast"], "moves":["aurasphere", "darkpulse", "dragonpulse", "waterpulse"], "pokeball": "cherishball"}, {"generation": 4, "level": 30, "gender": "M", "nature": "Adamant", "abilities":["innerfocus"], "moves":["forcepalm", "bonerush", "sunnyday", "blazekick"], "pokeball": "cherishball"}, {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["detect", "metalclaw", "counter", "bulletpunch"]}, {"generation": 5, "level": 50, "gender": "M", "nature": "Naughty", "ivs": {"atk": 31}, "isHidden": true, "moves":["bulletpunch", "closecombat", "stoneedge", "shadowclaw"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "nature": "Jolly", "isHidden": false, "abilities":["innerfocus"], "moves":["closecombat", "aurasphere", "flashcannon", "quickattack"], "pokeball": "cherishball"}, {"generation": 7, "level": 40, "gender": "M", "nature": "Serious", "isHidden": false, "abilities":["steadfast"], "moves":["aurasphere", "highjumpkick", "dragonpulse", "extremespeed"], "pokeball": "pokeball"}, ], tier: "BL2", }, lucariomega: { randomBattleMoves: ["swordsdance", "closecombat", "crunch", "icepunch", "bulletpunch", "nastyplot", "aurasphere", "darkpulse", "flashcannon"], randomDoubleBattleMoves: ["followme", "closecombat", "crunch", "extremespeed", "icepunch", "bulletpunch", "aurasphere", "darkpulse", "vacuumwave", "flashcannon", "protect"], requiredItem: "Lucarionite", tier: "Uber", }, hippopotas: { randomBattleMoves: ["earthquake", "slackoff", "whirlwind", "stealthrock", "protect", "toxic", "stockpile"], tier: "LC", }, hippowdon: { randomBattleMoves: ["earthquake", "slackoff", "whirlwind", "stealthrock", "toxic", "stoneedge"], randomDoubleBattleMoves: ["earthquake", "slackoff", "rockslide", "stealthrock", "protect", "stoneedge", "whirlwind"], tier: "UU", }, skorupi: { randomBattleMoves: ["toxicspikes", "xscissor", "poisonjab", "knockoff", "pinmissile", "whirlwind"], tier: "LC", }, drapion: { randomBattleMoves: ["knockoff", "taunt", "toxicspikes", "poisonjab", "whirlwind", "swordsdance", "aquatail", "earthquake"], randomDoubleBattleMoves: ["snarl", "taunt", "protect", "earthquake", "aquatail", "swordsdance", "poisonjab", "knockoff"], tier: "RU", }, croagunk: { randomBattleMoves: ["fakeout", "vacuumwave", "suckerpunch", "drainpunch", "darkpulse", "knockoff", "gunkshot", "toxic"], eventPokemon: [ {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["astonish", "mudslap", "poisonsting", "taunt"]}, {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["mudslap", "poisonsting", "taunt", "poisonjab"]}, ], tier: "LC", }, toxicroak: { randomBattleMoves: ["swordsdance", "gunkshot", "drainpunch", "suckerpunch", "icepunch", "substitute"], randomDoubleBattleMoves: ["suckerpunch", "drainpunch", "substitute", "swordsdance", "knockoff", "icepunch", "gunkshot", "fakeout", "protect"], tier: "NU", }, carnivine: { randomBattleMoves: ["swordsdance", "powerwhip", "return", "sleeppowder", "substitute", "knockoff"], randomDoubleBattleMoves: ["swordsdance", "powerwhip", "return", "sleeppowder", "substitute", "leechseed", "knockoff", "ragepowder", "protect"], tier: "PU", }, finneon: { randomBattleMoves: ["surf", "uturn", "icebeam", "hiddenpowerelectric", "hiddenpowergrass"], tier: "LC", }, lumineon: { randomBattleMoves: ["scald", "icebeam", "uturn", "toxic", "defog"], randomDoubleBattleMoves: ["surf", "uturn", "icebeam", "toxic", "raindance", "tailwind", "scald", "protect"], tier: "PU", }, snover: { randomBattleMoves: ["blizzard", "iceshard", "gigadrain", "leechseed", "substitute", "woodhammer"], tier: "LC", }, abomasnow: { randomBattleMoves: ["woodhammer", "iceshard", "blizzard", "gigadrain", "leechseed", "substitute", "focuspunch", "earthquake"], randomDoubleBattleMoves: ["blizzard", "iceshard", "gigadrain", "protect", "focusblast", "woodhammer", "earthquake"], tier: "PU", }, abomasnowmega: { randomBattleMoves: ["blizzard", "gigadrain", "woodhammer", "earthquake", "iceshard", "hiddenpowerfire"], randomDoubleBattleMoves: ["blizzard", "iceshard", "gigadrain", "protect", "focusblast", "woodhammer", "earthquake"], requiredItem: "Abomasite", tier: "RU", }, rotom: { randomBattleMoves: ["thunderbolt", "voltswitch", "shadowball", "substitute", "painsplit", "hiddenpowerice", "trick", "willowisp"], randomDoubleBattleMoves: ["thunderbolt", "voltswitch", "shadowball", "substitute", "painsplit", "hiddenpowerice", "trick", "willowisp", "electroweb", "protect"], eventPokemon: [ {"generation": 5, "level": 10, "nature": "Naughty", "moves":["uproar", "astonish", "trick", "thundershock"], "pokeball": "cherishball"}, {"generation": 6, "level": 10, "nature": "Quirky", "moves":["shockwave", "astonish", "trick", "thunderwave"], "pokeball": "cherishball"}, ], tier: "NU", }, rotomheat: { randomBattleMoves: ["overheat", "thunderbolt", "voltswitch", "hiddenpowerice", "painsplit", "willowisp", "trick"], randomDoubleBattleMoves: ["overheat", "thunderbolt", "voltswitch", "substitute", "painsplit", "hiddenpowerice", "willowisp", "trick", "electroweb", "protect"], tier: "RU", }, rotomwash: { randomBattleMoves: ["hydropump", "thunderbolt", "voltswitch", "painsplit", "hiddenpowerice", "willowisp", "trick"], randomDoubleBattleMoves: ["hydropump", "thunderbolt", "voltswitch", "substitute", "painsplit", "hiddenpowerice", "willowisp", "trick", "electroweb", "protect", "hiddenpowergrass"], tier: "UU", }, rotomfrost: { randomBattleMoves: ["blizzard", "thunderbolt", "voltswitch", "substitute", "painsplit", "willowisp", "trick"], randomDoubleBattleMoves: ["blizzard", "thunderbolt", "voltswitch", "substitute", "painsplit", "willowisp", "trick", "electroweb", "protect"], tier: "PU", }, rotomfan: { randomBattleMoves: ["airslash", "thunderbolt", "voltswitch", "painsplit", "willowisp", "trick"], randomDoubleBattleMoves: ["airslash", "thunderbolt", "voltswitch", "substitute", "painsplit", "hiddenpowerice", "willowisp", "electroweb", "discharge", "protect"], tier: "PU", }, rotommow: { randomBattleMoves: ["leafstorm", "thunderbolt", "voltswitch", "painsplit", "hiddenpowerfire", "willowisp", "trick"], randomDoubleBattleMoves: ["leafstorm", "thunderbolt", "voltswitch", "substitute", "painsplit", "hiddenpowerfire", "willowisp", "trick", "electroweb", "protect"], tier: "NU", }, uxie: { randomBattleMoves: ["stealthrock", "thunderwave", "psychic", "uturn", "healbell", "knockoff", "yawn"], randomDoubleBattleMoves: ["uturn", "psyshock", "yawn", "healbell", "stealthrock", "thunderbolt", "protect", "helpinghand", "thunderwave"], eventPokemon: [ {"generation": 4, "level": 50, "shiny": 1, "moves":["confusion", "yawn", "futuresight", "amnesia"]}, {"generation": 4, "level": 50, "shiny": 1, "moves":["swift", "yawn", "futuresight", "amnesia"]}, {"generation": 5, "level": 65, "shiny": 1, "moves":["futuresight", "amnesia", "extrasensory", "flail"]}, {"generation": 6, "level": 50, "shiny": 1, "moves":["yawn", "futuresight", "amnesia", "extrasensory"]}, ], eventOnly: true, tier: "NU", }, mesprit: { randomBattleMoves: ["calmmind", "psychic", "psyshock", "energyball", "signalbeam", "hiddenpowerfire", "icebeam", "healingwish", "stealthrock", "uturn"], randomDoubleBattleMoves: ["calmmind", "psychic", "thunderbolt", "icebeam", "substitute", "uturn", "trick", "protect", "knockoff", "helpinghand"], eventPokemon: [ {"generation": 4, "level": 50, "shiny": 1, "moves":["confusion", "luckychant", "futuresight", "charm"]}, {"generation": 4, "level": 50, "shiny": 1, "moves":["swift", "luckychant", "futuresight", "charm"]}, {"generation": 5, "level": 50, "shiny": 1, "moves":["futuresight", "charm", "extrasensory", "copycat"]}, {"generation": 6, "level": 50, "shiny": 1, "moves":["luckychant", "futuresight", "charm", "extrasensory"]}, ], eventOnly: true, tier: "PU", }, azelf: { randomBattleMoves: ["nastyplot", "psyshock", "fireblast", "dazzlinggleam", "stealthrock", "knockoff", "taunt", "explosion"], randomDoubleBattleMoves: ["nastyplot", "psychic", "fireblast", "thunderbolt", "icepunch", "knockoff", "zenheadbutt", "uturn", "trick", "taunt", "protect", "dazzlinggleam"], eventPokemon: [ {"generation": 4, "level": 50, "shiny": 1, "moves":["confusion", "uproar", "futuresight", "nastyplot"]}, {"generation": 4, "level": 50, "shiny": 1, "moves":["swift", "uproar", "futuresight", "nastyplot"]}, {"generation": 5, "level": 50, "shiny": 1, "moves":["futuresight", "nastyplot", "extrasensory", "lastresort"]}, {"generation": 6, "level": 50, "shiny": 1, "moves":["uproar", "futuresight", "nastyplot", "extrasensory"]}, ], eventOnly: true, tier: "UU", }, dialga: { randomBattleMoves: ["stealthrock", "toxic", "dracometeor", "fireblast", "flashcannon", "roar", "thunderbolt"], randomDoubleBattleMoves: ["dracometeor", "dragonpulse", "protect", "thunderbolt", "flashcannon", "earthpower", "fireblast", "aurasphere"], eventPokemon: [ {"generation": 4, "level": 47, "shiny": 1, "moves":["metalclaw", "ancientpower", "dragonclaw", "roaroftime"]}, {"generation": 4, "level": 70, "shiny": 1, "moves":["roaroftime", "healblock", "earthpower", "slash"]}, {"generation": 4, "level": 1, "shiny": 1, "moves":["dragonbreath", "scaryface"]}, {"generation": 5, "level": 5, "isHidden": true, "moves":["dragonbreath", "scaryface"], "pokeball": "dreamball"}, {"generation": 5, "level": 100, "shiny": true, "isHidden": false, "moves":["dragonpulse", "dracometeor", "aurasphere", "roaroftime"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["aurasphere", "irontail", "roaroftime", "flashcannon"]}, {"generation": 6, "level": 100, "nature": "Modest", "isHidden": true, "moves":["metalburst", "overheat", "roaroftime", "flashcannon"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "Uber", }, palkia: { randomBattleMoves: ["spacialrend", "dracometeor", "hydropump", "thunderwave", "dragontail", "fireblast"], randomDoubleBattleMoves: ["spacialrend", "dracometeor", "surf", "hydropump", "thunderbolt", "fireblast", "protect"], eventPokemon: [ {"generation": 4, "level": 47, "shiny": 1, "moves":["waterpulse", "ancientpower", "dragonclaw", "spacialrend"]}, {"generation": 4, "level": 70, "shiny": 1, "moves":["spacialrend", "healblock", "earthpower", "slash"]}, {"generation": 4, "level": 1, "shiny": 1, "moves":["dragonbreath", "scaryface"]}, {"generation": 5, "level": 5, "isHidden": true, "moves":["dragonbreath", "scaryface"], "pokeball": "dreamball"}, {"generation": 5, "level": 100, "shiny": true, "isHidden": false, "moves":["hydropump", "dracometeor", "spacialrend", "aurasphere"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["earthpower", "aurasphere", "spacialrend", "hydropump"]}, {"generation": 6, "level": 100, "nature": "Timid", "isHidden": true, "moves":["earthpower", "aurasphere", "spacialrend", "hydropump"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "Uber", }, heatran: { randomBattleMoves: ["fireblast", "lavaplume", "stealthrock", "earthpower", "flashcannon", "protect", "toxic", "roar"], randomDoubleBattleMoves: ["heatwave", "substitute", "earthpower", "protect", "eruption", "willowisp"], eventPokemon: [ {"generation": 4, "level": 70, "shiny": 1, "moves":["scaryface", "lavaplume", "firespin", "ironhead"]}, {"generation": 4, "level": 50, "shiny": 1, "moves":["metalsound", "crunch", "scaryface", "lavaplume"]}, {"generation": 4, "level": 50, "nature": "Quiet", "moves":["eruption", "magmastorm", "earthpower", "ancientpower"]}, {"generation": 5, "level": 68, "shiny": 1, "isHidden": false, "moves":["scaryface", "lavaplume", "firespin", "ironhead"]}, {"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["metalsound", "crunch", "scaryface", "lavaplume"]}, ], eventOnly: true, unreleasedHidden: true, tier: "OU", }, regigigas: { randomBattleMoves: ["thunderwave", "confuseray", "substitute", "return", "knockoff", "drainpunch"], randomDoubleBattleMoves: ["thunderwave", "substitute", "return", "icywind", "rockslide", "earthquake", "knockoff", "wideguard"], eventPokemon: [ {"generation": 4, "level": 70, "shiny": 1, "moves":["confuseray", "stomp", "superpower", "zenheadbutt"]}, {"generation": 4, "level": 1, "shiny": 1, "moves":["dizzypunch", "knockoff", "foresight", "confuseray"]}, {"generation": 4, "level": 100, "moves":["ironhead", "rockslide", "icywind", "crushgrip"], "pokeball": "cherishball"}, {"generation": 5, "level": 68, "shiny": 1, "moves":["revenge", "wideguard", "zenheadbutt", "payback"]}, {"generation": 6, "level": 50, "shiny": 1, "moves":["foresight", "revenge", "wideguard", "zenheadbutt"]}, ], eventOnly: true, tier: "PU", }, giratina: { randomBattleMoves: ["rest", "sleeptalk", "dragontail", "roar", "willowisp", "shadowball", "dragonpulse"], randomDoubleBattleMoves: ["tailwind", "shadowsneak", "protect", "dragontail", "willowisp", "calmmind", "dragonpulse", "shadowball"], eventPokemon: [ {"generation": 4, "level": 70, "shiny": 1, "moves":["shadowforce", "healblock", "earthpower", "slash"]}, {"generation": 4, "level": 47, "shiny": 1, "moves":["ominouswind", "ancientpower", "dragonclaw", "shadowforce"]}, {"generation": 4, "level": 1, "shiny": 1, "moves":["dragonbreath", "scaryface"]}, {"generation": 5, "level": 5, "isHidden": true, "moves":["dragonbreath", "scaryface"], "pokeball": "dreamball"}, {"generation": 5, "level": 100, "shiny": true, "isHidden": false, "moves":["dragonpulse", "dragonclaw", "aurasphere", "shadowforce"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["aurasphere", "shadowclaw", "shadowforce", "hex"]}, {"generation": 6, "level": 100, "nature": "Brave", "isHidden": true, "moves":["aurasphere", "dracometeor", "shadowforce", "ironhead"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "Uber", }, giratinaorigin: { randomBattleMoves: ["dracometeor", "shadowsneak", "dragontail", "willowisp", "defog", "toxic", "shadowball", "earthquake"], randomDoubleBattleMoves: ["dracometeor", "shadowsneak", "tailwind", "hiddenpowerfire", "willowisp", "calmmind", "substitute", "dragonpulse", "shadowball", "aurasphere", "protect", "earthquake"], eventOnly: true, requiredItem: "Griseous Orb", tier: "Uber", }, cresselia: { randomBattleMoves: ["moonlight", "psychic", "icebeam", "thunderwave", "toxic", "substitute", "psyshock", "moonblast", "calmmind"], randomDoubleBattleMoves: ["psyshock", "icywind", "thunderwave", "trickroom", "moonblast", "moonlight", "skillswap", "reflect", "lightscreen", "icebeam", "protect", "helpinghand"], eventPokemon: [ {"generation": 4, "level": 50, "shiny": 1, "moves":["mist", "aurorabeam", "futuresight", "slash"]}, {"generation": 5, "level": 68, "shiny": 1, "moves":["futuresight", "slash", "moonlight", "psychocut"]}, {"generation": 5, "level": 68, "nature": "Modest", "moves":["icebeam", "psyshock", "energyball", "hiddenpower"]}, {"generation": 6, "level": 50, "shiny": 1, "moves":["mist", "aurorabeam", "futuresight", "slash"]}, ], eventOnly: true, tier: "RU", }, phione: { randomBattleMoves: ["raindance", "scald", "uturn", "rest", "icebeam"], randomDoubleBattleMoves: ["raindance", "scald", "uturn", "rest", "icebeam", "helpinghand", "icywind", "protect"], eventPokemon: [ {"generation": 4, "level": 50, "moves":["grassknot", "raindance", "rest", "surf"], "pokeball": "cherishball"}, ], tier: "PU", }, manaphy: { randomBattleMoves: ["tailglow", "surf", "icebeam", "energyball", "psychic"], randomDoubleBattleMoves: ["tailglow", "surf", "icebeam", "energyball", "protect", "scald", "icywind", "helpinghand"], eventPokemon: [ {"generation": 4, "level": 5, "moves":["tailglow", "bubble", "watersport"]}, {"generation": 4, "level": 1, "shiny": 1, "moves":["tailglow", "bubble", "watersport"]}, {"generation": 4, "level": 50, "moves":["heartswap", "waterpulse", "whirlpool", "acidarmor"], "pokeball": "cherishball"}, {"generation": 4, "level": 50, "nature": "Impish", "moves":["aquaring", "waterpulse", "watersport", "heartswap"], "pokeball": "cherishball"}, {"generation": 6, "level": 1, "moves":["tailglow", "bubble", "watersport", "heartswap"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "moves":["tailglow", "bubble", "watersport"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "OU", }, darkrai: { randomBattleMoves: ["hypnosis", "darkpulse", "focusblast", "nastyplot", "substitute", "sludgebomb"], randomDoubleBattleMoves: ["darkpulse", "focusblast", "nastyplot", "substitute", "snarl", "icebeam", "protect"], eventPokemon: [ {"generation": 4, "level": 40, "shiny": 1, "moves":["quickattack", "hypnosis", "pursuit", "nightmare"]}, {"generation": 4, "level": 50, "moves":["roaroftime", "spacialrend", "nightmare", "hypnosis"], "pokeball": "cherishball"}, {"generation": 4, "level": 50, "moves":["darkvoid", "darkpulse", "shadowball", "doubleteam"]}, {"generation": 4, "level": 50, "shiny": 1, "moves":["hypnosis", "feintattack", "nightmare", "doubleteam"]}, {"generation": 5, "level": 50, "moves":["darkvoid", "ominouswind", "feintattack", "nightmare"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "moves":["darkvoid", "darkpulse", "phantomforce", "dreameater"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "moves":["darkvoid", "ominouswind", "nightmare", "feintattack"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "Uber", }, shaymin: { randomBattleMoves: ["seedflare", "earthpower", "airslash", "psychic", "rest", "substitute", "leechseed"], randomDoubleBattleMoves: ["seedflare", "earthpower", "airslash", "hiddenpowerfire", "rest", "substitute", "leechseed", "tailwind", "protect"], eventPokemon: [ {"generation": 4, "level": 50, "moves":["seedflare", "aromatherapy", "substitute", "energyball"], "pokeball": "cherishball"}, {"generation": 4, "level": 30, "shiny": 1, "moves":["growth", "magicalleaf", "leechseed", "synthesis"]}, {"generation": 5, "level": 50, "moves":["seedflare", "leechseed", "synthesis", "sweetscent"], "pokeball": "cherishball"}, {"generation": 6, "level": 15, "moves":["growth", "magicalleaf", "seedflare", "airslash"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "moves":["seedflare", "aromatherapy", "substitute", "energyball"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "RU", }, shayminsky: { randomBattleMoves: ["seedflare", "earthpower", "airslash", "hiddenpowerfire", "substitute", "leechseed", "healingwish"], randomDoubleBattleMoves: ["seedflare", "earthpower", "airslash", "hiddenpowerfire", "rest", "substitute", "leechseed", "tailwind", "protect", "hiddenpowerice"], eventOnly: true, tier: "Uber", }, arceus: { randomBattleMoves: ["swordsdance", "extremespeed", "shadowclaw", "earthquake", "recover"], randomDoubleBattleMoves: ["swordsdance", "extremespeed", "shadowclaw", "earthquake", "recover", "protect"], eventPokemon: [ {"generation": 4, "level": 100, "moves":["judgment", "roaroftime", "spacialrend", "shadowforce"], "pokeball": "cherishball"}, {"generation": 5, "level": 100, "moves":["recover", "hyperbeam", "perishsong", "judgment"]}, {"generation": 6, "level": 100, "shiny": 1, "moves":["judgment", "blastburn", "hydrocannon", "earthpower"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "moves":["judgment", "perishsong", "hyperbeam", "recover"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "Uber", }, arceusbug: { randomBattleMoves: ["swordsdance", "xscissor", "stoneedge", "recover", "earthquake", "ironhead"], randomDoubleBattleMoves: ["swordsdance", "xscissor", "stoneedge", "recover", "earthquake", "ironhead", "protect"], eventOnly: true, requiredItems: ["Insect Plate", "Buginium Z"], }, arceusdark: { randomBattleMoves: ["calmmind", "judgment", "recover", "fireblast", "thunderbolt"], randomDoubleBattleMoves: ["calmmind", "judgment", "recover", "focusblast", "safeguard", "snarl", "willowisp", "protect"], eventOnly: true, requiredItems: ["Dread Plate", "Darkinium Z"], }, arceusdragon: { randomBattleMoves: ["swordsdance", "outrage", "extremespeed", "earthquake", "recover", "calmmind", "judgment", "fireblast", "earthpower"], randomDoubleBattleMoves: ["swordsdance", "dragonclaw", "extremespeed", "earthquake", "recover", "protect"], eventOnly: true, requiredItems: ["Draco Plate", "Dragonium Z"], }, arceuselectric: { randomBattleMoves: ["calmmind", "judgment", "recover", "icebeam", "grassknot", "fireblast", "willowisp"], randomDoubleBattleMoves: ["calmmind", "judgment", "recover", "icebeam", "protect"], eventOnly: true, requiredItems: ["Zap Plate", "Electrium Z"], }, arceusfairy: { randomBattleMoves: ["calmmind", "judgment", "recover", "willowisp", "defog", "thunderbolt", "toxic", "fireblast"], randomDoubleBattleMoves: ["calmmind", "judgment", "recover", "willowisp", "protect", "earthpower", "thunderbolt"], eventOnly: true, requiredItems: ["Pixie Plate", "Fairium Z"], }, arceusfighting: { randomBattleMoves: ["calmmind", "judgment", "stoneedge", "shadowball", "recover", "toxic", "defog"], randomDoubleBattleMoves: ["calmmind", "judgment", "icebeam", "shadowball", "recover", "willowisp", "protect"], eventOnly: true, requiredItems: ["Fist Plate", "Fightinium Z"], }, arceusfire: { randomBattleMoves: ["calmmind", "judgment", "grassknot", "thunderbolt", "icebeam", "recover"], randomDoubleBattleMoves: ["calmmind", "judgment", "thunderbolt", "recover", "heatwave", "protect", "willowisp"], eventOnly: true, requiredItems: ["Flame Plate", "Firium Z"], }, arceusflying: { randomBattleMoves: ["calmmind", "judgment", "earthpower", "fireblast", "substitute", "recover"], randomDoubleBattleMoves: ["calmmind", "judgment", "safeguard", "recover", "substitute", "tailwind", "protect"], eventOnly: true, requiredItems: ["Sky Plate", "Flyinium Z"], }, arceusghost: { randomBattleMoves: ["calmmind", "judgment", "focusblast", "recover", "swordsdance", "shadowforce", "brickbreak", "willowisp", "roar", "defog"], randomDoubleBattleMoves: ["calmmind", "judgment", "focusblast", "recover", "swordsdance", "shadowforce", "brickbreak", "willowisp", "protect"], eventOnly: true, requiredItems: ["Spooky Plate", "Ghostium Z"], }, arceusgrass: { randomBattleMoves: ["judgment", "recover", "calmmind", "icebeam", "fireblast"], randomDoubleBattleMoves: ["calmmind", "icebeam", "judgment", "earthpower", "recover", "safeguard", "thunderwave", "protect"], eventOnly: true, requiredItems: ["Meadow Plate", "Grassium Z"], }, arceusground: { randomBattleMoves: ["swordsdance", "earthquake", "stoneedge", "recover", "extremespeed", "icebeam"], randomDoubleBattleMoves: ["swordsdance", "earthquake", "stoneedge", "recover", "calmmind", "judgment", "icebeam", "rockslide", "protect"], eventOnly: true, requiredItems: ["Earth Plate", "Groundium Z"], }, arceusice: { randomBattleMoves: ["calmmind", "judgment", "thunderbolt", "fireblast", "recover"], randomDoubleBattleMoves: ["calmmind", "judgment", "thunderbolt", "focusblast", "recover", "protect", "icywind"], eventOnly: true, requiredItems: ["Icicle Plate", "Icium Z"], }, arceuspoison: { randomBattleMoves: ["calmmind", "sludgebomb", "fireblast", "recover", "willowisp", "defog", "thunderwave"], randomDoubleBattleMoves: ["calmmind", "judgment", "sludgebomb", "heatwave", "recover", "willowisp", "protect", "earthpower"], eventOnly: true, requiredItems: ["Toxic Plate", "Poisonium Z"], }, arceuspsychic: { randomBattleMoves: ["judgment", "calmmind", "focusblast", "recover", "defog", "thunderbolt", "willowisp"], randomDoubleBattleMoves: ["calmmind", "psyshock", "focusblast", "recover", "willowisp", "judgment", "protect"], eventOnly: true, requiredItems: ["Mind Plate", "Psychium Z"], }, arceusrock: { randomBattleMoves: ["recover", "swordsdance", "earthquake", "stoneedge", "extremespeed"], randomDoubleBattleMoves: ["swordsdance", "stoneedge", "recover", "rockslide", "earthquake", "protect"], eventOnly: true, requiredItems: ["Stone Plate", "Rockium Z"], }, arceussteel: { randomBattleMoves: ["calmmind", "judgment", "recover", "willowisp", "thunderbolt", "swordsdance", "ironhead", "earthquake", "stoneedge"], randomDoubleBattleMoves: ["calmmind", "judgment", "recover", "protect", "willowisp"], eventOnly: true, requiredItems: ["Iron Plate", "Steelium Z"], }, arceuswater: { randomBattleMoves: ["recover", "calmmind", "judgment", "substitute", "willowisp", "thunderbolt"], randomDoubleBattleMoves: ["recover", "calmmind", "judgment", "icebeam", "fireblast", "icywind", "surf", "protect"], eventOnly: true, requiredItems: ["Splash Plate", "Waterium Z"], }, victini: { randomBattleMoves: ["vcreate", "boltstrike", "uturn", "zenheadbutt", "grassknot", "focusblast", "blueflare"], randomDoubleBattleMoves: ["vcreate", "boltstrike", "uturn", "psychic", "focusblast", "blueflare", "protect"], eventPokemon: [ {"generation": 5, "level": 15, "moves":["quickattack", "incinerate", "confusion", "endure"]}, {"generation": 5, "level": 50, "moves":["vcreate", "fusionflare", "fusionbolt", "searingshot"], "pokeball": "cherishball"}, {"generation": 5, "level": 100, "moves":["vcreate", "blueflare", "boltstrike", "glaciate"], "pokeball": "cherishball"}, {"generation": 6, "level": 15, "moves":["confusion", "quickattack", "vcreate", "searingshot"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "moves":["incinerate", "quickattack", "endure", "confusion"], "pokeball": "cherishball"}, {"generation": 6, "level": 15, "moves":["quickattack", "swagger", "vcreate"], "pokeball": "cherishball"}, {"generation": 7, "level": 15, "moves":["vcreate", "reversal", "storedpower", "celebrate"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "BL", }, snivy: { randomBattleMoves: ["leafstorm", "hiddenpowerfire", "substitute", "leechseed", "hiddenpowerice", "gigadrain"], eventPokemon: [ {"generation": 5, "level": 5, "gender": "M", "nature": "Hardy", "isHidden": false, "moves":["growth", "synthesis", "energyball", "aromatherapy"], "pokeball": "cherishball"}, ], tier: "LC", }, servine: { randomBattleMoves: ["leafstorm", "hiddenpowerfire", "substitute", "leechseed", "hiddenpowerice", "gigadrain"], tier: "NFE", }, serperior: { randomBattleMoves: ["leafstorm", "dragonpulse", "hiddenpowerfire", "substitute", "leechseed", "glare"], randomDoubleBattleMoves: ["leafstorm", "hiddenpowerfire", "substitute", "taunt", "dragonpulse", "protect"], eventPokemon: [ {"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["leafstorm", "substitute", "gigadrain", "leechseed"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "isHidden": true, "moves":["leafstorm", "holdback", "wringout", "gigadrain"], "pokeball": "cherishball"}, ], tier: "BL", }, tepig: { randomBattleMoves: ["flamecharge", "flareblitz", "wildcharge", "superpower", "headsmash"], tier: "LC", }, pignite: { randomBattleMoves: ["flamecharge", "flareblitz", "wildcharge", "superpower", "headsmash"], tier: "NFE", }, emboar: { randomBattleMoves: ["flareblitz", "superpower", "wildcharge", "stoneedge", "fireblast", "grassknot", "suckerpunch"], randomDoubleBattleMoves: ["flareblitz", "superpower", "flamecharge", "wildcharge", "headsmash", "protect", "heatwave", "rockslide"], eventPokemon: [ {"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["flareblitz", "hammerarm", "wildcharge", "headsmash"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "isHidden": true, "moves":["flareblitz", "holdback", "headsmash", "takedown"], "pokeball": "cherishball"}, ], tier: "NU", }, oshawott: { randomBattleMoves: ["swordsdance", "waterfall", "aquajet", "xscissor"], tier: "LC", }, dewott: { randomBattleMoves: ["swordsdance", "waterfall", "aquajet", "xscissor"], tier: "NFE", }, samurott: { randomBattleMoves: ["swordsdance", "waterfall", "aquajet", "megahorn", "superpower", "hydropump", "icebeam", "grassknot"], randomDoubleBattleMoves: ["hydropump", "aquajet", "icebeam", "scald", "hiddenpowergrass", "taunt", "helpinghand", "protect"], eventPokemon: [ {"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["hydropump", "icebeam", "megahorn", "superpower"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "isHidden": true, "moves":["razorshell", "holdback", "confide", "hydropump"], "pokeball": "cherishball"}, ], tier: "BL4", }, patrat: { randomBattleMoves: ["swordsdance", "batonpass", "substitute", "hypnosis", "return", "superfang"], tier: "LC", }, watchog: { randomBattleMoves: ["hypnosis", "substitute", "batonpass", "superfang", "swordsdance", "return", "knockoff"], randomDoubleBattleMoves: ["swordsdance", "knockoff", "substitute", "hypnosis", "return", "superfang", "protect"], tier: "PU", }, lillipup: { randomBattleMoves: ["return", "wildcharge", "firefang", "crunch", "icefang"], tier: "LC", }, herdier: { randomBattleMoves: ["return", "wildcharge", "firefang", "crunch", "icefang"], tier: "NFE", }, stoutland: { randomBattleMoves: ["return", "crunch", "wildcharge", "superpower", "icefang"], randomDoubleBattleMoves: ["return", "wildcharge", "superpower", "crunch", "icefang", "protect"], tier: "PU", }, purrloin: { randomBattleMoves: ["encore", "taunt", "uturn", "knockoff", "thunderwave"], tier: "LC", }, liepard: { randomBattleMoves: ["knockoff", "encore", "suckerpunch", "thunderwave", "uturn", "substitute", "nastyplot", "darkpulse", "copycat"], randomDoubleBattleMoves: ["encore", "thunderwave", "substitute", "knockoff", "playrough", "uturn", "suckerpunch", "fakeout", "protect"], eventPokemon: [ {"generation": 5, "level": 20, "gender": "F", "nature": "Jolly", "isHidden": true, "moves":["fakeout", "foulplay", "encore", "swagger"]}, ], tier: "PU", }, pansage: { randomBattleMoves: ["leafstorm", "hiddenpowerfire", "hiddenpowerice", "gigadrain", "nastyplot", "substitute", "leechseed"], eventPokemon: [ {"generation": 5, "level": 1, "shiny": 1, "gender": "M", "nature": "Brave", "ivs": {"spa": 31}, "isHidden": false, "moves":["bulletseed", "bite", "solarbeam", "dig"]}, {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["leer", "lick", "vinewhip", "leafstorm"]}, {"generation": 5, "level": 30, "gender": "M", "nature": "Serious", "isHidden": false, "moves":["seedbomb", "solarbeam", "rocktomb", "dig"], "pokeball": "cherishball"}, ], tier: "LC", }, simisage: { randomBattleMoves: ["nastyplot", "gigadrain", "focusblast", "hiddenpowerice", "substitute", "leafstorm", "knockoff", "superpower"], randomDoubleBattleMoves: ["nastyplot", "leafstorm", "hiddenpowerfire", "hiddenpowerice", "gigadrain", "focusblast", "substitute", "taunt", "synthesis", "helpinghand", "protect"], tier: "PU", }, pansear: { randomBattleMoves: ["nastyplot", "fireblast", "hiddenpowerelectric", "hiddenpowerground", "sunnyday", "solarbeam", "overheat"], eventPokemon: [ {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["leer", "lick", "incinerate", "heatwave"]}, ], tier: "LC", }, simisear: { randomBattleMoves: ["substitute", "nastyplot", "fireblast", "focusblast", "grassknot", "hiddenpowerrock"], randomDoubleBattleMoves: ["nastyplot", "fireblast", "focusblast", "grassknot", "hiddenpowerground", "substitute", "heatwave", "taunt", "protect"], eventPokemon: [ {"generation": 6, "level": 5, "perfectIVs": 2, "isHidden": false, "moves":["workup", "honeclaws", "poweruppunch", "gigaimpact"], "pokeball": "cherishball"}, ], tier: "PU", }, panpour: { randomBattleMoves: ["nastyplot", "hydropump", "hiddenpowergrass", "substitute", "surf", "icebeam"], eventPokemon: [ {"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["leer", "lick", "watergun", "hydropump"]}, ], tier: "LC", }, simipour: { randomBattleMoves: ["substitute", "nastyplot", "hydropump", "icebeam", "focusblast"], randomDoubleBattleMoves: ["nastyplot", "hydropump", "icebeam", "substitute", "surf", "taunt", "helpinghand", "protect"], tier: "PU", }, munna: { randomBattleMoves: ["psychic", "hiddenpowerfighting", "hypnosis", "calmmind", "moonlight", "thunderwave", "batonpass", "psyshock", "healbell", "signalbeam"], tier: "LC", }, musharna: { randomBattleMoves: ["calmmind", "psychic", "psyshock", "signalbeam", "batonpass", "moonlight", "healbell", "thunderwave"], randomDoubleBattleMoves: ["trickroom", "thunderwave", "moonlight", "psychic", "hiddenpowerfighting", "helpinghand", "psyshock", "hypnosis", "signalbeam", "protect"], eventPokemon: [ {"generation": 5, "level": 50, "isHidden": true, "moves":["defensecurl", "luckychant", "psybeam", "hypnosis"]}, ], tier: "PU", }, pidove: { randomBattleMoves: ["pluck", "uturn", "return", "detect", "roost", "wish"], eventPokemon: [ {"generation": 5, "level": 1, "shiny": 1, "gender": "F", "nature": "Hardy", "ivs": {"atk": 31}, "isHidden": false, "abilities":["superluck"], "moves":["gust", "quickattack", "aircutter"]}, ], tier: "LC", }, tranquill: { randomBattleMoves: ["pluck", "uturn", "return", "detect", "roost", "wish"], tier: "NFE", }, unfezant: { randomBattleMoves: ["return", "pluck", "hypnosis", "tailwind", "uturn", "roost", "nightslash"], randomDoubleBattleMoves: ["pluck", "uturn", "return", "protect", "tailwind", "taunt", "roost", "nightslash"], tier: "PU", }, blitzle: { randomBattleMoves: ["voltswitch", "hiddenpowergrass", "wildcharge", "mefirst"], tier: "LC", }, zebstrika: { randomBattleMoves: ["voltswitch", "hiddenpowergrass", "overheat", "wildcharge", "thunderbolt"], randomDoubleBattleMoves: ["voltswitch", "hiddenpowergrass", "overheat", "wildcharge", "protect"], tier: "PU", }, roggenrola: { randomBattleMoves: ["autotomize", "stoneedge", "stealthrock", "rockblast", "earthquake", "explosion"], tier: "LC", }, boldore: { randomBattleMoves: ["autotomize", "stoneedge", "stealthrock", "rockblast", "earthquake", "explosion"], tier: "NFE", }, gigalith: { randomBattleMoves: ["stealthrock", "rockblast", "earthquake", "explosion", "stoneedge", "superpower"], randomDoubleBattleMoves: ["stealthrock", "rockslide", "earthquake", "explosion", "stoneedge", "autotomize", "superpower", "wideguard", "protect"], tier: "RU", }, woobat: { randomBattleMoves: ["calmmind", "psychic", "airslash", "gigadrain", "roost", "heatwave", "storedpower"], tier: "LC", }, swoobat: { randomBattleMoves: ["substitute", "calmmind", "storedpower", "heatwave", "psychic", "airslash", "roost"], randomDoubleBattleMoves: ["calmmind", "psychic", "airslash", "gigadrain", "protect", "heatwave", "tailwind"], tier: "PU", }, drilbur: { randomBattleMoves: ["swordsdance", "rapidspin", "earthquake", "rockslide", "shadowclaw", "return", "xscissor"], tier: "LC", }, excadrill: { randomBattleMoves: ["swordsdance", "earthquake", "ironhead", "rockslide", "rapidspin"], randomDoubleBattleMoves: ["swordsdance", "drillrun", "earthquake", "rockslide", "ironhead", "substitute", "protect"], tier: "OU", }, audino: { randomBattleMoves: ["wish", "protect", "healbell", "toxic", "thunderwave", "reflect", "lightscreen", "doubleedge"], randomDoubleBattleMoves: ["healpulse", "protect", "healbell", "trickroom", "thunderwave", "reflect", "lightscreen", "doubleedge", "helpinghand", "hypervoice"], eventPokemon: [ {"generation": 5, "level": 30, "gender": "F", "nature": "Calm", "isHidden": false, "abilities":["healer"], "moves":["healpulse", "helpinghand", "refresh", "doubleslap"], "pokeball": "cherishball"}, {"generation": 5, "level": 30, "gender": "F", "nature": "Serious", "isHidden": false, "abilities":["healer"], "moves":["healpulse", "helpinghand", "refresh", "present"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "nature": "Relaxed", "isHidden": false, "abilities":["regenerator"], "moves":["trickroom", "healpulse", "simplebeam", "thunderbolt"], "pokeball": "cherishball"}, ], tier: "PU", }, audinomega: { randomBattleMoves: ["wish", "calmmind", "healbell", "dazzlinggleam", "hypervoice", "protect", "fireblast"], randomDoubleBattleMoves: ["healpulse", "protect", "healbell", "trickroom", "thunderwave", "hypervoice", "helpinghand", "dazzlinggleam"], requiredItem: "Audinite", tier: "NU", }, timburr: { randomBattleMoves: ["machpunch", "bulkup", "drainpunch", "icepunch", "knockoff"], tier: "LC", }, gurdurr: { randomBattleMoves: ["bulkup", "machpunch", "drainpunch", "icepunch", "knockoff"], tier: "NFE", }, conkeldurr: { randomBattleMoves: ["bulkup", "drainpunch", "icepunch", "knockoff", "machpunch"], randomDoubleBattleMoves: ["wideguard", "machpunch", "drainpunch", "icepunch", "knockoff", "protect"], tier: "BL", }, tympole: { randomBattleMoves: ["hydropump", "surf", "sludgewave", "earthpower", "hiddenpowerelectric"], tier: "LC", }, palpitoad: { randomBattleMoves: ["hydropump", "surf", "sludgewave", "earthpower", "hiddenpowerelectric", "stealthrock"], tier: "NFE", }, seismitoad: { randomBattleMoves: ["hydropump", "scald", "sludgewave", "earthquake", "knockoff", "stealthrock", "toxic", "raindance"], randomDoubleBattleMoves: ["hydropump", "muddywater", "sludgebomb", "earthquake", "hiddenpowerelectric", "icywind", "protect"], tier: "NU", }, throh: { randomBattleMoves: ["bulkup", "circlethrow", "icepunch", "stormthrow", "rest", "sleeptalk", "knockoff"], randomDoubleBattleMoves: ["helpinghand", "circlethrow", "icepunch", "stormthrow", "wideguard", "knockoff", "protect"], tier: "PU", }, sawk: { randomBattleMoves: ["closecombat", "earthquake", "icepunch", "poisonjab", "bulkup", "knockoff"], randomDoubleBattleMoves: ["closecombat", "knockoff", "icepunch", "rockslide", "protect"], tier: "BL4", }, sewaddle: { randomBattleMoves: ["calmmind", "gigadrain", "bugbuzz", "hiddenpowerfire", "hiddenpowerice", "airslash"], tier: "LC", }, swadloon: { randomBattleMoves: ["calmmind", "gigadrain", "bugbuzz", "hiddenpowerfire", "hiddenpowerice", "airslash", "stickyweb"], tier: "NFE", }, leavanny: { randomBattleMoves: ["stickyweb", "swordsdance", "leafblade", "xscissor", "knockoff", "batonpass"], randomDoubleBattleMoves: ["swordsdance", "leafblade", "xscissor", "protect", "stickyweb", "poisonjab"], tier: "PU", }, venipede: { randomBattleMoves: ["toxicspikes", "infestation", "spikes", "endeavor", "protect"], tier: "LC", }, whirlipede: { randomBattleMoves: ["toxicspikes", "infestation", "spikes", "endeavor", "protect"], tier: "NFE", }, scolipede: { randomBattleMoves: ["substitute", "spikes", "toxicspikes", "megahorn", "rockslide", "earthquake", "swordsdance", "batonpass", "poisonjab"], randomDoubleBattleMoves: ["substitute", "protect", "megahorn", "rockslide", "poisonjab", "swordsdance", "batonpass", "aquatail", "superpower"], tier: "BL", }, cottonee: { randomBattleMoves: ["encore", "taunt", "substitute", "leechseed", "toxic", "stunspore"], tier: "LC", }, whimsicott: { randomBattleMoves: ["encore", "taunt", "substitute", "leechseed", "uturn", "toxic", "stunspore", "memento", "tailwind", "moonblast"], randomDoubleBattleMoves: ["encore", "taunt", "substitute", "leechseed", "uturn", "helpinghand", "stunspore", "moonblast", "tailwind", "dazzlinggleam", "gigadrain", "protect"], eventPokemon: [ {"generation": 5, "level": 50, "gender": "F", "nature": "Timid", "ivs": {"spe": 31}, "isHidden": false, "abilities":["prankster"], "moves":["swagger", "gigadrain", "beatup", "helpinghand"], "pokeball": "cherishball"}, ], tier: "NU", }, petilil: { randomBattleMoves: ["sunnyday", "sleeppowder", "solarbeam", "hiddenpowerfire", "hiddenpowerice", "healingwish"], tier: "LC", }, lilligant: { randomBattleMoves: ["sleeppowder", "quiverdance", "petaldance", "gigadrain", "hiddenpowerfire", "hiddenpowerrock"], randomDoubleBattleMoves: ["quiverdance", "gigadrain", "sleeppowder", "hiddenpowerice", "hiddenpowerfire", "hiddenpowerrock", "petaldance", "helpinghand", "protect"], tier: "PU", }, basculin: { randomBattleMoves: ["waterfall", "aquajet", "superpower", "crunch", "headsmash"], randomDoubleBattleMoves: ["waterfall", "aquajet", "superpower", "crunch", "doubleedge", "protect"], tier: "PU", }, basculinbluestriped: { randomBattleMoves: ["waterfall", "aquajet", "superpower", "crunch", "headsmash"], randomDoubleBattleMoves: ["waterfall", "aquajet", "superpower", "crunch", "doubleedge", "protect"], tier: "PU", }, sandile: { randomBattleMoves: ["earthquake", "stoneedge", "pursuit", "crunch"], tier: "LC", }, krokorok: { randomBattleMoves: ["earthquake", "stoneedge", "pursuit", "crunch"], tier: "NFE", }, krookodile: { randomBattleMoves: ["earthquake", "stoneedge", "pursuit", "knockoff", "stealthrock", "superpower"], randomDoubleBattleMoves: ["earthquake", "stoneedge", "protect", "knockoff", "superpower"], tier: "UU", }, darumaka: { randomBattleMoves: ["uturn", "flareblitz", "firepunch", "rockslide", "superpower"], tier: "LC", }, darmanitan: { randomBattleMoves: ["uturn", "flareblitz", "rockslide", "earthquake", "superpower"], randomDoubleBattleMoves: ["uturn", "flareblitz", "firepunch", "rockslide", "earthquake", "superpower", "protect"], eventPokemon: [ {"generation": 5, "level": 35, "isHidden": true, "moves":["thrash", "bellydrum", "flareblitz", "hammerarm"]}, {"generation": 6, "level": 35, "gender": "M", "nature": "Calm", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": true, "moves":["thrash", "bellydrum", "flareblitz", "hammerarm"], "pokeball": "cherishball"}, ], tier: "UU", }, darmanitanzen: { requiredAbility: "Zen Mode", battleOnly: true, }, maractus: { randomBattleMoves: ["spikes", "gigadrain", "leechseed", "hiddenpowerfire", "toxic", "suckerpunch", "spikyshield"], randomDoubleBattleMoves: ["grassyterrain", "gigadrain", "leechseed", "hiddenpowerfire", "helpinghand", "suckerpunch", "spikyshield"], tier: "PU", }, dwebble: { randomBattleMoves: ["stealthrock", "spikes", "shellsmash", "earthquake", "rockblast", "xscissor", "stoneedge"], tier: "LC", }, crustle: { randomBattleMoves: ["stealthrock", "spikes", "shellsmash", "earthquake", "rockblast", "xscissor", "stoneedge"], randomDoubleBattleMoves: ["protect", "shellsmash", "earthquake", "rockslide", "xscissor", "stoneedge"], tier: "PU", }, scraggy: { randomBattleMoves: ["dragondance", "icepunch", "highjumpkick", "drainpunch", "rest", "bulkup", "crunch", "knockoff"], eventPokemon: [ {"generation": 5, "level": 1, "gender": "M", "nature": "Adamant", "isHidden": false, "abilities":["moxie"], "moves":["headbutt", "leer", "highjumpkick", "lowkick"], "pokeball": "cherishball"}, ], tier: "LC", }, scrafty: { randomBattleMoves: ["dragondance", "icepunch", "highjumpkick", "drainpunch", "rest", "bulkup", "knockoff"], randomDoubleBattleMoves: ["fakeout", "drainpunch", "knockoff", "icepunch", "stoneedge", "protect"], eventPokemon: [ {"generation": 5, "level": 50, "gender": "M", "nature": "Brave", "isHidden": false, "abilities":["moxie"], "moves":["firepunch", "payback", "drainpunch", "substitute"], "pokeball": "cherishball"}, ], tier: "NU", }, sigilyph: { randomBattleMoves: ["cosmicpower", "roost", "storedpower", "psychoshift"], randomDoubleBattleMoves: ["psyshock", "heatwave", "icebeam", "airslash", "energyball", "shadowball", "tailwind", "protect"], tier: "NU", }, yamask: { randomBattleMoves: ["nastyplot", "trickroom", "shadowball", "hiddenpowerfighting", "willowisp", "haze", "rest", "sleeptalk", "painsplit"], tier: "LC", }, cofagrigus: { randomBattleMoves: ["nastyplot", "trickroom", "shadowball", "hiddenpowerfighting", "willowisp", "haze", "painsplit"], randomDoubleBattleMoves: ["nastyplot", "trickroom", "shadowball", "hiddenpowerfighting", "willowisp", "protect", "painsplit"], tier: "BL3", }, tirtouga: { randomBattleMoves: ["shellsmash", "aquajet", "waterfall", "stoneedge", "earthquake", "stealthrock"], eventPokemon: [ {"generation": 5, "level": 15, "gender": "M", "isHidden": false, "abilities":["sturdy"], "moves":["bite", "protect", "aquajet", "bodyslam"], "pokeball": "cherishball"}, ], tier: "LC", }, carracosta: { randomBattleMoves: ["shellsmash", "aquajet", "liquidation", "stoneedge", "earthquake", "stealthrock"], randomDoubleBattleMoves: ["shellsmash", "aquajet", "waterfall", "stoneedge", "earthquake", "protect", "wideguard", "rockslide"], tier: "PU", }, archen: { randomBattleMoves: ["stoneedge", "rockslide", "earthquake", "uturn", "pluck", "headsmash"], eventPokemon: [ {"generation": 5, "level": 15, "gender": "M", "moves":["headsmash", "wingattack", "doubleteam", "scaryface"], "pokeball": "cherishball"}, ], tier: "LC", }, archeops: { randomBattleMoves: ["headsmash", "acrobatics", "stoneedge", "earthquake", "aquatail", "uturn", "tailwind"], randomDoubleBattleMoves: ["stoneedge", "rockslide", "earthquake", "uturn", "acrobatics", "tailwind", "taunt", "protect"], tier: "PU", }, trubbish: { randomBattleMoves: ["clearsmog", "toxicspikes", "spikes", "gunkshot", "painsplit", "toxic"], tier: "LC", }, garbodor: { randomBattleMoves: ["spikes", "toxicspikes", "gunkshot", "haze", "painsplit", "toxic", "drainpunch"], randomDoubleBattleMoves: ["protect", "painsplit", "gunkshot", "seedbomb", "drainpunch", "explosion", "rockblast"], tier: "NU", }, zorua: { randomBattleMoves: ["suckerpunch", "extrasensory", "darkpulse", "hiddenpowerfighting", "uturn", "knockoff"], tier: "LC", }, zoroark: { randomBattleMoves: ["suckerpunch", "darkpulse", "focusblast", "flamethrower", "uturn", "nastyplot", "knockoff", "trick", "sludgebomb"], randomDoubleBattleMoves: ["suckerpunch", "darkpulse", "focusblast", "flamethrower", "uturn", "nastyplot", "knockoff", "protect"], eventPokemon: [ {"generation": 5, "level": 50, "gender": "M", "nature": "Quirky", "moves":["agility", "embargo", "punishment", "snarl"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "moves":["sludgebomb", "darkpulse", "flamethrower", "suckerpunch"], "pokeball": "ultraball"}, ], tier: "RU", }, minccino: { randomBattleMoves: ["return", "tailslap", "wakeupslap", "uturn", "aquatail"], tier: "LC", }, cinccino: { randomBattleMoves: ["tailslap", "aquatail", "uturn", "knockoff", "bulletseed", "rockblast"], randomDoubleBattleMoves: ["tailslap", "aquatail", "uturn", "knockoff", "bulletseed", "rockblast", "protect"], tier: "NU", }, gothita: { randomBattleMoves: ["psychic", "thunderbolt", "hiddenpowerfighting", "shadowball", "substitute", "calmmind", "trick", "grassknot"], tier: "LC Uber", }, gothorita: { randomBattleMoves: ["psychic", "psyshock", "thunderbolt", "hiddenpowerfighting", "shadowball", "substitute", "calmmind", "trick", "grassknot"], eventPokemon: [ {"generation": 5, "level": 32, "gender": "M", "isHidden": true, "moves":["psyshock", "flatter", "futuresight", "mirrorcoat"]}, {"generation": 5, "level": 32, "gender": "M", "isHidden": true, "moves":["psyshock", "flatter", "futuresight", "imprison"]}, ], tier: "NFE", }, gothitelle: { randomBattleMoves: ["psychic", "thunderbolt", "shadowball", "hiddenpowerfire", "hiddenpowerfighting", "substitute", "calmmind", "trick", "psyshock"], randomDoubleBattleMoves: ["psychic", "thunderbolt", "shadowball", "hiddenpowerfighting", "reflect", "lightscreen", "psyshock", "energyball", "trickroom", "taunt", "healpulse", "protect"], tier: "PU", }, solosis: { randomBattleMoves: ["calmmind", "recover", "psychic", "hiddenpowerfighting", "shadowball", "trickroom", "psyshock"], tier: "LC", }, duosion: { randomBattleMoves: ["calmmind", "recover", "psychic", "hiddenpowerfighting", "shadowball", "trickroom", "psyshock"], tier: "NFE", }, reuniclus: { randomBattleMoves: ["calmmind", "recover", "psychic", "focusblast", "shadowball", "trickroom", "psyshock"], randomDoubleBattleMoves: ["energyball", "helpinghand", "psychic", "focusblast", "shadowball", "trickroom", "psyshock", "hiddenpowerfire", "protect"], tier: "BL2", }, ducklett: { randomBattleMoves: ["scald", "airslash", "roost", "hurricane", "icebeam", "hiddenpowergrass", "bravebird", "defog"], tier: "LC", }, swanna: { randomBattleMoves: ["airslash", "roost", "hurricane", "icebeam", "raindance", "defog", "scald"], randomDoubleBattleMoves: ["airslash", "roost", "hurricane", "surf", "icebeam", "raindance", "tailwind", "scald", "protect"], tier: "PU", }, vanillite: { randomBattleMoves: ["icebeam", "explosion", "hiddenpowerelectric", "hiddenpowerfighting", "autotomize"], tier: "LC", }, vanillish: { randomBattleMoves: ["icebeam", "explosion", "hiddenpowerelectric", "hiddenpowerfighting", "autotomize"], tier: "NFE", }, vanilluxe: { randomBattleMoves: ["blizzard", "explosion", "hiddenpowerground", "flashcannon", "autotomize", "freezedry"], randomDoubleBattleMoves: ["blizzard", "taunt", "hiddenpowerground", "flashcannon", "autotomize", "protect", "freezedry"], tier: "NU", }, deerling: { randomBattleMoves: ["agility", "batonpass", "seedbomb", "jumpkick", "synthesis", "return", "thunderwave"], eventPokemon: [ {"generation": 5, "level": 30, "gender": "F", "isHidden": true, "moves":["feintattack", "takedown", "jumpkick", "aromatherapy"]}, ], tier: "LC", }, sawsbuck: { randomBattleMoves: ["swordsdance", "hornleech", "jumpkick", "return", "substitute", "batonpass"], randomDoubleBattleMoves: ["swordsdance", "hornleech", "jumpkick", "return", "substitute", "synthesis", "protect"], tier: "PU", }, emolga: { randomBattleMoves: ["encore", "chargebeam", "batonpass", "substitute", "thunderbolt", "airslash", "roost"], randomDoubleBattleMoves: ["helpinghand", "tailwind", "encore", "substitute", "thunderbolt", "airslash", "roost", "protect"], tier: "PU", }, karrablast: { randomBattleMoves: ["swordsdance", "megahorn", "return", "substitute"], eventPokemon: [ {"generation": 5, "level": 30, "isHidden": false, "moves":["furyattack", "headbutt", "falseswipe", "bugbuzz"], "pokeball": "cherishball"}, {"generation": 5, "level": 50, "isHidden": false, "moves":["megahorn", "takedown", "xscissor", "flail"], "pokeball": "cherishball"}, ], tier: "LC", }, escavalier: { randomBattleMoves: ["megahorn", "pursuit", "ironhead", "knockoff", "swordsdance", "drillrun"], randomDoubleBattleMoves: ["megahorn", "protect", "ironhead", "knockoff", "swordsdance", "drillrun"], tier: "RU", }, foongus: { randomBattleMoves: ["spore", "stunspore", "gigadrain", "clearsmog", "hiddenpowerfire", "synthesis", "sludgebomb"], tier: "LC", }, amoonguss: { randomBattleMoves: ["spore", "stunspore", "gigadrain", "clearsmog", "hiddenpowerfire", "synthesis", "sludgebomb", "foulplay"], randomDoubleBattleMoves: ["spore", "stunspore", "gigadrain", "ragepowder", "hiddenpowerfire", "synthesis", "sludgebomb", "protect"], tier: "UU", }, frillish: { randomBattleMoves: ["scald", "willowisp", "recover", "toxic", "shadowball", "taunt"], tier: "LC", }, jellicent: { randomBattleMoves: ["scald", "willowisp", "recover", "toxic", "shadowball", "icebeam", "taunt"], randomDoubleBattleMoves: ["scald", "willowisp", "recover", "trickroom", "shadowball", "icebeam", "waterspout", "icywind", "protect"], eventPokemon: [ {"generation": 5, "level": 40, "isHidden": true, "moves":["waterpulse", "ominouswind", "brine", "raindance"]}, ], tier: "NU", }, alomomola: { randomBattleMoves: ["wish", "protect", "knockoff", "toxic", "scald"], randomDoubleBattleMoves: ["wish", "protect", "knockoff", "icywind", "scald", "helpinghand", "wideguard"], tier: "UU", }, joltik: { randomBattleMoves: ["thunderbolt", "bugbuzz", "hiddenpowerice", "gigadrain", "voltswitch"], tier: "LC", }, galvantula: { randomBattleMoves: ["thunder", "hiddenpowerice", "gigadrain", "bugbuzz", "voltswitch", "stickyweb"], randomDoubleBattleMoves: ["thunder", "hiddenpowerice", "gigadrain", "bugbuzz", "voltswitch", "stickyweb", "protect"], tier: "RU", }, ferroseed: { randomBattleMoves: ["spikes", "stealthrock", "leechseed", "seedbomb", "protect", "thunderwave", "gyroball"], tier: "LC", }, ferrothorn: { randomBattleMoves: ["spikes", "stealthrock", "leechseed", "powerwhip", "protect", "knockoff", "gyroball"], randomDoubleBattleMoves: ["gyroball", "stealthrock", "leechseed", "powerwhip", "knockoff", "protect"], tier: "OU", }, klink: { randomBattleMoves: ["shiftgear", "return", "geargrind", "wildcharge", "substitute"], tier: "LC", }, klang: { randomBattleMoves: ["shiftgear", "return", "geargrind", "wildcharge", "substitute"], tier: "NFE", }, klinklang: { randomBattleMoves: ["shiftgear", "return", "geargrind", "wildcharge", "substitute"], randomDoubleBattleMoves: ["shiftgear", "return", "geargrind", "wildcharge", "protect"], tier: "BL4", }, tynamo: { randomBattleMoves: ["spark", "chargebeam", "thunderwave", "tackle"], tier: "LC", }, eelektrik: { randomBattleMoves: ["uturn", "voltswitch", "acidspray", "wildcharge", "thunderbolt", "gigadrain", "aquatail", "coil"], tier: "NFE", }, eelektross: { randomBattleMoves: ["thunderbolt", "flamethrower", "uturn", "voltswitch", "acidspray", "gigadrain", "knockoff", "superpower", "aquatail"], randomDoubleBattleMoves: ["thunderbolt", "flamethrower", "uturn", "voltswitch", "knockoff", "gigadrain", "protect"], tier: "PU", }, elgyem: { randomBattleMoves: ["nastyplot", "psychic", "thunderbolt", "hiddenpowerfighting", "recover", "trickroom", "signalbeam"], tier: "LC", }, beheeyem: { randomBattleMoves: ["nastyplot", "psychic", "psyshock", "thunderbolt", "hiddenpowerfighting", "trick", "trickroom", "signalbeam"], randomDoubleBattleMoves: ["nastyplot", "psychic", "thunderbolt", "hiddenpowerfighting", "recover", "trick", "trickroom", "signalbeam", "protect"], tier: "PU", }, litwick: { randomBattleMoves: ["shadowball", "energyball", "fireblast", "hiddenpowerground", "trickroom", "substitute", "painsplit"], tier: "LC", }, lampent: { randomBattleMoves: ["calmmind", "shadowball", "energyball", "fireblast", "hiddenpowerground", "substitute", "painsplit"], tier: "NFE", }, chandelure: { randomBattleMoves: ["calmmind", "shadowball", "energyball", "fireblast", "hiddenpowerground", "trick", "substitute", "painsplit"], randomDoubleBattleMoves: ["shadowball", "energyball", "overheat", "heatwave", "hiddenpowerice", "trick", "protect"], eventPokemon: [ {"generation": 5, "level": 50, "gender": "F", "nature": "Modest", "ivs": {"spa": 31}, "isHidden": false, "abilities":["flashfire"], "moves":["heatwave", "shadowball", "energyball", "psychic"], "pokeball": "cherishball"}, ], tier: "UU", }, axew: { randomBattleMoves: ["dragondance", "outrage", "dragonclaw", "swordsdance", "aquatail", "superpower", "poisonjab", "taunt", "substitute"], eventPokemon: [ {"generation": 5, "level": 1, "shiny": 1, "gender": "M", "nature": "Naive", "ivs": {"spe": 31}, "isHidden": false, "abilities":["moldbreaker"], "moves":["scratch", "dragonrage"]}, {"generation": 5, "level": 10, "gender": "F", "isHidden": false, "abilities":["moldbreaker"], "moves":["dragonrage", "return", "endure", "dragonclaw"], "pokeball": "cherishball"}, {"generation": 5, "level": 30, "gender": "M", "nature": "Naive", "isHidden": false, "abilities":["rivalry"], "moves":["dragonrage", "scratch", "outrage", "gigaimpact"], "pokeball": "cherishball"}, ], tier: "LC", }, fraxure: { randomBattleMoves: ["dragondance", "swordsdance", "outrage", "dragonclaw", "aquatail", "superpower", "poisonjab", "taunt", "substitute"], tier: "NFE", }, haxorus: { randomBattleMoves: ["dragondance", "swordsdance", "outrage", "dragonclaw", "earthquake", "poisonjab", "taunt", "substitute"], randomDoubleBattleMoves: ["dragondance", "swordsdance", "protect", "dragonclaw", "earthquake", "poisonjab", "taunt", "substitute"], eventPokemon: [ {"generation": 5, "level": 59, "gender": "F", "nature": "Naive", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "abilities":["moldbreaker"], "moves":["earthquake", "dualchop", "xscissor", "dragondance"], "pokeball": "cherishball"}, ], tier: "UU", }, cubchoo: { randomBattleMoves: ["icebeam", "surf", "hiddenpowergrass", "superpower"], eventPokemon: [ {"generation": 5, "level": 15, "isHidden": false, "moves":["powdersnow", "growl", "bide", "icywind"], "pokeball": "cherishball"}, ], tier: "LC", }, beartic: { randomBattleMoves: ["iciclecrash", "superpower", "nightslash", "stoneedge", "swordsdance", "aquajet"], randomDoubleBattleMoves: ["iciclecrash", "superpower", "nightslash", "stoneedge", "swordsdance", "aquajet", "protect"], tier: "PU", }, cryogonal: { randomBattleMoves: ["icebeam", "recover", "toxic", "rapidspin", "haze", "freezedry", "hiddenpowerground"], randomDoubleBattleMoves: ["icebeam", "recover", "icywind", "protect", "reflect", "freezedry", "hiddenpowerground"], tier: "NU", }, shelmet: { randomBattleMoves: ["spikes", "yawn", "substitute", "acidarmor", "batonpass", "recover", "toxic", "bugbuzz", "infestation"], eventPokemon: [ {"generation": 5, "level": 30, "isHidden": false, "moves":["strugglebug", "megadrain", "yawn", "protect"], "pokeball": "cherishball"}, {"generation": 5, "level": 50, "isHidden": false, "moves":["encore", "gigadrain", "bodyslam", "bugbuzz"], "pokeball": "cherishball"}, ], tier: "LC", }, accelgor: { randomBattleMoves: ["spikes", "yawn", "bugbuzz", "focusblast", "gigadrain", "hiddenpowerrock", "encore"], randomDoubleBattleMoves: ["protect", "yawn", "bugbuzz", "focusblast", "gigadrain", "hiddenpowerrock", "encore", "sludgebomb"], tier: "NU", }, stunfisk: { randomBattleMoves: ["discharge", "earthpower", "scald", "toxic", "rest", "sleeptalk", "stealthrock"], randomDoubleBattleMoves: ["discharge", "earthpower", "scald", "electroweb", "protect", "stealthrock"], tier: "PU", }, mienfoo: { randomBattleMoves: ["uturn", "drainpunch", "stoneedge", "swordsdance", "batonpass", "highjumpkick", "fakeout", "knockoff"], tier: "LC", }, mienshao: { randomBattleMoves: ["uturn", "fakeout", "highjumpkick", "stoneedge", "substitute", "swordsdance", "batonpass", "knockoff"], randomDoubleBattleMoves: ["uturn", "fakeout", "highjumpkick", "stoneedge", "drainpunch", "swordsdance", "wideguard", "knockoff", "feint", "protect"], tier: "UU", }, druddigon: { randomBattleMoves: ["outrage", "earthquake", "suckerpunch", "dragonclaw", "dragontail", "substitute", "glare", "stealthrock", "firepunch", "gunkshot"], randomDoubleBattleMoves: ["superpower", "earthquake", "suckerpunch", "dragonclaw", "glare", "protect", "firepunch", "thunderpunch"], eventPokemon: [ {"generation": 5, "level": 1, "shiny": true, "isHidden": false, "moves":["leer", "scratch"]}, ], tier: "NU", }, golett: { randomBattleMoves: ["earthquake", "shadowpunch", "dynamicpunch", "icepunch", "stealthrock", "rockpolish"], tier: "LC", }, golurk: { randomBattleMoves: ["earthquake", "shadowpunch", "dynamicpunch", "icepunch", "stealthrock", "rockpolish"], randomDoubleBattleMoves: ["earthquake", "shadowpunch", "dynamicpunch", "icepunch", "stoneedge", "protect", "rockpolish"], eventPokemon: [ {"generation": 5, "level": 70, "shiny": true, "isHidden": false, "abilities":["ironfist"], "moves":["shadowpunch", "hyperbeam", "gyroball", "hammerarm"], "pokeball": "cherishball"}, ], tier: "PU", }, pawniard: { randomBattleMoves: ["swordsdance", "substitute", "suckerpunch", "ironhead", "brickbreak", "knockoff"], tier: "LC", }, bisharp: { randomBattleMoves: ["swordsdance", "substitute", "suckerpunch", "ironhead", "brickbreak", "knockoff"], randomDoubleBattleMoves: ["swordsdance", "substitute", "suckerpunch", "ironhead", "brickbreak", "knockoff", "protect"], tier: "OU", }, bouffalant: { randomBattleMoves: ["headcharge", "earthquake", "stoneedge", "megahorn", "swordsdance", "superpower"], randomDoubleBattleMoves: ["headcharge", "earthquake", "stoneedge", "megahorn", "swordsdance", "superpower", "protect"], eventPokemon: [ {"generation": 6, "level": 50, "nature": "Adamant", "ivs": {"hp": 31, "atk": 31}, "isHidden": true, "moves":["headcharge", "facade", "earthquake", "rockslide"], "pokeball": "cherishball"}, ], tier: "PU", }, rufflet: { randomBattleMoves: ["bravebird", "rockslide", "return", "uturn", "substitute", "bulkup", "roost"], tier: "LC", }, braviary: { randomBattleMoves: ["bravebird", "superpower", "return", "uturn", "substitute", "rockslide", "bulkup", "roost"], randomDoubleBattleMoves: ["bravebird", "superpower", "return", "uturn", "tailwind", "rockslide", "bulkup", "roost", "skydrop", "protect"], eventPokemon: [ {"generation": 5, "level": 25, "gender": "M", "isHidden": true, "moves":["wingattack", "honeclaws", "scaryface", "aerialace"]}, ], tier: "NU", }, vullaby: { randomBattleMoves: ["knockoff", "roost", "taunt", "whirlwind", "toxic", "defog", "uturn", "bravebird"], tier: "LC", }, mandibuzz: { randomBattleMoves: ["foulplay", "knockoff", "roost", "taunt", "whirlwind", "toxic", "uturn", "bravebird", "defog"], randomDoubleBattleMoves: ["knockoff", "roost", "taunt", "tailwind", "snarl", "uturn", "bravebird", "protect"], eventPokemon: [ {"generation": 5, "level": 25, "gender": "F", "isHidden": true, "moves":["pluck", "nastyplot", "flatter", "feintattack"]}, ], tier: "UU", }, heatmor: { randomBattleMoves: ["fireblast", "suckerpunch", "focusblast", "gigadrain", "knockoff"], randomDoubleBattleMoves: ["fireblast", "suckerpunch", "focusblast", "gigadrain", "heatwave", "protect"], tier: "PU", }, durant: { randomBattleMoves: ["honeclaws", "ironhead", "xscissor", "stoneedge", "batonpass", "superpower"], randomDoubleBattleMoves: ["honeclaws", "ironhead", "xscissor", "rockslide", "protect", "superpower"], tier: "RU", }, deino: { randomBattleMoves: ["outrage", "crunch", "firefang", "dragontail", "thunderwave", "superpower"], eventPokemon: [ {"generation": 5, "level": 1, "shiny": true, "moves":["tackle", "dragonrage"]}, ], tier: "LC", }, zweilous: { randomBattleMoves: ["outrage", "crunch", "headsmash", "dragontail", "superpower", "rest", "sleeptalk"], tier: "NFE", }, hydreigon: { randomBattleMoves: ["uturn", "dracometeor", "dragonpulse", "earthpower", "fireblast", "darkpulse", "roost", "flashcannon", "superpower"], randomDoubleBattleMoves: ["uturn", "dracometeor", "dragonpulse", "earthpower", "fireblast", "darkpulse", "roost", "flashcannon", "superpower", "tailwind", "protect"], eventPokemon: [ {"generation": 5, "level": 70, "shiny": true, "gender": "M", "moves":["hypervoice", "dragonbreath", "flamethrower", "focusblast"], "pokeball": "cherishball"}, {"generation": 6, "level": 52, "gender": "M", "perfectIVs": 2, "moves":["dragonrush", "crunch", "rockslide", "frustration"], "pokeball": "cherishball"}, ], tier: "UU", }, larvesta: { randomBattleMoves: ["flareblitz", "uturn", "wildcharge", "zenheadbutt", "morningsun", "willowisp"], tier: "LC", }, volcarona: { randomBattleMoves: ["quiverdance", "fierydance", "fireblast", "bugbuzz", "roost", "gigadrain", "hiddenpowerice", "hiddenpowerground"], randomDoubleBattleMoves: ["quiverdance", "fierydance", "fireblast", "bugbuzz", "roost", "gigadrain", "hiddenpowerice", "heatwave", "willowisp", "ragepowder", "tailwind", "protect"], eventPokemon: [ {"generation": 5, "level": 35, "isHidden": false, "moves":["stringshot", "leechlife", "gust", "firespin"]}, {"generation": 5, "level": 77, "gender": "M", "nature": "Calm", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "moves":["bugbuzz", "overheat", "hyperbeam", "quiverdance"], "pokeball": "cherishball"}, ], tier: "OU", }, cobalion: { randomBattleMoves: ["closecombat", "ironhead", "swordsdance", "substitute", "stoneedge", "voltswitch", "hiddenpowerice", "taunt", "stealthrock"], randomDoubleBattleMoves: ["closecombat", "ironhead", "swordsdance", "substitute", "stoneedge", "thunderwave", "protect"], eventPokemon: [ {"generation": 5, "level": 42, "shiny": 1, "moves":["helpinghand", "retaliate", "ironhead", "sacredsword"]}, {"generation": 5, "level": 45, "shiny": 1, "moves":["helpinghand", "retaliate", "ironhead", "sacredsword"]}, {"generation": 5, "level": 65, "shiny": 1, "moves":["sacredsword", "swordsdance", "quickguard", "workup"]}, {"generation": 6, "level": 50, "shiny": 1, "moves":["retaliate", "ironhead", "sacredsword", "swordsdance"]}, ], eventOnly: true, tier: "UU", }, terrakion: { randomBattleMoves: ["stoneedge", "closecombat", "swordsdance", "substitute", "stealthrock", "earthquake"], randomDoubleBattleMoves: ["stoneedge", "closecombat", "substitute", "rockslide", "earthquake", "taunt", "protect"], eventPokemon: [ {"generation": 5, "level": 42, "shiny": 1, "moves":["helpinghand", "retaliate", "rockslide", "sacredsword"]}, {"generation": 5, "level": 45, "shiny": 1, "moves":["helpinghand", "retaliate", "rockslide", "sacredsword"]}, {"generation": 5, "level": 65, "shiny": 1, "moves":["sacredsword", "swordsdance", "quickguard", "workup"]}, {"generation": 6, "level": 50, "shiny": 1, "moves":["retaliate", "rockslide", "sacredsword", "swordsdance"]}, ], eventOnly: true, tier: "UU", }, virizion: { randomBattleMoves: ["swordsdance", "closecombat", "leafblade", "stoneedge", "calmmind", "focusblast", "gigadrain", "hiddenpowerice", "substitute"], randomDoubleBattleMoves: ["taunt", "closecombat", "stoneedge", "leafblade", "swordsdance", "synthesis", "protect"], eventPokemon: [ {"generation": 5, "level": 42, "shiny": 1, "moves":["helpinghand", "retaliate", "gigadrain", "sacredsword"]}, {"generation": 5, "level": 45, "shiny": 1, "moves":["helpinghand", "retaliate", "gigadrain", "sacredsword"]}, {"generation": 5, "level": 65, "shiny": 1, "moves":["sacredsword", "swordsdance", "quickguard", "workup"]}, {"generation": 6, "level": 50, "shiny": 1, "moves":["retaliate", "gigadrain", "sacredsword", "swordsdance"]}, ], eventOnly: true, tier: "NU", }, tornadus: { randomBattleMoves: ["bulkup", "acrobatics", "knockoff", "substitute", "hurricane", "heatwave", "superpower", "uturn", "taunt", "tailwind"], randomDoubleBattleMoves: ["hurricane", "airslash", "uturn", "superpower", "focusblast", "taunt", "substitute", "heatwave", "tailwind", "protect", "skydrop"], eventPokemon: [ {"generation": 5, "level": 40, "shiny": 1, "isHidden": false, "moves":["revenge", "aircutter", "extrasensory", "agility"]}, {"generation": 5, "level": 5, "isHidden": true, "moves":["uproar", "astonish", "gust"], "pokeball": "dreamball"}, {"generation": 5, "level": 70, "isHidden": false, "moves":["hurricane", "hammerarm", "airslash", "hiddenpower"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["extrasensory", "agility", "airslash", "crunch"]}, ], eventOnly: true, tier: "BL2", }, tornadustherian: { randomBattleMoves: ["hurricane", "airslash", "heatwave", "knockoff", "superpower", "uturn", "taunt"], randomDoubleBattleMoves: ["hurricane", "airslash", "focusblast", "uturn", "heatwave", "skydrop", "tailwind", "taunt", "protect"], eventOnly: true, tier: "BL", }, thundurus: { randomBattleMoves: ["thunderwave", "nastyplot", "thunderbolt", "hiddenpowerice", "hiddenpowerflying", "focusblast", "substitute", "knockoff", "taunt"], randomDoubleBattleMoves: ["thunderwave", "nastyplot", "thunderbolt", "hiddenpowerice", "hiddenpowerflying", "focusblast", "substitute", "knockoff", "taunt", "protect"], eventPokemon: [ {"generation": 5, "level": 40, "shiny": 1, "isHidden": false, "moves":["revenge", "shockwave", "healblock", "agility"]}, {"generation": 5, "level": 5, "isHidden": true, "moves":["uproar", "astonish", "thundershock"], "pokeball": "dreamball"}, {"generation": 5, "level": 70, "isHidden": false, "moves":["thunder", "hammerarm", "focusblast", "wildcharge"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["healblock", "agility", "discharge", "crunch"]}, ], eventOnly: true, tier: "BL", }, thundurustherian: { randomBattleMoves: ["nastyplot", "thunderbolt", "hiddenpowerflying", "hiddenpowerice", "focusblast", "voltswitch"], randomDoubleBattleMoves: ["nastyplot", "thunderbolt", "hiddenpowerflying", "hiddenpowerice", "focusblast", "voltswitch", "protect"], eventOnly: true, tier: "BL", }, reshiram: { randomBattleMoves: ["blueflare", "dracometeor", "dragonpulse", "toxic", "flamecharge", "stoneedge", "roost"], randomDoubleBattleMoves: ["blueflare", "dracometeor", "dragonpulse", "heatwave", "flamecharge", "roost", "protect", "tailwind"], eventPokemon: [ {"generation": 5, "level": 50, "moves":["dragonbreath", "slash", "extrasensory", "fusionflare"]}, {"generation": 5, "level": 70, "moves":["extrasensory", "fusionflare", "dragonpulse", "imprison"]}, {"generation": 5, "level": 100, "moves":["blueflare", "fusionflare", "mist", "dracometeor"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "shiny": 1, "moves":["dragonbreath", "slash", "extrasensory", "fusionflare"]}, ], eventOnly: true, tier: "Uber", }, zekrom: { randomBattleMoves: ["boltstrike", "outrage", "dragonclaw", "dracometeor", "voltswitch", "honeclaws", "substitute", "roost"], randomDoubleBattleMoves: ["voltswitch", "protect", "dragonclaw", "boltstrike", "honeclaws", "substitute", "dracometeor", "fusionbolt", "roost", "tailwind"], eventPokemon: [ {"generation": 5, "level": 50, "moves":["dragonbreath", "slash", "zenheadbutt", "fusionbolt"]}, {"generation": 5, "level": 70, "moves":["zenheadbutt", "fusionbolt", "dragonclaw", "imprison"]}, {"generation": 5, "level": 100, "moves":["boltstrike", "fusionbolt", "haze", "outrage"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "shiny": 1, "moves":["dragonbreath", "slash", "zenheadbutt", "fusionbolt"]}, ], eventOnly: true, tier: "Uber", }, landorus: { randomBattleMoves: ["calmmind", "rockpolish", "earthpower", "focusblast", "psychic", "sludgewave", "stealthrock", "knockoff", "rockslide"], randomDoubleBattleMoves: ["earthpower", "focusblast", "hiddenpowerice", "psychic", "sludgebomb", "rockslide", "protect"], eventPokemon: [ {"generation": 5, "level": 70, "shiny": 1, "isHidden": false, "moves":["rockslide", "earthquake", "sandstorm", "fissure"]}, {"generation": 5, "level": 5, "isHidden": true, "moves":["block", "mudshot", "rocktomb"], "pokeball": "dreamball"}, {"generation": 6, "level": 65, "shiny": 1, "isHidden": false, "moves":["extrasensory", "swordsdance", "earthpower", "rockslide"]}, {"generation": 6, "level": 50, "nature": "Adamant", "ivs": {"hp": 31, "atk": 31, "def": 31, "spa": 1, "spd": 31, "spe": 24}, "isHidden": false, "moves":["earthquake", "knockoff", "uturn", "rocktomb"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "Uber", }, landorustherian: { randomBattleMoves: ["swordsdance", "rockpolish", "earthquake", "stoneedge", "uturn", "superpower", "stealthrock", "fly"], randomDoubleBattleMoves: ["rockslide", "earthquake", "stoneedge", "uturn", "superpower", "knockoff", "protect"], eventOnly: true, tier: "OU", }, kyurem: { randomBattleMoves: ["dracometeor", "icebeam", "earthpower", "outrage", "substitute", "dragonpulse", "focusblast", "roost"], randomDoubleBattleMoves: ["substitute", "icebeam", "dracometeor", "dragonpulse", "focusblast", "glaciate", "earthpower", "roost", "protect"], eventPokemon: [ {"generation": 5, "level": 75, "shiny": 1, "moves":["glaciate", "dragonpulse", "imprison", "endeavor"]}, {"generation": 5, "level": 70, "shiny": 1, "moves":["scaryface", "glaciate", "dragonpulse", "imprison"]}, {"generation": 6, "level": 50, "shiny": 1, "moves":["dragonbreath", "slash", "scaryface", "glaciate"]}, {"generation": 6, "level": 100, "moves":["glaciate", "scaryface", "dracometeor", "ironhead"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "BL2", }, kyuremblack: { randomBattleMoves: ["outrage", "fusionbolt", "icebeam", "roost", "substitute", "earthpower", "dragonclaw"], randomDoubleBattleMoves: ["protect", "fusionbolt", "icebeam", "roost", "substitute", "honeclaws", "earthpower", "dragonclaw"], eventPokemon: [ {"generation": 5, "level": 75, "shiny": 1, "moves":["freezeshock", "dragonpulse", "imprison", "endeavor"]}, {"generation": 5, "level": 70, "shiny": 1, "moves":["fusionbolt", "freezeshock", "dragonpulse", "imprison"]}, {"generation": 6, "level": 50, "shiny": 1, "moves":["dragonbreath", "slash", "fusionbolt", "freezeshock"]}, {"generation": 6, "level": 100, "moves":["freezeshock", "fusionbolt", "dracometeor", "ironhead"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "OU", }, kyuremwhite: { randomBattleMoves: ["dracometeor", "icebeam", "fusionflare", "earthpower", "focusblast", "dragonpulse", "substitute", "roost", "toxic"], randomDoubleBattleMoves: ["dracometeor", "dragonpulse", "icebeam", "fusionflare", "earthpower", "focusblast", "roost", "protect"], eventPokemon: [ {"generation": 5, "level": 75, "shiny": 1, "moves":["iceburn", "dragonpulse", "imprison", "endeavor"]}, {"generation": 5, "level": 70, "shiny": 1, "moves":["fusionflare", "iceburn", "dragonpulse", "imprison"]}, {"generation": 6, "level": 50, "shiny": 1, "moves":["dragonbreath", "slash", "fusionflare", "iceburn"]}, {"generation": 6, "level": 100, "moves":["iceburn", "fusionflare", "dracometeor", "ironhead"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "Uber", }, keldeo: { randomBattleMoves: ["hydropump", "secretsword", "calmmind", "hiddenpowerflying", "hiddenpowerelectric", "substitute", "scald", "icywind"], randomDoubleBattleMoves: ["hydropump", "secretsword", "protect", "hiddenpowerflying", "hiddenpowerelectric", "substitute", "surf", "icywind", "taunt"], eventPokemon: [ {"generation": 5, "level": 15, "moves":["aquajet", "leer", "doublekick", "bubblebeam"], "pokeball": "cherishball"}, {"generation": 5, "level": 50, "moves":["sacredsword", "hydropump", "aquajet", "swordsdance"], "pokeball": "cherishball"}, {"generation": 6, "level": 15, "moves":["aquajet", "leer", "doublekick", "hydropump"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "moves":["aquajet", "leer", "doublekick", "bubblebeam"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "OU", }, keldeoresolute: { eventOnly: true, requiredMove: "Secret Sword", }, meloetta: { randomBattleMoves: ["uturn", "calmmind", "psyshock", "hypervoice", "shadowball", "focusblast"], randomDoubleBattleMoves: ["calmmind", "psyshock", "thunderbolt", "hypervoice", "shadowball", "focusblast", "protect"], eventPokemon: [ {"generation": 5, "level": 15, "moves":["quickattack", "confusion", "round"], "pokeball": "cherishball"}, {"generation": 5, "level": 50, "moves":["round", "teeterdance", "psychic", "closecombat"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "RU", }, meloettapirouette: { randomBattleMoves: ["relicsong", "closecombat", "knockoff", "return"], randomDoubleBattleMoves: ["relicsong", "closecombat", "knockoff", "return", "protect"], requiredMove: "Relic Song", battleOnly: true, }, genesect: { randomBattleMoves: ["uturn", "bugbuzz", "icebeam", "flamethrower", "thunderbolt", "ironhead", "shiftgear", "extremespeed", "blazekick"], randomDoubleBattleMoves: ["uturn", "bugbuzz", "icebeam", "flamethrower", "thunderbolt", "ironhead", "shiftgear", "extremespeed", "blazekick", "protect"], eventPokemon: [ {"generation": 5, "level": 50, "moves":["technoblast", "magnetbomb", "solarbeam", "signalbeam"], "pokeball": "cherishball"}, {"generation": 5, "level": 15, "moves":["technoblast", "magnetbomb", "solarbeam", "signalbeam"], "pokeball": "cherishball"}, {"generation": 5, "level": 100, "shiny": true, "nature": "Hasty", "ivs": {"atk": 31, "spe": 31}, "moves":["extremespeed", "technoblast", "blazekick", "shiftgear"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "moves":["technoblast", "magnetbomb", "solarbeam", "signalbeam"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "Uber", }, genesectburn: { randomBattleMoves: ["uturn", "bugbuzz", "icebeam", "technoblast", "thunderbolt", "ironhead", "extremespeed"], randomDoubleBattleMoves: ["uturn", "bugbuzz", "icebeam", "technoblast", "thunderbolt", "ironhead", "extremespeed", "protect"], eventOnly: true, requiredItem: "Burn Drive", }, genesectchill: { randomBattleMoves: ["uturn", "bugbuzz", "technoblast", "flamethrower", "thunderbolt", "ironhead", "extremespeed"], randomDoubleBattleMoves: ["uturn", "bugbuzz", "technoblast", "flamethrower", "thunderbolt", "ironhead", "extremespeed", "protect"], eventOnly: true, requiredItem: "Chill Drive", }, genesectdouse: { randomBattleMoves: ["uturn", "bugbuzz", "icebeam", "flamethrower", "thunderbolt", "technoblast", "ironhead", "extremespeed"], randomDoubleBattleMoves: ["uturn", "bugbuzz", "icebeam", "flamethrower", "thunderbolt", "technoblast", "ironhead", "extremespeed", "protect"], eventOnly: true, requiredItem: "Douse Drive", }, genesectshock: { randomBattleMoves: ["uturn", "bugbuzz", "icebeam", "flamethrower", "technoblast", "ironhead", "extremespeed"], randomDoubleBattleMoves: ["uturn", "bugbuzz", "icebeam", "flamethrower", "technoblast", "ironhead", "extremespeed", "protect"], eventOnly: true, requiredItem: "Shock Drive", }, chespin: { randomBattleMoves: ["curse", "gyroball", "seedbomb", "stoneedge", "spikes", "synthesis"], tier: "LC", }, quilladin: { randomBattleMoves: ["curse", "gyroball", "seedbomb", "stoneedge", "spikes", "synthesis"], tier: "NFE", }, chesnaught: { randomBattleMoves: ["leechseed", "synthesis", "spikes", "drainpunch", "spikyshield", "woodhammer"], randomDoubleBattleMoves: ["leechseed", "synthesis", "hammerarm", "spikyshield", "stoneedge", "woodhammer", "rockslide"], tier: "RU", }, fennekin: { randomBattleMoves: ["fireblast", "psychic", "psyshock", "grassknot", "willowisp", "hypnosis", "hiddenpowerrock", "flamecharge"], eventPokemon: [ {"generation": 6, "level": 15, "gender": "F", "nature": "Hardy", "isHidden": false, "moves":["scratch", "flamethrower", "hiddenpower"], "pokeball": "cherishball"}, ], tier: "LC", }, braixen: { randomBattleMoves: ["fireblast", "flamethrower", "psychic", "psyshock", "grassknot", "willowisp", "hiddenpowerrock"], tier: "NFE", }, delphox: { randomBattleMoves: ["calmmind", "fireblast", "psyshock", "grassknot", "switcheroo", "shadowball"], randomDoubleBattleMoves: ["calmmind", "fireblast", "psyshock", "grassknot", "switcheroo", "shadowball", "heatwave", "dazzlinggleam", "protect"], tier: "NU", }, froakie: { randomBattleMoves: ["quickattack", "hydropump", "icebeam", "waterfall", "toxicspikes", "poweruppunch", "uturn"], eventPokemon: [ {"generation": 6, "level": 7, "isHidden": false, "moves":["pound", "growl", "bubble", "return"], "pokeball": "cherishball"}, ], tier: "LC", }, frogadier: { randomBattleMoves: ["hydropump", "surf", "icebeam", "uturn", "taunt", "toxicspikes"], tier: "NFE", }, greninja: { randomBattleMoves: ["hydropump", "icebeam", "darkpulse", "gunkshot", "uturn", "spikes", "toxicspikes", "taunt"], randomDoubleBattleMoves: ["hydropump", "uturn", "surf", "icebeam", "matblock", "taunt", "darkpulse", "protect"], eventPokemon: [ {"generation": 6, "level": 36, "ivs": {"spe": 31}, "isHidden": true, "moves":["watershuriken", "shadowsneak", "hydropump", "substitute"], "pokeball": "cherishball"}, {"generation": 6, "level": 100, "isHidden": true, "moves":["hydrocannon", "gunkshot", "matblock", "happyhour"], "pokeball": "cherishball"}, ], tier: "OU", }, greninjaash: { randomBattleMoves: ["hydropump", "icebeam", "darkpulse", "watershuriken", "uturn"], eventPokemon: [ {"generation": 7, "level": 36, "ivs": {"hp": 20, "atk": 31, "def": 20, "spa": 31, "spd": 20, "spe": 31}, "moves":["watershuriken", "aerialace", "doubleteam", "nightslash"]}, ], eventOnly: true, gen: 7, requiredAbility: "Battle Bond", battleOnly: true, tier: "OU", }, bunnelby: { randomBattleMoves: ["agility", "earthquake", "return", "quickattack", "uturn", "stoneedge", "spikes", "bounce"], tier: "LC", }, diggersby: { randomBattleMoves: ["earthquake", "return", "wildcharge", "uturn", "swordsdance", "quickattack", "knockoff", "agility"], randomDoubleBattleMoves: ["earthquake", "uturn", "return", "wildcharge", "protect", "quickattack"], tier: "BL", }, fletchling: { randomBattleMoves: ["roost", "swordsdance", "uturn", "return", "overheat", "flamecharge", "tailwind"], tier: "LC", }, fletchinder: { randomBattleMoves: ["roost", "swordsdance", "uturn", "return", "overheat", "flamecharge", "tailwind", "acrobatics"], tier: "NFE", }, talonflame: { randomBattleMoves: ["bravebird", "flareblitz", "roost", "swordsdance", "uturn", "willowisp", "tailwind"], randomDoubleBattleMoves: ["bravebird", "flareblitz", "roost", "swordsdance", "uturn", "willowisp", "tailwind", "taunt", "protect"], tier: "BL2", }, scatterbug: { randomBattleMoves: ["tackle", "stringshot", "stunspore", "bugbite", "poisonpowder"], tier: "LC", }, spewpa: { randomBattleMoves: ["tackle", "stringshot", "stunspore", "bugbite", "poisonpowder"], tier: "NFE", }, vivillon: { randomBattleMoves: ["sleeppowder", "quiverdance", "hurricane", "bugbuzz", "substitute"], randomDoubleBattleMoves: ["sleeppowder", "quiverdance", "hurricane", "bugbuzz", "roost", "protect"], tier: "NU", }, vivillonfancy: { eventPokemon: [ {"generation": 6, "level": 12, "isHidden": false, "moves":["gust", "lightscreen", "strugglebug", "holdhands"], "pokeball": "cherishball"}, ], eventOnly: true, }, vivillonpokeball: { eventPokemon: [ {"generation": 6, "level": 12, "isHidden": false, "moves":["stunspore", "gust", "lightscreen", "strugglebug"]}, ], eventOnly: true, }, litleo: { randomBattleMoves: ["hypervoice", "fireblast", "willowisp", "bulldoze", "yawn"], tier: "LC", }, pyroar: { randomBattleMoves: ["sunnyday", "fireblast", "hypervoice", "solarbeam", "willowisp", "darkpulse"], randomDoubleBattleMoves: ["hypervoice", "fireblast", "willowisp", "protect", "sunnyday", "solarbeam"], eventPokemon: [ {"generation": 6, "level": 49, "gender": "M", "perfectIVs": 2, "isHidden": false, "abilities":["unnerve"], "moves":["hypervoice", "fireblast", "darkpulse"], "pokeball": "cherishball"}, ], tier: "PU", }, flabebe: { randomBattleMoves: ["moonblast", "toxic", "wish", "psychic", "aromatherapy", "protect", "calmmind"], tier: "LC", }, floette: { randomBattleMoves: ["moonblast", "toxic", "wish", "psychic", "aromatherapy", "protect", "calmmind"], tier: "NFE", }, floetteeternal: { randomBattleMoves: ["lightofruin", "psychic", "hiddenpowerfire", "hiddenpowerground", "moonblast"], randomDoubleBattleMoves: ["lightofruin", "dazzlinggleam", "wish", "psychic", "aromatherapy", "protect", "calmmind"], isUnreleased: true, tier: "Unreleased", }, florges: { randomBattleMoves: ["calmmind", "moonblast", "synthesis", "aromatherapy", "wish", "toxic", "protect"], randomDoubleBattleMoves: ["moonblast", "dazzlinggleam", "wish", "psychic", "aromatherapy", "protect", "calmmind"], tier: "RU", }, skiddo: { randomBattleMoves: ["hornleech", "brickbreak", "bulkup", "leechseed", "milkdrink", "rockslide"], tier: "LC", }, gogoat: { randomBattleMoves: ["bulkup", "hornleech", "earthquake", "rockslide", "substitute", "leechseed", "milkdrink"], randomDoubleBattleMoves: ["hornleech", "earthquake", "brickbreak", "bulkup", "leechseed", "milkdrink", "rockslide", "protect"], tier: "PU", }, pancham: { randomBattleMoves: ["partingshot", "skyuppercut", "crunch", "stoneedge", "bulldoze", "shadowclaw", "bulkup"], eventPokemon: [ {"generation": 6, "level": 30, "gender": "M", "nature": "Adamant", "isHidden": false, "abilities":["moldbreaker"], "moves":["armthrust", "stoneedge", "darkpulse"], "pokeball": "cherishball"}, ], tier: "LC", }, pangoro: { randomBattleMoves: ["knockoff", "superpower", "gunkshot", "icepunch", "partingshot", "drainpunch"], randomDoubleBattleMoves: ["partingshot", "hammerarm", "crunch", "circlethrow", "icepunch", "earthquake", "poisonjab", "protect"], tier: "RU", }, furfrou: { randomBattleMoves: ["return", "cottonguard", "thunderwave", "substitute", "toxic", "suckerpunch", "uturn", "rest"], randomDoubleBattleMoves: ["return", "cottonguard", "uturn", "thunderwave", "suckerpunch", "snarl", "wildcharge", "protect"], tier: "PU", }, espurr: { randomBattleMoves: ["fakeout", "yawn", "thunderwave", "psychic", "trick", "darkpulse"], tier: "LC", }, meowstic: { randomBattleMoves: ["toxic", "yawn", "thunderwave", "psychic", "reflect", "lightscreen", "healbell"], randomDoubleBattleMoves: ["fakeout", "thunderwave", "psychic", "reflect", "lightscreen", "safeguard", "protect"], tier: "PU", }, meowsticf: { randomBattleMoves: ["calmmind", "psychic", "psyshock", "shadowball", "energyball", "thunderbolt"], randomDoubleBattleMoves: ["psyshock", "darkpulse", "fakeout", "energyball", "signalbeam", "thunderbolt", "protect", "helpinghand"], tier: "PU", }, honedge: { randomBattleMoves: ["swordsdance", "shadowclaw", "shadowsneak", "ironhead", "rockslide", "aerialace", "destinybond"], tier: "LC", }, doublade: { randomBattleMoves: ["swordsdance", "shadowclaw", "shadowsneak", "ironhead", "sacredsword"], randomDoubleBattleMoves: ["swordsdance", "shadowclaw", "shadowsneak", "ironhead", "sacredsword", "rockslide", "protect"], tier: "RU", }, aegislash: { randomBattleMoves: ["kingsshield", "swordsdance", "shadowclaw", "sacredsword", "ironhead", "shadowsneak", "hiddenpowerice", "shadowball", "flashcannon"], randomDoubleBattleMoves: ["kingsshield", "swordsdance", "shadowclaw", "sacredsword", "ironhead", "shadowsneak", "wideguard", "hiddenpowerice", "shadowball", "flashcannon"], eventPokemon: [ {"generation": 6, "level": 50, "gender": "F", "nature": "Quiet", "moves":["wideguard", "kingsshield", "shadowball", "flashcannon"], "pokeball": "cherishball"}, ], tier: "Uber", }, aegislashblade: { battleOnly: true, }, spritzee: { randomBattleMoves: ["calmmind", "drainingkiss", "moonblast", "psychic", "aromatherapy", "wish", "trickroom", "thunderbolt"], tier: "LC", }, aromatisse: { randomBattleMoves: ["wish", "protect", "moonblast", "aromatherapy", "reflect", "lightscreen"], randomDoubleBattleMoves: ["moonblast", "aromatherapy", "wish", "trickroom", "thunderbolt", "protect", "healpulse"], eventPokemon: [ {"generation": 6, "level": 50, "nature": "Relaxed", "isHidden": true, "moves":["trickroom", "healpulse", "disable", "moonblast"], "pokeball": "cherishball"}, ], tier: "NU", }, swirlix: { randomBattleMoves: ["calmmind", "drainingkiss", "dazzlinggleam", "surf", "psychic", "flamethrower", "bellydrum", "thunderbolt", "return", "thief", "cottonguard"], tier: "LC Uber", }, slurpuff: { randomBattleMoves: ["substitute", "bellydrum", "playrough", "return", "drainpunch", "calmmind", "drainingkiss", "dazzlinggleam", "flamethrower", "surf"], randomDoubleBattleMoves: ["substitute", "bellydrum", "playrough", "return", "drainpunch", "dazzlinggleam", "surf", "psychic", "flamethrower", "protect"], tier: "BL3", }, inkay: { randomBattleMoves: ["topsyturvy", "switcheroo", "superpower", "psychocut", "flamethrower", "rockslide", "trickroom"], eventPokemon: [ {"generation": 6, "level": 10, "isHidden": false, "moves":["happyhour", "foulplay", "hypnosis", "topsyturvy"], "pokeball": "cherishball"}, ], tier: "LC", }, malamar: { randomBattleMoves: ["superpower", "knockoff", "psychocut", "rockslide", "substitute", "trickroom"], randomDoubleBattleMoves: ["superpower", "psychocut", "rockslide", "trickroom", "knockoff", "protect"], eventPokemon: [ {"generation": 6, "level": 50, "nature": "Adamant", "ivs": {"hp": 31, "atk": 31}, "isHidden": false, "abilities":["contrary"], "moves":["superpower", "knockoff", "facade", "rockslide"], "pokeball": "cherishball"}, ], tier: "NU", }, binacle: { randomBattleMoves: ["shellsmash", "razorshell", "stoneedge", "earthquake", "crosschop", "poisonjab", "xscissor", "rockslide"], tier: "LC", }, barbaracle: { randomBattleMoves: ["shellsmash", "stoneedge", "razorshell", "earthquake", "crosschop", "stealthrock"], randomDoubleBattleMoves: ["shellsmash", "razorshell", "earthquake", "crosschop", "rockslide", "protect"], tier: "NU", }, skrelp: { randomBattleMoves: ["scald", "sludgebomb", "thunderbolt", "shadowball", "toxicspikes", "hydropump"], tier: "LC", }, dragalge: { randomBattleMoves: ["dracometeor", "sludgewave", "focusblast", "scald", "hiddenpowerfire", "toxicspikes", "dragonpulse"], randomDoubleBattleMoves: ["dracometeor", "sludgebomb", "focusblast", "scald", "hiddenpowerfire", "protect", "dragonpulse"], tier: "RU", }, clauncher: { randomBattleMoves: ["waterpulse", "flashcannon", "uturn", "crabhammer", "aquajet", "sludgebomb"], tier: "LC", }, clawitzer: { randomBattleMoves: ["scald", "waterpulse", "darkpulse", "aurasphere", "icebeam", "uturn"], randomDoubleBattleMoves: ["waterpulse", "icebeam", "uturn", "darkpulse", "aurasphere", "muddywater", "helpinghand", "protect"], tier: "NU", }, helioptile: { randomBattleMoves: ["surf", "voltswitch", "hiddenpowerice", "raindance", "thunder", "darkpulse", "thunderbolt"], tier: "LC", }, heliolisk: { randomBattleMoves: ["raindance", "thunder", "hypervoice", "surf", "darkpulse", "hiddenpowerice", "voltswitch", "thunderbolt"], randomDoubleBattleMoves: ["surf", "voltswitch", "hiddenpowerice", "raindance", "thunder", "darkpulse", "thunderbolt", "electricterrain", "protect"], tier: "RU", }, tyrunt: { randomBattleMoves: ["stealthrock", "dragondance", "stoneedge", "dragonclaw", "earthquake", "icefang", "firefang"], eventPokemon: [ {"generation": 6, "level": 10, "isHidden": true, "moves":["tailwhip", "tackle", "roar", "stomp"], "pokeball": "cherishball"}, ], tier: "LC", }, tyrantrum: { randomBattleMoves: ["stealthrock", "dragondance", "dragonclaw", "earthquake", "superpower", "outrage", "headsmash"], randomDoubleBattleMoves: ["rockslide", "dragondance", "headsmash", "dragonclaw", "earthquake", "icefang", "firefang", "protect"], tier: "BL3", }, amaura: { randomBattleMoves: ["naturepower", "hypervoice", "ancientpower", "thunderbolt", "darkpulse", "thunderwave", "dragontail", "flashcannon"], eventPokemon: [ {"generation": 6, "level": 10, "isHidden": true, "moves":["growl", "powdersnow", "thunderwave", "rockthrow"], "pokeball": "cherishball"}, ], tier: "LC", }, aurorus: { randomBattleMoves: ["ancientpower", "blizzard", "thunderwave", "earthpower", "freezedry", "hypervoice", "stealthrock"], randomDoubleBattleMoves: ["hypervoice", "ancientpower", "thunderwave", "flashcannon", "freezedry", "icywind", "protect"], tier: "NU", }, sylveon: { randomBattleMoves: ["hypervoice", "calmmind", "wish", "protect", "psyshock", "batonpass", "shadowball"], randomDoubleBattleMoves: ["hypervoice", "calmmind", "wish", "protect", "psyshock", "helpinghand", "shadowball", "hiddenpowerground"], eventPokemon: [ {"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "helpinghand", "sandattack", "fairywind"], "pokeball": "cherishball"}, {"generation": 6, "level": 10, "gender": "F", "isHidden": false, "moves":["disarmingvoice", "babydolleyes", "quickattack", "drainingkiss"], "pokeball": "cherishball"}, {"generation": 7, "level": 50, "gender": "F", "isHidden": true, "moves":["hyperbeam", "drainingkiss", "psyshock", "calmmind"], "pokeball": "cherishball"}, ], tier: "UU", }, hawlucha: { randomBattleMoves: ["substitute", "swordsdance", "highjumpkick", "acrobatics", "roost", "stoneedge"], randomDoubleBattleMoves: ["swordsdance", "highjumpkick", "uturn", "stoneedge", "skydrop", "encore", "protect"], tier: "OU", }, dedenne: { randomBattleMoves: ["substitute", "recycle", "thunderbolt", "nuzzle", "grassknot", "hiddenpowerice", "toxic"], randomDoubleBattleMoves: ["voltswitch", "thunderbolt", "nuzzle", "grassknot", "hiddenpowerice", "uturn", "helpinghand", "protect"], tier: "PU", }, carbink: { randomBattleMoves: ["stealthrock", "lightscreen", "reflect", "explosion", "powergem", "moonblast"], randomDoubleBattleMoves: ["trickroom", "lightscreen", "reflect", "explosion", "powergem", "moonblast", "protect"], tier: "PU", }, goomy: { randomBattleMoves: ["sludgebomb", "thunderbolt", "toxic", "protect", "infestation"], eventPokemon: [ {"generation": 7, "level": 1, "shiny": 1, "isHidden": true, "moves":["bodyslam", "dragonpulse", "counter"], "pokeball": "cherishball"}, ], tier: "LC", }, sliggoo: { randomBattleMoves: ["sludgebomb", "thunderbolt", "toxic", "protect", "infestation", "icebeam"], tier: "NFE", }, goodra: { randomBattleMoves: ["dracometeor", "dragonpulse", "fireblast", "sludgebomb", "thunderbolt", "earthquake", "dragontail"], randomDoubleBattleMoves: ["thunderbolt", "icebeam", "dragonpulse", "fireblast", "muddywater", "dracometeor", "focusblast", "protect"], tier: "RU", }, klefki: { randomBattleMoves: ["reflect", "lightscreen", "spikes", "magnetrise", "playrough", "thunderwave", "foulplay", "toxic"], randomDoubleBattleMoves: ["reflect", "lightscreen", "safeguard", "playrough", "substitute", "thunderwave", "protect", "flashcannon", "dazzlinggleam"], tier: "UU", }, phantump: { randomBattleMoves: ["hornleech", "leechseed", "phantomforce", "substitute", "willowisp", "rest"], tier: "LC", }, trevenant: { randomBattleMoves: ["hornleech", "shadowclaw", "leechseed", "willowisp", "rest", "substitute", "phantomforce"], randomDoubleBattleMoves: ["hornleech", "woodhammer", "leechseed", "shadowclaw", "willowisp", "trickroom", "earthquake", "rockslide", "protect"], tier: "PU", }, pumpkaboo: { randomBattleMoves: ["willowisp", "shadowsneak", "destinybond", "synthesis", "seedbomb", "leechseed"], tier: "LC", }, pumpkaboosmall: { randomBattleMoves: ["willowisp", "shadowsneak", "destinybond", "synthesis", "seedbomb"], unreleasedHidden: true, tier: "LC", }, pumpkaboolarge: { randomBattleMoves: ["willowisp", "shadowsneak", "leechseed", "synthesis", "seedbomb"], unreleasedHidden: true, tier: "LC", }, pumpkaboosuper: { randomBattleMoves: ["willowisp", "shadowsneak", "leechseed", "synthesis", "seedbomb"], eventPokemon: [ {"generation": 6, "level": 50, "moves":["trickortreat", "astonish", "scaryface", "shadowsneak"], "pokeball": "cherishball"}, ], tier: "LC", }, gourgeist: { randomBattleMoves: ["willowisp", "seedbomb", "leechseed", "shadowsneak", "substitute", "synthesis"], randomDoubleBattleMoves: ["willowisp", "shadowsneak", "painsplit", "seedbomb", "leechseed", "phantomforce", "explosion", "protect"], tier: "PU", }, gourgeistsmall: { randomBattleMoves: ["willowisp", "seedbomb", "leechseed", "shadowsneak", "substitute", "synthesis"], randomDoubleBattleMoves: ["willowisp", "shadowsneak", "painsplit", "seedbomb", "leechseed", "phantomforce", "explosion", "protect"], unreleasedHidden: true, tier: "PU", }, gourgeistlarge: { randomBattleMoves: ["willowisp", "seedbomb", "leechseed", "shadowsneak", "substitute", "synthesis"], randomDoubleBattleMoves: ["willowisp", "shadowsneak", "painsplit", "seedbomb", "leechseed", "phantomforce", "explosion", "protect", "trickroom"], unreleasedHidden: true, tier: "PU", }, gourgeistsuper: { randomBattleMoves: ["willowisp", "seedbomb", "leechseed", "shadowsneak", "substitute", "synthesis"], randomDoubleBattleMoves: ["willowisp", "shadowsneak", "painsplit", "seedbomb", "leechseed", "phantomforce", "explosion", "protect", "trickroom"], tier: "PU", }, bergmite: { randomBattleMoves: ["avalanche", "recover", "stoneedge", "curse", "gyroball", "rapidspin"], tier: "LC", }, avalugg: { randomBattleMoves: ["avalanche", "recover", "toxic", "rapidspin", "roar", "earthquake"], randomDoubleBattleMoves: ["avalanche", "recover", "earthquake", "protect"], tier: "PU", }, noibat: { randomBattleMoves: ["airslash", "hurricane", "dracometeor", "uturn", "roost", "switcheroo"], tier: "LC", }, noivern: { randomBattleMoves: ["dracometeor", "hurricane", "airslash", "flamethrower", "boomburst", "switcheroo", "uturn", "roost", "taunt"], randomDoubleBattleMoves: ["airslash", "hurricane", "dragonpulse", "dracometeor", "focusblast", "flamethrower", "uturn", "roost", "boomburst", "switcheroo", "tailwind", "taunt", "protect"], tier: "BL3", }, xerneas: { randomBattleMoves: ["geomancy", "moonblast", "thunder", "focusblast", "thunderbolt", "hiddenpowerfire", "psyshock", "rockslide", "closecombat"], randomDoubleBattleMoves: ["geomancy", "dazzlinggleam", "thunder", "focusblast", "thunderbolt", "hiddenpowerfire", "psyshock", "rockslide", "closecombat", "protect"], eventPokemon: [ {"generation": 6, "level": 50, "moves":["gravity", "geomancy", "moonblast", "megahorn"]}, {"generation": 6, "level": 100, "shiny": true, "moves":["geomancy", "moonblast", "aromatherapy", "focusblast"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "Uber", }, yveltal: { randomBattleMoves: ["darkpulse", "hurricane", "foulplay", "oblivionwing", "uturn", "suckerpunch", "taunt", "toxic", "roost"], randomDoubleBattleMoves: ["darkpulse", "oblivionwing", "taunt", "focusblast", "hurricane", "roost", "suckerpunch", "snarl", "skydrop", "protect"], eventPokemon: [ {"generation": 6, "level": 50, "moves":["snarl", "oblivionwing", "disable", "darkpulse"]}, {"generation": 6, "level": 100, "shiny": true, "moves":["oblivionwing", "suckerpunch", "darkpulse", "foulplay"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "Uber", }, zygarde: { randomBattleMoves: ["dragondance", "thousandarrows", "outrage", "extremespeed", "irontail"], randomDoubleBattleMoves: ["dragondance", "thousandarrows", "extremespeed", "rockslide", "coil", "stoneedge", "glare", "protect"], eventPokemon: [ {"generation": 6, "level": 70, "moves":["crunch", "earthquake", "camouflage", "dragonpulse"]}, {"generation": 6, "level": 100, "moves":["landswrath", "extremespeed", "glare", "outrage"], "pokeball": "cherishball"}, {"generation": 7, "level": 50, "moves":["bind", "landswrath", "sandstorm", "haze"]}, {"generation": 7, "level": 50, "isHidden": true, "moves":["bind", "landswrath", "sandstorm", "haze"]}, ], eventOnly: true, tier: "OU", }, zygarde10: { randomBattleMoves: ["dragondance", "thousandarrows", "outrage", "extremespeed", "irontail", "substitute"], randomDoubleBattleMoves: ["dragondance", "thousandarrows", "extremespeed", "irontail", "protect"], eventPokemon: [ {"generation": 7, "level": 30, "moves":["safeguard", "dig", "bind", "landswrath"]}, {"generation": 7, "level": 50, "isHidden": true, "moves":["safeguard", "dig", "bind", "landswrath"]}, ], eventOnly: true, gen: 7, tier: "RU", }, zygardecomplete: { gen: 7, requiredAbility: "Power Construct", battleOnly: true, tier: "Uber", }, diancie: { randomBattleMoves: ["reflect", "lightscreen", "stealthrock", "diamondstorm", "moonblast", "hiddenpowerfire"], randomDoubleBattleMoves: ["diamondstorm", "moonblast", "reflect", "lightscreen", "safeguard", "substitute", "calmmind", "psychic", "dazzlinggleam", "protect"], eventPokemon: [ {"generation": 6, "level": 50, "perfectIVs": 0, "moves":["diamondstorm", "reflect", "return", "moonblast"], "pokeball": "cherishball"}, {"generation": 6, "level": 50, "shiny": true, "moves":["diamondstorm", "moonblast", "reflect", "return"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "RU", }, dianciemega: { randomBattleMoves: ["calmmind", "moonblast", "earthpower", "hiddenpowerfire", "psyshock", "diamondstorm"], randomDoubleBattleMoves: ["diamondstorm", "moonblast", "calmmind", "psyshock", "earthpower", "hiddenpowerfire", "dazzlinggleam", "protect"], requiredItem: "Diancite", tier: "OU", }, hoopa: { randomBattleMoves: ["nastyplot", "psyshock", "shadowball", "focusblast", "trick"], randomDoubleBattleMoves: ["hyperspacehole", "shadowball", "focusblast", "protect", "psychic", "trickroom"], eventPokemon: [ {"generation": 6, "level": 50, "moves":["hyperspacehole", "nastyplot", "psychic", "astonish"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "RU", }, hoopaunbound: { randomBattleMoves: ["nastyplot", "substitute", "psyshock", "psychic", "darkpulse", "focusblast", "hyperspacefury", "zenheadbutt", "icepunch", "drainpunch", "gunkshot", "knockoff", "trick"], randomDoubleBattleMoves: ["psychic", "darkpulse", "focusblast", "protect", "hyperspacefury", "zenheadbutt", "icepunch", "drainpunch", "gunkshot"], eventOnly: true, tier: "BL", }, volcanion: { randomBattleMoves: ["substitute", "steameruption", "fireblast", "sludgewave", "hiddenpowerice", "earthpower", "superpower"], randomDoubleBattleMoves: ["substitute", "steameruption", "heatwave", "sludgebomb", "rockslide", "earthquake", "protect"], eventPokemon: [ {"generation": 6, "level": 70, "moves":["steameruption", "overheat", "hydropump", "mist"], "pokeball": "cherishball"}, {"generation": 6, "level": 70, "moves":["steameruption", "flamethrower", "hydropump", "explosion"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "UU", }, rowlet: { unreleasedHidden: true, tier: "LC", }, dartrix: { unreleasedHidden: true, tier: "NFE", }, decidueye: { randomBattleMoves: ["spiritshackle", "uturn", "leafblade", "roost", "swordsdance", "suckerpunch"], randomDoubleBattleMoves: ["spiritshackle", "leafblade", "bravebird", "protect", "suckerpunch"], unreleasedHidden: true, tier: "RU", }, litten: { unreleasedHidden: true, tier: "LC", }, torracat: { unreleasedHidden: true, tier: "NFE", }, incineroar: { randomBattleMoves: ["fakeout", "darkestlariat", "flareblitz", "uturn", "earthquake"], randomDoubleBattleMoves: ["fakeout", "darkestlariat", "flareblitz", "crosschop", "willowisp", "taunt", "snarl"], unreleasedHidden: true, tier: "NU", }, popplio: { unreleasedHidden: true, tier: "LC", }, brionne: { unreleasedHidden: true, tier: "NFE", }, primarina: { randomBattleMoves: ["hydropump", "moonblast", "scald", "psychic", "hiddenpowerfire"], randomDoubleBattleMoves: ["hypervoice", "moonblast", "substitute", "protect", "icebeam"], unreleasedHidden: true, tier: "UU", }, pikipek: { tier: "LC", }, trumbeak: { tier: "NFE", }, toucannon: { randomBattleMoves: ["substitute", "beakblast", "swordsdance", "roost", "brickbreak", "bulletseed", "rockblast"], randomDoubleBattleMoves: ["bulletseed", "rockblast", "bravebird", "tailwind", "protect"], tier: "PU", }, yungoos: { tier: "LC", }, gumshoos: { randomBattleMoves: ["uturn", "return", "crunch", "earthquake"], randomDoubleBattleMoves: ["uturn", "return", "superfang", "protect", "crunch"], tier: "PU", }, grubbin: { tier: "LC", }, charjabug: { tier: "NFE", }, vikavolt: { randomBattleMoves: ["agility", "bugbuzz", "thunderbolt", "voltswitch", "energyball", "hiddenpowerice"], randomDoubleBattleMoves: ["thunderbolt", "bugbuzz", "stringshot", "protect", "voltswitch", "hiddenpowerice"], tier: "NU", }, crabrawler: { tier: "LC", }, crabominable: { randomBattleMoves: ["icehammer", "closecombat", "earthquake", "stoneedge"], randomDoubleBattleMoves: ["icehammer", "closecombat", "stoneedge", "protect", "wideguard", "earthquake"], tier: "PU", }, oricorio: { randomBattleMoves: ["revelationdance", "hurricane", "toxic", "roost", "uturn"], randomDoubleBattleMoves: ["revelationdance", "airslash", "hurricane", "tailwind", "protect"], tier: "PU", }, oricoriopompom: { randomBattleMoves: ["revelationdance", "hurricane", "toxic", "roost", "uturn"], randomDoubleBattleMoves: ["revelationdance", "airslash", "hurricane", "tailwind", "protect"], tier: "PU", }, oricoriopau: { randomBattleMoves: ["revelationdance", "hurricane", "toxic", "roost", "uturn"], randomDoubleBattleMoves: ["revelationdance", "airslash", "hurricane", "tailwind", "protect"], tier: "PU", }, oricoriosensu: { randomBattleMoves: ["revelationdance", "hurricane", "toxic", "roost", "uturn"], randomDoubleBattleMoves: ["revelationdance", "airslash", "hurricane", "tailwind", "protect"], tier: "PU", }, cutiefly: { tier: "LC Uber", }, ribombee: { randomBattleMoves: ["quiverdance", "bugbuzz", "moonblast", "hiddenpowerfire", "roost", "batonpass"], randomDoubleBattleMoves: ["quiverdance", "pollenpuff", "moonblast", "protect", "batonpass"], tier: "BL3", }, rockruff: { tier: "LC", }, lycanroc: { randomBattleMoves: ["swordsdance", "accelerock", "stoneedge", "crunch", "firefang"], randomDoubleBattleMoves: ["accelerock", "stoneedge", "crunch", "firefang", "protect", "taunt"], tier: "PU", }, lycanrocmidnight: { randomBattleMoves: ["bulkup", "stoneedge", "stealthrock", "suckerpunch", "swordsdance", "firefang"], randomDoubleBattleMoves: ["stoneedge", "suckerpunch", "swordsdance", "protect", "taunt"], eventPokemon: [ {"generation": 7, "level": 50, "isHidden": true, "moves":["stoneedge", "firefang", "suckerpunch", "swordsdance"], "pokeball": "cherishball"}, ], tier: "PU", }, wishiwashi: { randomBattleMoves: ["scald", "hydropump", "icebeam", "hiddenpowergrass", "earthquake"], randomDoubleBattleMoves: ["hydropump", "icebeam", "endeavor", "protect", "hiddenpowergrass", "earthquake", "helpinghand"], tier: "PU", }, wishiwashischool: { battleOnly: true, }, mareanie: { eventPokemon: [ {"generation": 7, "level": 1, "shiny": 1, "isHidden": true, "moves":["toxic", "stockpile", "swallow"], "pokeball": "cherishball"}, ], tier: "LC", }, toxapex: { randomBattleMoves: ["toxicspikes", "banefulbunker", "recover", "scald", "haze"], randomDoubleBattleMoves: ["scald", "banefulbunker", "haze", "wideguard", "lightscreen"], tier: "OU", }, mudbray: { tier: "LC", }, mudsdale: { randomBattleMoves: ["earthquake", "closecombat", "payback", "rockslide", "heavyslam"], randomDoubleBattleMoves: ["highhorsepower", "heavyslam", "closecombat", "rockslide", "protect", "earthquake", "rocktomb"], tier: "PU", }, dewpider: { tier: "LC", }, araquanid: { randomBattleMoves: ["liquidation", "leechlife", "lunge", "toxic", "mirrorcoat", "crunch"], randomDoubleBattleMoves: ["liquidation", "leechlife", "lunge", "poisonjab", "protect", "wideguard"], tier: "RU", }, fomantis: { tier: "LC", }, lurantis: { randomBattleMoves: ["leafstorm", "hiddenpowerfire", "gigadrain", "substitute"], randomDoubleBattleMoves: ["leafstorm", "gigadrain", "hiddenpowerice", "hiddenpowerfire", "protect"], tier: "PU", }, morelull: { tier: "LC", }, shiinotic: { randomBattleMoves: ["spore", "strengthsap", "moonblast", "substitute", "leechseed"], randomDoubleBattleMoves: ["spore", "gigadrain", "moonblast", "sludgebomb", "protect"], tier: "PU", }, salandit: { tier: "LC", }, salazzle: { randomBattleMoves: ["nastyplot", "fireblast", "sludgewave", "hiddenpowerground"], randomDoubleBattleMoves: ["protect", "flamethrower", "sludgebomb", "hiddenpowerground", "hiddenpowerice", "fakeout", "encore", "willowisp", "taunt"], eventPokemon: [ {"generation": 7, "level": 50, "isHidden": false, "moves":["fakeout", "toxic", "sludgebomb", "flamethrower"], "pokeball": "cherishball"}, ], tier: "RU", }, stufful: { tier: "LC", }, bewear: { randomBattleMoves: ["hammerarm", "icepunch", "swordsdance", "return", "shadowclaw", "doubleedge"], randomDoubleBattleMoves: ["hammerarm", "icepunch", "doubleedge", "protect", "wideguard"], eventPokemon: [ {"generation": 7, "level": 50, "gender": "F", "isHidden": true, "moves":["babydolleyes", "brutalswing", "superpower", "bind"], "pokeball": "cherishball"}, ], tier: "RU", }, bounsweet: { tier: "LC", }, steenee: { eventPokemon: [ {"generation": 7, "level": 20, "nature": "Naive", "isHidden": false, "abilities":["leafguard"], "moves":["magicalleaf", "doubleslap", "sweetscent"], "pokeball": "cherishball"}, ], tier: "NFE", }, tsareena: { randomBattleMoves: ["highjumpkick", "tropkick", "playrough", "uturn"], randomDoubleBattleMoves: ["highjumpkick", "playrough", "tropkick", "uturn", "feint", "protect"], tier: "RU", }, comfey: { randomBattleMoves: ["aromatherapy", "drainingkiss", "toxic", "synthesis", "uturn"], randomDoubleBattleMoves: ["floralhealing", "drainingkiss", "uturn", "lightscreen", "taunt"], eventPokemon: [ {"generation": 7, "level": 10, "nature": "Jolly", "isHidden": false, "moves":["celebrate", "leechseed", "drainingkiss", "magicalleaf"], "pokeball": "cherishball"}, ], tier: "RU", }, oranguru: { randomBattleMoves: ["nastyplot", "psyshock", "focusblast", "thunderbolt"], randomDoubleBattleMoves: ["trickroom", "foulplay", "instruct", "psychic", "protect", "lightscreen", "reflect"], eventPokemon: [ {"generation": 7, "level": 1, "shiny": 1, "isHidden": false, "abilities":["telepathy"], "moves":["instruct", "psychic", "psychicterrain"], "pokeball": "cherishball"}, ], unreleasedHidden: true, tier: "PU", }, passimian: { randomBattleMoves: ["rockslide", "closecombat", "earthquake", "ironhead", "uturn"], randomDoubleBattleMoves: ["closecombat", "uturn", "rockslide", "protect", "ironhead", "taunt"], eventPokemon: [ {"generation": 7, "level": 1, "shiny": 1, "isHidden": false, "moves":["bestow", "fling", "feint"], "pokeball": "cherishball"}, ], unreleasedHidden: true, tier: "PU", }, wimpod: { tier: "LC", }, golisopod: { randomBattleMoves: ["spikes", "firstimpression", "liquidation", "suckerpunch", "aquajet", "toxic", "leechlife"], randomDoubleBattleMoves: ["firstimpression", "aquajet", "liquidation", "leechlife", "protect", "suckerpunch", "wideguard"], tier: "RU", }, sandygast: { tier: "LC", }, palossand: { randomBattleMoves: ["shoreup", "earthpower", "shadowball", "protect", "toxic"], randomDoubleBattleMoves: ["shoreup", "protect", "shadowball", "earthpower"], tier: "PU", }, pyukumuku: { randomBattleMoves: ["batonpass", "counter", "reflect", "lightscreen"], randomDoubleBattleMoves: ["reflect", "lightscreen", "counter", "helpinghand", "safeguard", "memento"], tier: "PU", }, typenull: { eventPokemon: [ {"generation": 7, "level": 40, "shiny": 1, "perfectIVs": 3, "moves":["crushclaw", "scaryface", "xscissor", "takedown"]}, ], eventOnly: true, tier: "NFE", }, silvally: { randomBattleMoves: ["swordsdance", "return", "doubleedge", "crunch", "flamecharge", "flamethrower", "icebeam", "uturn", "ironhead"], randomDoubleBattleMoves: ["protect", "doubleedge", "uturn", "crunch", "icebeam", "partingshot", "flamecharge", "swordsdance", "explosion"], eventPokemon: [ {"generation": 7, "level": 100, "shiny": true, "moves":["multiattack", "partingshot", "punishment", "scaryface"], "pokeball": "cherishball"}, ], tier: "PU", }, silvallybug: { randomBattleMoves: ["flamethrower", "icebeam", "thunderbolt", "uturn"], randomDoubleBattleMoves: ["protect", "uturn", "flamethrower", "icebeam", "thunderbolt", "thunderwave"], requiredItem: "Bug Memory", tier: "PU", }, silvallydark: { randomBattleMoves: ["multiattack", "swordsdance", "flamecharge", "ironhead"], randomDoubleBattleMoves: ["protect", "multiattack", "icebeam", "partingshot", "uturn", "snarl", "thunderwave"], requiredItem: "Dark Memory", tier: "PU", }, silvallydragon: { randomBattleMoves: ["multiattack", "ironhead", "flamecharge", "flamethrower", "icebeam", "dracometeor", "swordsdance", "uturn"], randomDoubleBattleMoves: ["protect", "dracometeor", "icebeam", "flamethrower", "partingshot", "uturn", "thunderwave"], requiredItem: "Dragon Memory", tier: "PU", }, silvallyelectric: { randomBattleMoves: ["multiattack", "flamethrower", "icebeam", "partingshot", "toxic"], randomDoubleBattleMoves: ["protect", "thunderbolt", "icebeam", "uturn", "partingshot", "snarl", "thunderwave"], requiredItem: "Electric Memory", tier: "PU", }, silvallyfairy: { randomBattleMoves: ["multiattack", "flamethrower", "rockslide", "thunderwave", "partingshot"], randomDoubleBattleMoves: ["protect", "multiattack", "uturn", "icebeam", "partingshot", "flamethrower", "thunderwave"], requiredItem: "Fairy Memory", tier: "PU", }, silvallyfighting: { randomBattleMoves: ["swordsdance", "multiattack", "shadowclaw", "flamecharge", "ironhead"], randomDoubleBattleMoves: ["protect", "multiattack", "rockslide", "swordsdance", "flamecharge"], requiredItem: "Fighting Memory", tier: "PU", }, silvallyfire: { randomBattleMoves: ["multiattack", "icebeam", "thunderbolt", "uturn"], randomDoubleBattleMoves: ["protect", "flamethrower", "snarl", "uturn", "thunderbolt", "icebeam", "thunderwave"], requiredItem: "Fire Memory", tier: "PU", }, silvallyflying: { randomBattleMoves: ["multiattack", "flamethrower", "ironhead", "partingshot", "thunderwave"], randomDoubleBattleMoves: ["protect", "multiattack", "partingshot", "swordsdance", "flamecharge", "uturn", "ironhead", "thunderwave"], requiredItem: "Flying Memory", tier: "PU", }, silvallyghost: { randomBattleMoves: ["multiattack", "flamethrower", "icebeam", "partingshot", "toxic"], randomDoubleBattleMoves: ["protect", "multiattack", "uturn", "icebeam", "partingshot"], requiredItem: "Ghost Memory", tier: "PU", }, silvallygrass: { randomBattleMoves: ["multiattack", "flamethrower", "icebeam", "partingshot", "toxic"], randomDoubleBattleMoves: ["protect", "flamethrower", "multiattack", "icebeam", "uturn", "partingshot", "thunderwave"], requiredItem: "Grass Memory", tier: "PU", }, silvallyground: { randomBattleMoves: ["multiattack", "swordsdance", "flamecharge", "rockslide"], randomDoubleBattleMoves: ["protect", "multiattack", "icebeam", "thunderbolt", "flamecharge", "rockslide", "swordsdance"], requiredItem: "Ground Memory", tier: "PU", }, silvallyice: { randomBattleMoves: ["multiattack", "thunderbolt", "flamethrower", "uturn", "toxic"], randomDoubleBattleMoves: ["protect", "icebeam", "thunderbolt", "partingshot", "uturn", "thunderwave"], requiredItem: "Ice Memory", tier: "PU", }, silvallypoison: { randomBattleMoves: ["multiattack", "flamethrower", "icebeam", "partingshot", "toxic"], randomDoubleBattleMoves: ["protect", "multiattack", "uturn", "partingshot", "flamethrower", "icebeam", "thunderwave"], requiredItem: "Poison Memory", tier: "PU", }, silvallypsychic: { randomBattleMoves: ["multiattack", "flamethrower", "rockslide", "partingshot", "thunderwave"], randomDoubleBattleMoves: ["protect", "multiattack", "partingshot", "uturn", "flamethrower", "thunderwave"], requiredItem: "Psychic Memory", tier: "PU", }, silvallyrock: { randomBattleMoves: ["multiattack", "flamethrower", "icebeam", "partingshot", "toxic"], randomDoubleBattleMoves: ["protect", "rockslide", "uturn", "icebeam", "flamethrower", "partingshot"], requiredItem: "Rock Memory", tier: "PU", }, silvallysteel: { randomBattleMoves: ["multiattack", "crunch", "flamethrower", "thunderbolt"], randomDoubleBattleMoves: ["protect", "multiattack", "swordsdance", "rockslide", "flamecharge", "uturn", "partingshot"], requiredItem: "Steel Memory", tier: "PU", }, silvallywater: { randomBattleMoves: ["multiattack", "icebeam", "thunderbolt", "partingshot"], randomDoubleBattleMoves: ["protect", "multiattack", "icebeam", "thunderbolt", "flamethrower", "partingshot", "uturn", "thunderwave"], requiredItem: "Water Memory", tier: "PU", }, minior: { randomBattleMoves: ["shellsmash", "powergem", "acrobatics", "earthquake"], randomDoubleBattleMoves: ["shellsmash", "powergem", "acrobatics", "earthquake", "protect"], tier: "NU", }, miniormeteor: { battleOnly: true, }, komala: { randomBattleMoves: ["return", "suckerpunch", "woodhammer", "earthquake", "playrough", "uturn"], randomDoubleBattleMoves: ["protect", "return", "uturn", "suckerpunch", "woodhammer", "shadowclaw", "playrough", "swordsdance"], tier: "PU", }, turtonator: { randomBattleMoves: ["fireblast", "shelltrap", "earthquake", "dragontail", "explosion", "dracometeor"], randomDoubleBattleMoves: ["dragonpulse", "dracometeor", "fireblast", "shellsmash", "protect", "focusblast", "explosion"], eventPokemon: [ {"generation": 7, "level": 1, "shiny": 1, "moves":["flamethrower", "bodyslam", "wideguard"], "pokeball": "cherishball"}, {"generation": 7, "level": 30, "gender": "M", "nature": "Brave", "moves":["flamethrower", "shelltrap", "dragontail"], "pokeball": "cherishball"}, ], tier: "PU", }, togedemaru: { randomBattleMoves: ["spikyshield", "zingzap", "nuzzle", "uturn", "wish"], randomDoubleBattleMoves: ["zingzap", "nuzzle", "spikyshield", "encore", "fakeout", "uturn"], tier: "PU", }, mimikyu: { randomBattleMoves: ["swordsdance", "shadowsneak", "playrough", "woodhammer", "shadowclaw"], randomDoubleBattleMoves: ["trickroom", "shadowclaw", "playrough", "woodhammer", "willowisp", "shadowsneak", "swordsdance", "protect"], eventPokemon: [ {"generation": 7, "level": 10, "moves":["copycat", "babydolleyes", "splash", "astonish"], "pokeball": "cherishball"}, {"generation": 7, "level": 10, "moves":["astonish", "playrough", "copycat", "substitute"], "pokeball": "cherishball"}, ], tier: "OU", }, mimikyubusted: { battleOnly: true, }, bruxish: { randomBattleMoves: ["psychicfangs", "crunch", "waterfall", "icefang", "aquajet", "swordsdance"], randomDoubleBattleMoves: ["trickroom", "psychicfangs", "crunch", "waterfall", "protect", "swordsdance"], tier: "RU", }, drampa: { randomBattleMoves: ["dracometeor", "dragonpulse", "hypervoice", "fireblast", "thunderbolt", "glare", "substitute", "roost"], randomDoubleBattleMoves: ["dracometeor", "dragonpulse", "hypervoice", "fireblast", "icebeam", "energyball", "thunderbolt", "protect", "roost"], eventPokemon: [ {"generation": 7, "level": 1, "shiny": 1, "isHidden": true, "moves":["playnice", "echoedvoice", "hurricane"], "pokeball": "cherishball"}, ], tier: "PU", }, dhelmise: { randomBattleMoves: ["swordsdance", "powerwhip", "phantomforce", "anchorshot", "switcheroo", "earthquake"], randomDoubleBattleMoves: ["powerwhip", "shadowclaw", "anchorshot", "protect", "gyroball"], tier: "RU", }, jangmoo: { tier: "LC", }, hakamoo: { tier: "NFE", }, kommoo: { randomBattleMoves: ["dragondance", "outrage", "dragonclaw", "skyuppercut", "poisonjab"], randomDoubleBattleMoves: ["clangingscales", "focusblast", "flashcannon", "substitute", "protect", "dracometeor"], tier: "RU", }, tapukoko: { randomBattleMoves: ["wildcharge", "voltswitch", "naturesmadness", "bravebird", "uturn", "dazzlinggleam"], randomDoubleBattleMoves: ["wildcharge", "voltswitch", "dazzlinggleam", "bravebird", "protect", "thunderbolt", "hiddenpowerice", "taunt", "skydrop", "naturesmadness", "uturn"], eventPokemon: [ {"generation": 7, "level": 60, "isHidden": false, "moves":["naturesmadness", "discharge", "agility", "electroball"]}, {"generation": 7, "level": 60, "shiny": true, "nature": "Timid", "isHidden": false, "moves":["naturesmadness", "discharge", "agility", "electroball"], "pokeball": "cherishball"}, ], eventOnly: true, unreleasedHidden: true, tier: "OU", }, tapulele: { randomBattleMoves: ["moonblast", "psyshock", "calmmind", "focusblast", "taunt"], randomDoubleBattleMoves: ["moonblast", "psychic", "dazzlinggleam", "focusblast", "protect", "taunt", "shadowball", "thunderbolt"], eventPokemon: [ {"generation": 7, "level": 60, "isHidden": false, "moves":["naturesmadness", "extrasensory", "flatter", "moonblast"]}, ], eventOnly: true, unreleasedHidden: true, tier: "OU", }, tapubulu: { randomBattleMoves: ["woodhammer", "hornleech", "stoneedge", "superpower", "megahorn", "bulkup"], randomDoubleBattleMoves: ["woodhammer", "hornleech", "stoneedge", "superpower", "leechseed", "protect", "naturesmadness"], eventPokemon: [ {"generation": 7, "level": 60, "isHidden": false, "moves":["naturesmadness", "zenheadbutt", "megahorn", "skullbash"]}, ], eventOnly: true, unreleasedHidden: true, tier: "OU", }, tapufini: { randomBattleMoves: ["calmmind", "moonblast", "surf", "substitute", "icebeam", "hydropump"], randomDoubleBattleMoves: ["muddywater", "moonblast", "calmmind", "icebeam", "healpulse", "protect", "taunt", "swagger"], eventPokemon: [ {"generation": 7, "level": 60, "isHidden": false, "moves":["naturesmadness", "muddywater", "aquaring", "hydropump"]}, ], eventOnly: true, unreleasedHidden: true, tier: "OU", }, cosmog: { eventPokemon: [ {"generation": 7, "level": 5, "moves":["splash"]}, ], eventOnly: true, tier: "LC", }, cosmoem: { tier: "NFE", }, solgaleo: { randomBattleMoves: ["sunsteelstrike", "zenheadbutt", "flareblitz", "morningsun", "stoneedge", "earthquake"], randomDoubleBattleMoves: ["wideguard", "protect", "sunsteelstrike", "morningsun", "zenheadbutt", "flareblitz"], eventPokemon: [ {"generation": 7, "level": 55, "moves":["sunsteelstrike", "cosmicpower", "crunch", "zenheadbutt"]}, ], tier: "Uber", }, lunala: { randomBattleMoves: ["moongeistbeam", "psyshock", "calmmind", "focusblast", "roost"], randomDoubleBattleMoves: ["wideguard", "protect", "roost", "moongeistbeam", "psychic", "focusblast"], eventPokemon: [ {"generation": 7, "level": 55, "moves":["moongeistbeam", "cosmicpower", "nightdaze", "shadowball"]}, ], tier: "Uber", }, nihilego: { randomBattleMoves: ["stealthrock", "acidspray", "powergem", "toxicspikes", "sludgewave"], randomDoubleBattleMoves: ["powergem", "sludgebomb", "grassknot", "protect", "thunderbolt", "hiddenpowerice"], eventPokemon: [ {"generation": 7, "level": 55, "moves":["powergem", "mirrorcoat", "acidspray", "venomdrench"]}, ], eventOnly: true, tier: "UU", }, buzzwole: { randomBattleMoves: ["superpower", "leechlife", "stoneedge", "poisonjab", "earthquake"], randomDoubleBattleMoves: ["hammerarm", "superpower", "leechlife", "icepunch", "poisonjab"], eventPokemon: [ {"generation": 7, "level": 65, "moves":["counter", "hammerarm", "lunge", "dynamicpunch"]}, ], eventOnly: true, tier: "BL", }, pheromosa: { randomBattleMoves: ["highjumpkick", "uturn", "icebeam", "poisonjab", "bugbuzz"], randomDoubleBattleMoves: ["highjumpkick", "uturn", "icebeam", "poisonjab", "bugbuzz", "protect", "speedswap"], eventPokemon: [ {"generation": 7, "level": 60, "moves":["triplekick", "lunge", "bugbuzz", "mefirst"]}, ], eventOnly: true, tier: "Uber", }, xurkitree: { randomBattleMoves: ["thunderbolt", "voltswitch", "energyball", "dazzlinggleam", "hiddenpowerice"], randomDoubleBattleMoves: ["thunderbolt", "hiddenpowerice", "tailglow", "protect", "energyball", "hypnosis"], eventPokemon: [ {"generation": 7, "level": 65, "moves":["hypnosis", "discharge", "electricterrain", "powerwhip"]}, ], eventOnly: true, tier: "BL", }, celesteela: { randomBattleMoves: ["autotomize", "heavyslam", "airslash", "fireblast", "earthquake", "leechseed", "protect"], randomDoubleBattleMoves: ["protect", "heavyslam", "fireblast", "earthquake", "wideguard", "leechseed", "flamethrower", "substitute"], eventPokemon: [ {"generation": 7, "level": 65, "moves":["autotomize", "seedbomb", "skullbash", "irondefense"]}, ], eventOnly: true, tier: "OU", }, kartana: { randomBattleMoves: ["leafblade", "sacredsword", "smartstrike", "psychocut", "swordsdance"], randomDoubleBattleMoves: ["leafblade", "sacredsword", "smartstrike", "psychocut", "protect", "nightslash"], eventPokemon: [ {"generation": 7, "level": 60, "moves":["leafblade", "xscissor", "detect", "airslash"]}, ], eventOnly: true, tier: "OU", }, guzzlord: { randomBattleMoves: ["dracometeor", "hammerarm", "crunch", "earthquake", "fireblast"], randomDoubleBattleMoves: ["dracometeor", "crunch", "darkpulse", "wideguard", "fireblast", "protect"], eventPokemon: [ {"generation": 7, "level": 70, "moves":["thrash", "gastroacid", "heavyslam", "wringout"]}, ], eventOnly: true, tier: "PU", }, necrozma: { randomBattleMoves: ["calmmind", "psychic", "darkpulse", "moonlight", "stealthrock", "storedpower"], randomDoubleBattleMoves: ["calmmind", "autotomize", "irondefense", "trickroom", "moonlight", "storedpower", "psyshock"], eventPokemon: [ {"generation": 7, "level": 75, "moves":["stealthrock", "irondefense", "wringout", "prismaticlaser"]}, ], eventOnly: true, tier: "BL3", }, magearna: { randomBattleMoves: ["shiftgear", "flashcannon", "aurasphere", "fleurcannon", "ironhead", "thunderbolt", "icebeam"], randomDoubleBattleMoves: ["dazzlinggleam", "flashcannon", "substitute", "protect", "trickroom", "fleurcannon", "aurasphere", "voltswitch"], eventPokemon: [ {"generation": 7, "level": 50, "moves":["fleurcannon", "flashcannon", "luckychant", "helpinghand"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "OU", }, magearnaoriginal: { isUnreleased: true, tier: "Unreleased", }, marshadow: { randomBattleMoves: ["spectralthief", "closecombat", "stoneedge", "shadowsneak", "icepunch"], randomDoubleBattleMoves: ["spectralthief", "closecombat", "shadowsneak", "icepunch", "protect"], eventPokemon: [ {"generation": 7, "level": 50, "moves":["spectralthief", "closecombat", "forcepalm", "shadowball"], "pokeball": "cherishball"}, ], eventOnly: true, tier: "Uber", }, missingno: { randomBattleMoves: ["watergun", "skyattack", "doubleedge", "metronome"], isNonstandard: true, tier: "Illegal", }, tomohawk: { randomBattleMoves: ["aurasphere", "roost", "stealthrock", "rapidspin", "hurricane", "airslash", "taunt", "substitute", "toxic", "naturepower", "earthpower"], isNonstandard: true, tier: "CAP", }, necturna: { randomBattleMoves: ["powerwhip", "hornleech", "willowisp", "shadowsneak", "stoneedge", "sacredfire", "boltstrike", "vcreate", "extremespeed", "closecombat", "shellsmash", "spore", "milkdrink", "batonpass", "stickyweb"], isNonstandard: true, tier: "CAP", }, mollux: { randomBattleMoves: ["fireblast", "thunderbolt", "sludgebomb", "thunderwave", "willowisp", "recover", "rapidspin", "trick", "stealthrock", "toxicspikes", "lavaplume"], isNonstandard: true, tier: "CAP", }, aurumoth: { randomBattleMoves: ["dragondance", "quiverdance", "closecombat", "bugbuzz", "hydropump", "megahorn", "psychic", "blizzard", "thunder", "focusblast", "zenheadbutt"], isNonstandard: true, tier: "CAP", }, malaconda: { randomBattleMoves: ["powerwhip", "glare", "toxic", "suckerpunch", "rest", "substitute", "uturn", "synthesis", "rapidspin", "knockoff"], isNonstandard: true, tier: "CAP", }, cawmodore: { randomBattleMoves: ["bellydrum", "bulletpunch", "drainpunch", "acrobatics", "drillpeck", "substitute", "ironhead", "quickattack"], isNonstandard: true, tier: "CAP", }, volkraken: { randomBattleMoves: ["scald", "powergem", "hydropump", "memento", "hiddenpowerice", "fireblast", "willowisp", "uturn", "substitute", "flashcannon", "surf"], isNonstandard: true, tier: "CAP", }, plasmanta: { randomBattleMoves: ["sludgebomb", "thunderbolt", "substitute", "hiddenpowerice", "psyshock", "dazzlinggleam", "flashcannon"], isNonstandard: true, tier: "CAP", }, naviathan: { randomBattleMoves: ["dragondance", "waterfall", "ironhead", "iciclecrash"], isNonstandard: true, tier: "CAP", }, crucibelle: { randomBattleMoves: ["headsmash", "gunkshot", "coil", "lowkick", "uturn", "stealthrock"], isNonstandard: true, tier: "CAP", }, crucibellemega: { randomBattleMoves: ["headsmash", "gunkshot", "coil", "woodhammer", "lowkick", "uturn"], requiredItem: "Crucibellite", isNonstandard: true, tier: "CAP", }, kerfluffle: { randomBattleMoves: ["aurasphere", "moonblast", "taunt", "partingshot", "gigadrain", "yawn"], isNonstandard: true, eventPokemon: [ {"generation": 6, "level": 16, "isHidden": false, "abilities":["naturalcure"], "moves":["celebrate", "holdhands", "fly", "metronome"], "pokeball": "cherishball"}, ], tier: "CAP", }, syclant: { randomBattleMoves: ["bugbuzz", "icebeam", "blizzard", "earthpower", "spikes", "superpower", "tailglow", "uturn", "focusblast"], isNonstandard: true, tier: "CAP", }, revenankh: { randomBattleMoves: ["bulkup", "shadowsneak", "drainpunch", "rest", "moonlight", "icepunch", "glare"], isNonstandard: true, tier: "CAP", }, pyroak: { randomBattleMoves: ["leechseed", "lavaplume", "substitute", "protect", "gigadrain"], isNonstandard: true, tier: "CAP", }, fidgit: { randomBattleMoves: ["spikes", "stealthrock", "toxicspikes", "wish", "rapidspin", "encore", "uturn", "sludgebomb", "earthpower"], isNonstandard: true, tier: "CAP", }, stratagem: { randomBattleMoves: ["paleowave", "earthpower", "fireblast", "gigadrain", "calmmind", "substitute"], isNonstandard: true, tier: "CAP", }, arghonaut: { randomBattleMoves: ["recover", "bulkup", "waterfall", "drainpunch", "crosschop", "stoneedge", "thunderpunch", "aquajet", "machpunch"], isNonstandard: true, tier: "CAP", }, kitsunoh: { randomBattleMoves: ["shadowstrike", "earthquake", "superpower", "meteormash", "uturn", "icepunch", "trick", "willowisp"], isNonstandard: true, tier: "CAP", }, cyclohm: { randomBattleMoves: ["slackoff", "dracometeor", "dragonpulse", "fireblast", "thunderbolt", "hydropump", "discharge", "healbell"], isNonstandard: true, tier: "CAP", }, colossoil: { randomBattleMoves: ["earthquake", "crunch", "suckerpunch", "uturn", "rapidspin", "encore", "pursuit", "knockoff"], isNonstandard: true, tier: "CAP", }, krilowatt: { randomBattleMoves: ["surf", "thunderbolt", "icebeam", "earthpower"], isNonstandard: true, tier: "CAP", }, voodoom: { randomBattleMoves: ["aurasphere", "darkpulse", "taunt", "painsplit", "substitute", "hiddenpowerice", "vacuumwave", "flashcannon"], isNonstandard: true, tier: "CAP", }, syclar: { isNonstandard: true, tier: "CAP LC", }, embirch: { isNonstandard: true, tier: "CAP LC", }, flarelm: { isNonstandard: true, tier: "CAP NFE", }, breezi: { isNonstandard: true, tier: "CAP LC", }, scratchet: { isNonstandard: true, tier: "CAP LC", }, necturine: { isNonstandard: true, tier: "CAP LC", }, cupra: { isNonstandard: true, tier: "CAP LC", }, argalis: { isNonstandard: true, tier: "CAP NFE", }, brattler: { isNonstandard: true, tier: "CAP LC", }, cawdet: { isNonstandard: true, tier: "CAP LC", }, volkritter: { isNonstandard: true, tier: "CAP LC", }, snugglow: { isNonstandard: true, tier: "CAP LC", }, floatoy: { isNonstandard: true, tier: "CAP LC", }, caimanoe: { isNonstandard: true, tier: "CAP NFE", }, pluffle: { isNonstandard: true, tier: "CAP LC", }, pokestarufo: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 38, "moves": ["bubblebeam", "counter", "recover", "signalbeam"]}, ], gen: 5, tier: "Illegal", }, pokestarufo2: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 47, "moves": ["darkpulse", "flamethrower", "hyperbeam", "icebeam"]}, ], gen: 5, tier: "Illegal", }, pokestarbrycenman: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 56, "moves": ["icebeam", "nightshade", "psychic", "uturn"]}, ], gen: 5, tier: "Illegal", }, pokestarmt: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 63, "moves": ["earthquake", "ironhead", "spark", "surf"]}, ], gen: 5, tier: "Illegal", }, pokestarmt2: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 72, "moves": ["dragonpulse", "flamethrower", "metalburst", "thunderbolt"]}, ], gen: 5, tier: "Illegal", }, pokestartransport: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 20, "moves": ["clearsmog", "flameburst", "discharge"]}, {"generation": 5, "level": 50, "moves": ["iciclecrash", "overheat", "signalbeam"]}, ], gen: 5, tier: "Illegal", }, pokestargiant: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 99, "moves": ["crushgrip", "focuspunch", "growl", "rage"]}, ], gen: 5, tier: "Illegal", }, pokestargiant2: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 99, "moves": ["crushgrip", "doubleslap", "teeterdance", "stomp"]}, ], gen: 5, tier: "Illegal", }, pokestarhumanoid: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 20, "gender": "M", "moves": ["scratch", "shadowclaw", "acid"]}, {"generation": 5, "level": 30, "gender": "M", "moves": ["darkpulse", "shadowclaw", "slash"]}, {"generation": 5, "level": 20, "gender": "F", "moves": ["acid", "nightslash"]}, {"generation": 5, "level": 20, "gender": "M", "moves": ["acid", "doubleedge"]}, {"generation": 5, "level": 20, "gender": "F", "moves": ["acid", "rockslide"]}, {"generation": 5, "level": 20, "gender": "M", "moves": ["acid", "thudnerpunch"]}, {"generation": 5, "level": 20, "gender": "F", "moves": ["acid", "icepunch"]}, {"generation": 5, "level": 40, "gender": "F", "moves": ["explosion", "selfdestruct"]}, {"generation": 5, "level": 40, "gender": "F", "moves": ["shadowclaw", "scratch"]}, {"generation": 5, "level": 40, "gender": "M", "moves": ["nightslash", "scratch"]}, {"generation": 5, "level": 40, "gender": "M", "moves": ["doubleedge", "scratch"]}, {"generation": 5, "level": 40, "gender": "F", "moves": ["rockslide", "scratch"]}, ], gen: 5, tier: "Illegal", }, pokestarmonster: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 50, "moves": ["darkpulse", "confusion"]}, ], gen: 5, tier: "Illegal", }, pokestarf00: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 10, "moves": ["teeterdance", "growl", "flail", "chatter"]}, {"generation": 5, "level": 58, "moves": ["needlearm", "headsmash", "headbutt", "defensecurl"]}, {"generation": 5, "level": 60, "moves": ["hammerarm", "perishsong", "ironhead", "thrash"]}, ], gen: 5, tier: "Illegal", }, pokestarf002: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 52, "moves": ["flareblitz", "ironhead", "psychic", "wildcharge"]}, ], gen: 5, tier: "Illegal", }, pokestarspirit: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 99, "moves": ["crunch", "dualchop", "slackoff", "swordsdance"]}, ], gen: 5, tier: "Illegal", }, pokestarblackdoor: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 53, "moves": ["luckychant", "amnesia", "ingrain", "rest"]}, {"generation": 5, "level": 70, "moves": ["batonpass", "counter", "flamecharge", "toxic"]}, ], gen: 5, tier: "Illegal", }, pokestarwhitedoor: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 7, "moves": ["batonpass", "inferno", "mirrorcoat", "toxic"]}, ], gen: 5, tier: "Illegal", }, pokestarblackbelt: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 30, "moves": ["focuspunch", "machpunch", "taunt"]}, {"generation": 5, "level": 40, "moves": ["machpunch", "hammerarm", "jumpkick"]}, ], gen: 5, tier: "Illegal", }, pokestargiantpropo2: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 99, "moves": ["crushgrip", "doubleslap", "teeterdance", "stomp"]}, ], gen: 5, tier: "Illegal", }, pokestarufopropu2: { isNonstandard: true, eventPokemon: [ {"generation": 5, "level": 47, "moves": ["darkpulse", "flamethrower", "hyperbeam", "icebeam"]}, ], gen: 5, tier: "Illegal", }, };<|fim▁end|>
<|file_name|>FixWrongMasterEpochDirectoryTest.java<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2013 Michael Berlin, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ package org.xtreemfs.test.osd.rwre; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException;<|fim▁hole|>import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import org.xtreemfs.osd.storage.HashStorageLayout; import org.xtreemfs.osd.storage.MetadataCache; import org.xtreemfs.test.SetupUtils; import org.xtreemfs.test.TestHelper; public class FixWrongMasterEpochDirectoryTest { @Rule public final TestRule testLog = TestHelper.testLog; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { } @Test public void testAutomaticMoveToCorrectDirectory() throws IOException { final String globalFileId = "f32b0854-91eb-44d8-adf8-65bb8baf5f60:13193"; final String correctedFileId = globalFileId; final String brokenFileId = "/" + correctedFileId; final HashStorageLayout hsl = new HashStorageLayout(SetupUtils.createOSD1Config(), new MetadataCache()); // Cleanup previous runs. hsl.deleteFile(brokenFileId, true); hsl.deleteFile(correctedFileId, true); final File brokenFileDir = new File(hsl.generateAbsoluteFilePath(brokenFileId)); final File correctedFileDir = new File(hsl.generateAbsoluteFilePath(correctedFileId)); // Set masterepoch using the wrong id. assertFalse(brokenFileDir.isDirectory()); assertFalse(correctedFileDir.isDirectory()); hsl.setMasterEpoch(brokenFileId, 1); assertTrue(brokenFileDir.isDirectory()); // Get the masterepoch with the correct id. assertEquals(1, hsl.getMasterEpoch(correctedFileId)); assertFalse(brokenFileDir.isDirectory()); assertTrue(correctedFileDir.isDirectory()); // Get the masterepoch of a file which does not exist. assertEquals(0, hsl.getMasterEpoch("fileIdDoesNotExist")); } }<|fim▁end|>
import org.junit.After;
<|file_name|>[id].ts<|end_file_name|><|fim▁begin|>import fs from "fs"; import path from "path"; import * as showdown from "showdown"; import { POSTS_DIR, getPosts } from "."; const converter: showdown.Converter = new showdown.Converter(); export const getFullPost = async (posts: any[], slug: string): Promise<any> => { const postData = posts.find((post) => post.slug === slug); if (!postData) { return { error: true, }; } if (postData.url) { return { error: true, }; } <|fim▁hole|> POSTS_DIR, postData.path, "article.md" ); const entry: string = await fs.promises.readFile(articlePath, "utf-8"); return { ...postData, entry: converter.makeHtml(entry), }; } catch (error) { console.error(error); if (postData.url) { return { redirect: postData.url, }; } } }; export default async (req, res) => { const posts = await getPosts(); const post = await getFullPost(posts, req.url.split("/").pop()); return res.status(200).json(post); };<|fim▁end|>
try { const articlePath: string = path.resolve(
<|file_name|>get_template.go<|end_file_name|><|fim▁begin|>// Copyright 2012-2015 Oliver Eilhard. All rights reserved. // Use of this source code is governed by a MIT-license. // See http://olivere.mit-license.org/license.txt for details. package elastic import ( "encoding/json" "fmt" "net/url" "github.com/devacto/grobot/Godeps/_workspace/src/gopkg.in/olivere/elastic.v2/uritemplates" ) // GetTemplateService reads a search template. // It is documented at http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-template.html. type GetTemplateService struct { client *Client pretty bool id string version interface{} versionType string } <|fim▁hole|> client: client, } } // Id is the template ID. func (s *GetTemplateService) Id(id string) *GetTemplateService { s.id = id return s } // Version is an explicit version number for concurrency control. func (s *GetTemplateService) Version(version interface{}) *GetTemplateService { s.version = version return s } // VersionType is a specific version type. func (s *GetTemplateService) VersionType(versionType string) *GetTemplateService { s.versionType = versionType return s } // buildURL builds the URL for the operation. func (s *GetTemplateService) buildURL() (string, url.Values, error) { // Build URL path, err := uritemplates.Expand("/_search/template/{id}", map[string]string{ "id": s.id, }) if err != nil { return "", url.Values{}, err } // Add query string parameters params := url.Values{} if s.version != nil { params.Set("version", fmt.Sprintf("%v", s.version)) } if s.versionType != "" { params.Set("version_type", s.versionType) } return path, params, nil } // Validate checks if the operation is valid. func (s *GetTemplateService) Validate() error { var invalid []string if s.id == "" { invalid = append(invalid, "Id") } if len(invalid) > 0 { return fmt.Errorf("missing required fields: %v", invalid) } return nil } // Do executes the operation and returns the template. func (s *GetTemplateService) Do() (*GetTemplateResponse, error) { // Check pre-conditions if err := s.Validate(); err != nil { return nil, err } // Get URL for request path, params, err := s.buildURL() if err != nil { return nil, err } // Get HTTP response res, err := s.client.PerformRequest("GET", path, params, nil) if err != nil { return nil, err } // Return result ret := new(GetTemplateResponse) if err := json.Unmarshal(res.Body, ret); err != nil { return nil, err } return ret, nil } type GetTemplateResponse struct { Template string `json:"template"` }<|fim▁end|>
// NewGetTemplateService creates a new GetTemplateService. func NewGetTemplateService(client *Client) *GetTemplateService { return &GetTemplateService{
<|file_name|>bitcoin_ky.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="ky" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About VPSCoin</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;VPSCoin&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The VPSCoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Жаң даректи жасоо</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-46"/> <source>These are your VPSCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/><|fim▁hole|> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Verify a message to ensure it was signed with a specified VPSCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>Ө&amp;чүрүү</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation>Дарек</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(аты жок)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation type="unfinished"/> </message> <message> <location line="-58"/> <source>VPSCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation type="unfinished"/> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation type="unfinished"/> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+282"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+251"/> <source>Synchronizing with network...</source> <translation type="unfinished"/> </message> <message> <location line="-319"/> <source>&amp;Overview</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;Транзакциялар</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Quit application</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show information about VPSCoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+259"/> <source>~%n block(s) remaining</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"/> </message> <message> <location line="-256"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Send coins to a VPSCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Modify configuration options for VPSCoin</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>Билдирүүнү &amp;текшерүү...</translation> </message> <message> <location line="-202"/> <source>VPSCoin</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet</source> <translation>Капчык</translation> </message> <message> <location line="+180"/> <source>&amp;About VPSCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>&amp;File</source> <translation>&amp;Файл</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>&amp;Жардам</translation> </message> <message> <location line="+12"/> <source>Tabs toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+60"/> <source>VPSCoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+75"/> <source>%n active connection(s) to VPSCoin network</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="-312"/> <source>About VPSCoin card</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about VPSCoin card</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+297"/> <source>%n minute(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation>Жаңыланган</translation> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid VPSCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+109"/> <source>A fatal error occurred. VPSCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation>Дарек</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+317"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation>(аты жок)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Дарек</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid VPSCoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+420"/> <location line="+12"/> <source>VPSCoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start VPSCoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start VPSCoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>&amp;Тармак</translation> </message> <message> <location line="+6"/> <source>Automatically open the VPSCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the VPSCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Порт:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Терезе</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting VPSCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show VPSCoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;Жарайт</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Жокко чыгаруу</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation>жарыяланбаган</translation> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting VPSCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the VPSCoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-160"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-107"/> <source>Wallet</source> <translation>Капчык</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation>синхрондоштурулган эмес</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+348"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Ачуу</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the VPSCoin-Qt help message to get a list with possible VPSCoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Консоль</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>VPSCoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>VPSCoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the VPSCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Консолду тазалоо</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the VPSCoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 VPS</source> <translation type="unfinished"/> </message> <message> <location line="-191"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>&amp;Бардыгын тазалоо</translation> </message> <message> <location line="+28"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>123.456 VPS</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Жөнөтүү</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a VPSCoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+251"/> <source>WARNING: Invalid VPSCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(аты жок)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Даректи алмашуу буферинен коюу</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a VPSCoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>Даректи алмашуу буферинен коюу</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this VPSCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>&amp;Бардыгын тазалоо</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified VPSCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a VPSCoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter VPSCoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>%1/тармакта эмес</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation>Билдирүү</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-211"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation>Дарек</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation type="unfinished"/> </message> <message> <location line="+190"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+55"/> <location line="+16"/> <source>All</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <source>Today</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This week</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Last month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This year</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Range...</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>To yourself</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Other</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Min amount</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+144"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Address</source> <translation>Дарек</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+206"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+33"/> <source>VPSCoin version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send command to -server or VPSCoind</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Options:</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify configuration file (default: VPSCoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: VPSCoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"/> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="-88"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-38"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong VPSCoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+94"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-82"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=VPSCoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;VPSCoin Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-158"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. VPSCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-98"/> <source>VPSCoin</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of VPSCoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart VPSCoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <location line="-103"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="+122"/> <source>Unable to bind to %s on this computer. VPSCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Done loading</source> <translation type="unfinished"/> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Error</source> <translation>Ката</translation> </message> <message> <location line="+6"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS><|fim▁end|>
<source>Sign a message to prove you own a VPSCoin address</source> <translation type="unfinished"/> </message> <message>
<|file_name|>run.rs<|end_file_name|><|fim▁begin|>// Copyright 2017, 2019 Guanhao Yin <[email protected]> // This file is part of TiTun. // TiTun 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. // TiTun 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 TiTun. If not, see <https://www.gnu.org/licenses/>. use crate::async_utils::AsyncScope; #[cfg(unix)] use crate::cli::daemonize::NotifyHandle; use crate::cli::network_config::network_config; use crate::cli::Config; use crate::ipc::ipc_server; use crate::wireguard::*; use anyhow::Context; use std::net::*; use tokio::sync::oneshot; #[cfg(not(unix))] type NotifyHandle = (); #[cfg(unix)] async fn do_reload( config_file_path: std::path::PathBuf, wg: &std::sync::Arc<WgState>, ) -> anyhow::Result<()> { let new_config = tokio::task::spawn_blocking(move || super::load_config_from_path(&config_file_path, false)) .await .expect("join load_config_from_path")?; crate::cli::reload(wg, new_config).await } #[cfg(unix)] async fn reload_on_sighup( config_file_path: Option<std::path::PathBuf>, weak: std::sync::Weak<WgState>, ) -> anyhow::Result<()> { use tokio::signal::unix::{signal, SignalKind}; let mut hangups = signal(SignalKind::hangup())?; while hangups.recv().await.is_some() { if let Some(ref config_file_path) = config_file_path { if let Some(wg) = weak.upgrade() { info!("reloading"); do_reload(config_file_path.clone(), &wg) .await .unwrap_or_else(|e| warn!("error in reloading: {:#}", e)); } } } Ok(()) } pub async fn run( c: Config<SocketAddr>, notify: Option<NotifyHandle>, stop_rx: Option<oneshot::Receiver<()>>, ) -> anyhow::Result<()> { #[cfg(unix)] let mut c = c; let scope0 = AsyncScope::new(); scope0.spawn_canceller(async move { tokio::signal::ctrl_c() .await .unwrap_or_else(|e| warn!("ctrl_c failed: {:#}", e)); info!("Received SIGINT or Ctrl-C, shutting down."); }); if let Some(stop_rx) = stop_rx { scope0.spawn_canceller(async move { stop_rx.await.unwrap(); }); } #[cfg(unix)] scope0.spawn_canceller(async move { use tokio::signal::unix::{signal, SignalKind}; let mut term = signal(SignalKind::terminate()).unwrap(); term.recv().await; info!("Received SIGTERM, shutting down."); }); let dev_name = c.interface.name.clone().unwrap(); let tun = AsyncTun::open(&dev_name).context("failed to open tun interface")?; if let Err(e) = network_config(&c).await { warn!("failed to configure network: {:#}", e); } let wg = WgState::new(tun)?; info!("setting privatge key"); wg.set_key(c.interface.private_key); if let Some(port) = c.interface.listen_port { info!("setting port"); wg.set_port(port).await.context("failed to set port")?; } if let Some(fwmark) = c.interface.fwmark { info!("setting fwmark"); wg.set_fwmark(fwmark).context("failed to set fwmark")?; } for p in c.peers { info!("adding peer {}", base64::encode(&p.public_key)); wg.add_peer(&p.public_key)?; wg.set_peer(SetPeerCommand { public_key: p.public_key, preshared_key: p.preshared_key, endpoint: p.endpoint, keepalive: p.keepalive.map(|x| x.get()), replace_allowed_ips: true, allowed_ips: p.allowed_ips, })?; } let weak = std::sync::Arc::downgrade(&wg); <|fim▁hole|> scope0.spawn_canceller(wg.clone().task_rx()); scope0.spawn_canceller(wg.clone().task_tx()); #[cfg(unix)] { let weak1 = weak.clone(); let config_file_path = c.general.config_file_path.take(); scope0.spawn_canceller(async move { reload_on_sighup(config_file_path, weak1) .await .unwrap_or_else(|e| warn!("error in reload_on_sighup: {:#}", e)) }); } let (ready_tx, ready_rx) = tokio::sync::oneshot::channel::<()>(); scope0.spawn_canceller(async move { ipc_server(weak, &dev_name, ready_tx) .await .unwrap_or_else(|e| error!("IPC server error: {:#}", e)) }); if ready_rx.await.is_ok() { #[cfg(unix)] { if c.general.group.is_some() || c.general.user.is_some() { let p = privdrop::PrivDrop::default(); let p = if let Some(ref user) = c.general.user { p.user(user) } else { p }; let p = if let Some(ref group) = c.general.group { p.group(group) } else { p }; p.apply().context("failed to change user and group")?; } if c.general.foreground { super::systemd::notify_ready() .unwrap_or_else(|e| warn!("failed to notify systemd: {:#}", e)); } else { notify .unwrap() .notify(0) .context("failed to notify grand parent")?; } } // So rustc does not warn about unused. #[cfg(not(unix))] let _notify = notify; } scope0.cancelled().await; Ok(()) }<|fim▁end|>
scope0.spawn_canceller(wg.clone().task_update_cookie_secret()); #[cfg(not(windows))] scope0.spawn_canceller(wg.clone().task_update_mtu());
<|file_name|>summary_key_matcher.py<|end_file_name|><|fim▁begin|>from ert.cwrap import CWrapper, BaseCClass from ert.enkf import ENKF_LIB from ert.util import StringList class SummaryKeyMatcher(BaseCClass): def __init__(self): c_ptr = SummaryKeyMatcher.cNamespace().alloc() super(SummaryKeyMatcher, self).__init__(c_ptr) <|fim▁hole|> return SummaryKeyMatcher.cNamespace().add_key(self, key) def __len__(self): return SummaryKeyMatcher.cNamespace().size(self) def __contains__(self, key): return SummaryKeyMatcher.cNamespace().match_key(self, key) def isRequired(self, key): """ @rtype: bool """ return SummaryKeyMatcher.cNamespace().is_required(self, key) def keys(self): """ @rtype: StringList """ return SummaryKeyMatcher.cNamespace().keys(self) def free(self): SummaryKeyMatcher.cNamespace().free(self) cwrapper = CWrapper(ENKF_LIB) cwrapper.registerObjectType("summary_key_matcher", SummaryKeyMatcher) SummaryKeyMatcher.cNamespace().alloc = cwrapper.prototype("c_void_p summary_key_matcher_alloc()") SummaryKeyMatcher.cNamespace().free = cwrapper.prototype("void summary_key_matcher_free(summary_key_matcher)") SummaryKeyMatcher.cNamespace().size = cwrapper.prototype("int summary_key_matcher_get_size(summary_key_matcher)") SummaryKeyMatcher.cNamespace().add_key = cwrapper.prototype("void summary_key_matcher_add_summary_key(summary_key_matcher, char*)") SummaryKeyMatcher.cNamespace().match_key = cwrapper.prototype("bool summary_key_matcher_match_summary_key(summary_key_matcher, char*)") SummaryKeyMatcher.cNamespace().keys = cwrapper.prototype("stringlist_obj summary_key_matcher_get_keys(summary_key_matcher)") SummaryKeyMatcher.cNamespace().is_required = cwrapper.prototype("bool summary_key_matcher_summary_key_is_required(summary_key_matcher, char*)")<|fim▁end|>
def addSummaryKey(self, key): assert isinstance(key, str)
<|file_name|>TreeTabDemo.js<|end_file_name|><|fim▁begin|>/** * @author fanguozhu */ $(function() { var tab = new TabPanel("tab",true); var f_tree = new Fieldset("f_tree","公司列表",{ state: Fieldset.OPEN_STATE, topdown: false }); var mytree = new PorTreeT("tree", "-1", "手机公司",{isDefaultClick:0} ); var dw = new DataWrapper(); dw.service("PRtree"); mytree.dataWrapper(dw); tab.dataWrapper(dw); tab.addChangeObserver(function(src, msg){ var dw = this.dataWrapper(); if (!dw) return; var label = msg.data.label; <|fim▁hole|> this.setTitle(i,"["+name+"]公司产品["+i+"]"); } else { this.setTitle(i,"全部公司产品["+i+"]"); } } },PorMessage.MSG_TREE_ONCLICK); var dw1 = new DataWrapper(); dw1.service("PR02"); var dw2 = new DataWrapper(); dw2.service("PR02"); var dw3 = new DataWrapper(); dw3.service("PR02"); var dg1 = new DataGrid("grid_1",{autoDraw:true,readonly:true}); dg1.dataWrapper(dw1); var dg2 = new DataGrid("grid_2",{autoDraw:true,readonly:true}); dg2.dataWrapper(dw2); var dg3 = new DataGrid("grid_3",{autoDraw:true,readonly:true}); dg3.dataWrapper(dw3); var mapping = { master:["label"], sub:["company"] }; PorUtil.linkTreeAndGrid( dw,[{ sub:dw1, mapping:mapping, tabs:{ tab:[0,1] //配置在'tab'的第1个tab页需要加载 } },{ sub:dw2, mapping:mapping, tabs:{ tab:[2] //配置在'tab'的第2个tab页需要加载 } },{ sub:dw3, mapping:mapping, tabs:{ tab:[3] //配置在'tab'的第3个tab页需要加载 } }]); mytree.init(); });<|fim▁end|>
var name = msg.data.name; for (var i=1;i<=3;i++) { if (label) {
<|file_name|>SolveTSPSimulatedAnnealing.py<|end_file_name|><|fim▁begin|>#============================================================================== #description : Solves travelling salesman problem by using Hill Climbing. #author : Yakup Cengiz #date : 20151121 #version : 0.1 #notes : #python_version : 3.5.0 #Reference : http://www.psychicorigami.com/category/tsp/ #============================================================================== import math import sys import os import random CommonPath = os.path.abspath(os.path.join('..', 'Common')) sys.path.append(CommonPath) import tsp def GenerateInitialPath(tour_length): tour=list(range(tour_length)) random.shuffle(tour) return tour MAX_ITERATION = 50000 def reversed_sections(tour): '''generator to return all possible variations where the section between two cities are swapped''' for i,j in tsp.AllEdges(len(tour)): if i != j: copy=tour[:] if i < j: copy[i:j+1]=reversed(tour[i:j+1]) else: copy[i+1:]=reversed(tour[:j]) copy[:j]=reversed(tour[i+1:]) if copy != tour: # no point returning the same tour yield copy def kirkpatrick_cooling(start_temp, alpha): T = start_temp while True: yield T T = alpha * T def P(prev_score,next_score,temperature): if next_score > prev_score:<|fim▁hole|> class ObjectiveFunction: '''class to wrap an objective function and keep track of the best solution evaluated''' def __init__(self,objective_function): self.objective_function=objective_function self.best=None self.best_score=None def __call__(self,solution): score=self.objective_function(solution) if self.best is None or score > self.best_score: self.best_score=score self.best=solution return score def ApplySimulatedAnnealing(init_function,move_operator,objective_function,max_evaluations,start_temp,alpha): # wrap the objective function (so we record the best) objective_function=ObjectiveFunction(objective_function) current = init_function() current_score = objective_function(current) iterationCount = 1 cooling_schedule = kirkpatrick_cooling(start_temp, alpha) for temperature in cooling_schedule: done = False # examine moves around our current position for next in move_operator(current): if iterationCount >= max_evaluations: done=True break next_score=objective_function(next) iterationCount+=1 # probablistically accept this solution always accepting better solutions p = P(current_score, next_score, temperature) # random.random() basic function random() generates a random float uniformly in the range [0.0, 1.0). # p function returns data in range [0.0, 1.0] if random.random() < p: current = next current_score= next_score break # see if completely finished if done: break best_score = objective_function.best_score best = objective_function.best return (iterationCount,best_score,best) def SolveTSP(): print("Starting to solve travel salesman problem") coordinates = tsp.ReadCoordinatesFromFile(".\cityCoordinates.csv") distance_matrix = tsp.ComputeDistanceMatrix(coordinates); init_function = lambda: GenerateInitialPath(len(coordinates)) objective_function = lambda tour: -tsp.ComputeTourLength(distance_matrix, tour) start_temp,alpha = 100, 0.995 iterationCount,best_score,shortestPath = ApplySimulatedAnnealing(init_function, reversed_sections, objective_function, MAX_ITERATION,start_temp,alpha) print(iterationCount, best_score, shortestPath); tsp.DrawPath(coordinates, shortestPath, "TSP.png"); if __name__ == "__main__": SolveTSP();<|fim▁end|>
return 1.0 else: return math.exp( -abs(next_score-prev_score)/temperature )
<|file_name|>models.py<|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 https://mozilla.org/MPL/2.0/. <|fim▁hole|> name = models.CharField(max_length=100, db_index=True, unique=True) value = models.CharField(max_length=200) class Meta: app_label = "base" def __str__(self): return "%s=%s" % (self.name, self.value) def get_config_dict(): return {c.name: c.value for c in ConfigValue.objects.all()}<|fim▁end|>
from django.db import models class ConfigValue(models.Model):
<|file_name|>my.js<|end_file_name|><|fim▁begin|>var yt = yt || {}; //加载图片 yt.loadImg = function ($imgs, time) { var _time = 0; time = time || 200; $imgs.each(function () { var $that = $(this); if ($that.data('hasload')) { return false; } setTimeout(function () { $that.fadeOut(0); $that.attr('src', $that.data('src')); $that.attr('data-hasload', 'true'); $that.fadeIn(500); }, _time); _time += time; }); }; //wap端环境 yt.isWap = function () { var s = navigator.userAgent.toLowerCase(); var ipad = s.match(/ipad/i) == "ipad" , iphone = s.match(/iphone os/i) == "iphone os" , midp = s.match(/midp/i) == "midp" , uc7 = s.match(/rv:1.2.3.4/i) == "rv:1.2.3.4" , uc = s.match(/ucweb/i) == "ucweb" , android = s.match(/android/i) == "android" , ce = s.match(/windows ce/i) == "windows ce" , wm = s.match(/windows mobile/i) == "windows mobile"; if (iphone || midp || uc7 || uc || android || ce || wm || ipad) { return true; } return false; }; //滑动绑定 yt.app = function () { var $swiperContainer = $("#swiper-container1"), $pages = $("#wrapper").children(), $as = $("#nav li a"), $lis = $("#nav li"), $win =$(window), slideCount = $pages.length, nowIndex = 0, acn = "animation", mySwiper, _zx = 1; var params = { selectorClassName: "swiper-container", animationClassName: acn, animationElm: $("." + acn) }; var setCssText = function (prop, value) { return prop + ': ' + value + '; '; }; /* * insertCss(rule) * 向文档<head>底部插入css rule操作 * rule: 传入的css text * */ var insertCss = function (rule) { var head = document.head || document.getElementsByTagName('head')[0], style; if (!!head.getElementsByTagName('style').length) { style = head.getElementsByTagName('style')[0]; if (style.styleSheet) { style.styleSheet.cssText = rule; } else { style.innerHTML = ''; style.appendChild(document.createTextNode(rule)); } } else { style = document.createElement('style'); style.type = 'text/css'; if (style.styleSheet) { style.styleSheet.cssText = rule; } else { style.appendChild(document.createTextNode(rule)); } head.appendChild(style); } }; var setAnimationStyle=function() { var cssText = ''; cssText += '.' + params.animationClassName + '{' + setCssText('display', 'none') + '}' + '.touchstart .' + params.animationClassName + '{' + setCssText('-webkit-animation-duration', '0 !important') + setCssText('-webkit-animation-delay', '0 !important') + setCssText('-webkit-animation-iteration-count', '1 !important') + '}'; var index = mySwiper.activeIndex, _index = index + 1, $ans = $pages.eq(index).find('.' + params.animationClassName); $ans.each(function () { var obj = $(this); _className = obj.attr('data-item'), _animation = obj.attr('data-animation'), _duration = ((obj.attr('data-duration') / 1000) || 1) + 's', _timing = obj.attr('data-timing-function') || 'ease', _delay = ((obj.attr('data-delay') || 0) / 1000) + 's', _count = obj.attr('data-iteration-count') || 1; var _t = '.' + params.selectorClassName + ' .page-' + _index + ' .' + _className; cssText += _t + '{' + setCssText('display', 'block !important') + setCssText('-webkit-animation-name', _animation) + setCssText('-webkit-animation-duration', _duration) + setCssText('-webkit-animation-timing-function', _timing) + setCssText('-webkit-animation-delay', _delay) + setCssText('-webkit-animation-fill-mode', 'both') + setCssText('-webkit-animation-iteration-count', _count) + '}'; }); return cssText; }; //设置动画 var setAms = function () { insertCss(setAnimationStyle()); }; //设置布局 var setLayout = function () { var $wrapers = $("#swiper-container1 .wraper"), $wraper1 = $("#wraper1"), isWap=yt.isWap(), w = 720, h = 1135; var sl = function () { var _w = $wraper1.width(), h = $win.height(), _h = isWap && _w<h?$win.height():_w * 1135 / 720; $wrapers.height(_h); if($win.height()<300){ $(".cn-slidetips").hide(); }else{ $(".cn-slidetips").show(); } }; sl(); $win.resize(sl); }; //滑动绑定函数 var onSlideChangeTime = 0; var onSlideChange = function () { if (onSlideChangeTime>1) { return; } var index = mySwiper.activeIndex; if (nowIndex == index && mySwiper.touches['abs'] < 50) { return; } onSlideChangeTime = 20; setAms(); nowIndex = index || 0; //history.pushState(null, null, "index.html?p=" + (nowIndex + 1)); //执行动画 var timer=setInterval(function () { onSlideChangeTime -= 1; if (onSlideChangeTime == 0) { clearInterval(timer); } },1); }; //触摸结束绑定 var onTouchEnd = function () { /* var index = mySwiper.index; if (nowIndex == slideCount-1 && +mySwiper.touches['diff'] <-50) { return mySwiper.swipeTo(0); }*/ }; //滑动结束绑定 var onSlideChangeEnd = function () { //console.log(mySwiper.activeIndex) onSlideChange(); if(mySwiper.activeIndex == 2){ setTimeout(function(){ mySwiper.swipeTo(3); },2500) } }; //绑定滑动主函数 var bindSwiper = function () { mySwiper = $swiperContainer.swiper({ onTouchEnd: onTouchEnd, onSlideChangeEnd: onSlideChangeEnd, moveStartThreshold:10000 //mousewheelControl:true, //mode: 'vertical' }); }; //滚到下一个屏 var bindNext = function () { $(".next").on("click", function () { mySwiper.activeIndex = mySwiper.activeIndex || 0; var index = mySwiper.activeIndex == slideCount - 1 ? 0 : (mySwiper.activeIndex||0) + 1; mySwiper.swipeTo(index); }); }; var btn1 = $('#btn1').jRange({ from: 0, to: 100, step: 1, scale: [0,25,50,75,100], format: '%s', width: "100%" }); var btn2 = $('#btn2').jRange({ from: 0, to: 100, step: 1, scale: [0,25,50,75,100], format: '%s', width: "100%" }); var btn3 = $('#btn3').jRange({ from: 0, to: 100, step: 1, scale: [0,25,50,75,100], format: '%s', width: "100%" }); var btn4 = $('#btn4').jRange({ from: 0, to: 100, step: 1, scale: [0,25,50,75,100], format: '%s', width: "100%" }); var btn5 = $('#btn5').jRange({ from: 0, to: 100, step: 1, scale: [0,25,50,75,100], format: '%s', width: "100%" }); var btn6 = $('#btn6').jRange({ from: 0, to: 100, step: 1, scale: [0,25,50,75,100], format: '%s', width: "100%" }); //抽选人物 var setPerson = function () { var i = (Math.random()*7).toFixed(0); var span = $("#p3 .cy span"); switch(i){ case "1":$("#p4 .rw").hide().eq(0).show(); $("#p5 .rw").hide().eq(0).show(); span.eq(0).html(1); span.eq(1).html(9); span.eq(2).html(9); span.eq(3).html(2); break; case "2":$("#p4 .rw").hide().eq(1).show(); $("#p5 .rw").hide().eq(1).show(); span.eq(0).html(2); span.eq(1).html(0); span.eq(2).html(0); span.eq(3).html(3); break; case "3":$("#p4 .rw").hide().eq(2).show(); $("#p5 .rw").hide().eq(2).show(); $("#p5 .rw").hide().eq(1).show(); span.eq(0).html(1); span.eq(1).html(9); span.eq(2).html(8); span.eq(3).html(6); break; case "4":$("#p4 .rw").hide().eq(3).show(); $("#p5 .rw").hide().eq(3).show(); $("#p5 .rw").hide().eq(1).show(); span.eq(0).html(1); span.eq(1).html(9); span.eq(2).html(8); span.eq(3).html(6); break; case "5":$("#p4 .rw").hide().eq(4).show(); $("#p5 .rw").hide().eq(4).show(); $("#p5 .rw").hide().eq(1).show(); span.eq(0).html(1); span.eq(1).html(9); span.eq(2).html(9); span.eq(3).html(5); break; default:$("#p4 .rw").hide().eq(5).show(); $("#p5 .rw").hide().eq(5).show(); $("#p5 .rw").hide().eq(1).show(); span.eq(0).html(1); span.eq(1).html(9); span.eq(2).html(9); span.eq(3).html(6); break; } } //更换造型 var setZX = function () { //console.log(_zx%6) $("#p4").removeClass("style"+(_zx%6)).addClass("style"+(_zx+1)%6); $("#p5").removeClass("style"+(_zx%6)).addClass("style"+(_zx+1)%6); _zx++; } //初始化 bindSwiper(); bindNext(); setLayout(); setAms(); setPerson(); setZX(); //mySwiper.swipeTo(0); $("#in .am3 .high").click(function(){ if($(this).next().html()>25){ console.log("跳转页面"); } }); $("#in .am4 .high").click(function(){ if($(this).next().html()<25){ console.log("分享提示"); $("#shareTips").fadeIn(); } }); $("#p1 .high").click(function(){ //console.log($(this).next().html()) if($(this).next().html()<20){ console.log("翻页 goto2") mySwiper.swipeTo(1); } }); $("#p4 .high").click(function(){ //console.log($(this).next().html()) if($(this).next().html()<20){ console.log("翻页 goto5") mySwiper.swipeTo(4); }<|fim▁hole|> $("#p5 .am3 .high").click(function(){ //console.log($(this).next().html()) if($(this).next().html()>80){ console.log("重置"); location.reload(false); /*_zx = 1; setPerson(); setZX(); $(".whiteBg").empty(); $(".btnBox input").val(0) mySwiper.swipeTo(2);*/ } }); $("#p5 .am4 .high").click(function(){ //console.log($(this).next().html()) if($(this).next().html()<25){ console.log("分享提示"); $("#shareTips").fadeIn(); } }); $("#shareTips").click(function(){ $("#shareTips").fadeOut(); }); $("#p2 .am1").click(function(){ mySwiper.swipeTo(2); }); $(".upload").click(function(){ $("#file").click(); }); $("#file").on("change", function(){ // Get a reference to the fileList var files = !!this.files ? this.files : []; // If no files were selected, or no FileReader support, return if (!files.length || !window.FileReader) return; // Only proceed if the selected file is an image if (/^image/.test( files[0].type)){ // Create a new instance of the FileReader var reader = new FileReader(); // Read the local file as a DataURL reader.readAsDataURL(files[0]); // When loaded, set image data as background of div reader.onloadend = function(){ console.log(this.result) $(".whiteBg").empty().append("<img src='"+this.result+"'>"); } }else{ alert("请上传图片"); } }); if(window.DeviceMotionEvent) { var speed = 10; var x = y = z = lastX = lastY = lastZ = 0; window.addEventListener('devicemotion', function(){ var acceleration =event.accelerationIncludingGravity; x = acceleration.x; y = acceleration.y; if((Math.abs(x-lastX) > speed || Math.abs(y-lastY) > speed)) { setZX(); /*if(shake){ shake = false; } if (navigator.vibrate) { navigator.vibrate(1000); } else if (navigator.webkitVibrate) { navigator.webkitVibrate(1000); }*/ } lastX = x; lastY = y; }, false); }else{ //不支持摇一摇 alert("您的手机暂不支持摇一摇!"); } //测试用 $("#p4 .am1").click(function(){ setZX(); }); }; //初始化 yt.init = function () { window.onload = function () { $("#loading").hide(); setTimeout(yt.app); }; }; yt.init();<|fim▁end|>
});
<|file_name|>zwave.py<|end_file_name|><|fim▁begin|>"""Mock helpers for Z-Wave component.""" from pydispatch import dispatcher from tests.async_mock import MagicMock def value_changed(value): """Fire a value changed.""" dispatcher.send( MockNetwork.SIGNAL_VALUE_CHANGED, value=value, node=value.node, network=value.node._network, ) def node_changed(node): """Fire a node changed.""" dispatcher.send(MockNetwork.SIGNAL_NODE, node=node, network=node._network) def notification(node_id, network=None): """Fire a notification.""" dispatcher.send( MockNetwork.SIGNAL_NOTIFICATION, args={"nodeId": node_id}, network=network ) class MockOption(MagicMock): """Mock Z-Wave options.""" def __init__(self, device=None, config_path=None, user_path=None, cmd_line=None): """Initialize a Z-Wave mock options.""" super().__init__() self.device = device self.config_path = config_path self.user_path = user_path self.cmd_line = cmd_line def _get_child_mock(self, **kw): """Create child mocks with right MagicMock class.""" return MagicMock(**kw) class MockNetwork(MagicMock): """Mock Z-Wave network.""" SIGNAL_NETWORK_FAILED = "mock_NetworkFailed" SIGNAL_NETWORK_STARTED = "mock_NetworkStarted" SIGNAL_NETWORK_READY = "mock_NetworkReady" SIGNAL_NETWORK_STOPPED = "mock_NetworkStopped" SIGNAL_NETWORK_RESETTED = "mock_DriverResetted" SIGNAL_NETWORK_AWAKED = "mock_DriverAwaked" SIGNAL_DRIVER_FAILED = "mock_DriverFailed" SIGNAL_DRIVER_READY = "mock_DriverReady" SIGNAL_DRIVER_RESET = "mock_DriverReset" SIGNAL_DRIVER_REMOVED = "mock_DriverRemoved" SIGNAL_GROUP = "mock_Group" SIGNAL_NODE = "mock_Node" SIGNAL_NODE_ADDED = "mock_NodeAdded" SIGNAL_NODE_EVENT = "mock_NodeEvent" SIGNAL_NODE_NAMING = "mock_NodeNaming" SIGNAL_NODE_NEW = "mock_NodeNew" SIGNAL_NODE_PROTOCOL_INFO = "mock_NodeProtocolInfo" SIGNAL_NODE_READY = "mock_NodeReady" SIGNAL_NODE_REMOVED = "mock_NodeRemoved" SIGNAL_SCENE_EVENT = "mock_SceneEvent" SIGNAL_VALUE = "mock_Value" SIGNAL_VALUE_ADDED = "mock_ValueAdded" SIGNAL_VALUE_CHANGED = "mock_ValueChanged" SIGNAL_VALUE_REFRESHED = "mock_ValueRefreshed" SIGNAL_VALUE_REMOVED = "mock_ValueRemoved" SIGNAL_POLLING_ENABLED = "mock_PollingEnabled" SIGNAL_POLLING_DISABLED = "mock_PollingDisabled" SIGNAL_CREATE_BUTTON = "mock_CreateButton" SIGNAL_DELETE_BUTTON = "mock_DeleteButton" SIGNAL_BUTTON_ON = "mock_ButtonOn" SIGNAL_BUTTON_OFF = "mock_ButtonOff" SIGNAL_ESSENTIAL_NODE_QUERIES_COMPLETE = "mock_EssentialNodeQueriesComplete" SIGNAL_NODE_QUERIES_COMPLETE = "mock_NodeQueriesComplete" SIGNAL_AWAKE_NODES_QUERIED = "mock_AwakeNodesQueried" SIGNAL_ALL_NODES_QUERIED = "mock_AllNodesQueried" SIGNAL_ALL_NODES_QUERIED_SOME_DEAD = "mock_AllNodesQueriedSomeDead" SIGNAL_MSG_COMPLETE = "mock_MsgComplete" SIGNAL_NOTIFICATION = "mock_Notification" SIGNAL_CONTROLLER_COMMAND = "mock_ControllerCommand" SIGNAL_CONTROLLER_WAITING = "mock_ControllerWaiting" STATE_STOPPED = 0 STATE_FAILED = 1 STATE_RESETTED = 3 STATE_STARTED = 5 STATE_AWAKED = 7 STATE_READY = 10 def __init__(self, options=None, *args, **kwargs): """Initialize a Z-Wave mock network.""" super().__init__() self.options = options self.state = MockNetwork.STATE_STOPPED class MockNode(MagicMock): """Mock Z-Wave node.""" def __init__( self, *, node_id=567, name="Mock Node", manufacturer_id="ABCD", product_id="123", product_type="678", command_classes=None, can_wake_up_value=True, manufacturer_name="Test Manufacturer", product_name="Test Product", network=None, **kwargs, ): """Initialize a Z-Wave mock node.""" super().__init__() self.node_id = node_id self.name = name self.manufacturer_id = manufacturer_id self.product_id = product_id self.product_type = product_type self.manufacturer_name = manufacturer_name self.product_name = product_name self.can_wake_up_value = can_wake_up_value self._command_classes = command_classes or [] if network is not None: self._network = network for attr_name in kwargs: setattr(self, attr_name, kwargs[attr_name]) def has_command_class(self, command_class): """Test if mock has a command class.""" return command_class in self._command_classes def get_battery_level(self): """Return mock battery level.""" return 42 def can_wake_up(self): """Return whether the node can wake up.""" return self.can_wake_up_value def _get_child_mock(self, **kw): """Create child mocks with right MagicMock class.""" return MagicMock(**kw) class MockValue(MagicMock): """Mock Z-Wave value.""" _mock_value_id = 1234 def __init__( self, *, label="Mock Value", node=None, instance=0, index=0, value_id=None, **kwargs, ): """Initialize a Z-Wave mock value.""" super().__init__() self.label = label self.node = node self.instance = instance self.index = index if value_id is None: MockValue._mock_value_id += 1 value_id = MockValue._mock_value_id self.value_id = value_id self.object_id = value_id for attr_name in kwargs: setattr(self, attr_name, kwargs[attr_name])<|fim▁hole|> def _get_child_mock(self, **kw): """Create child mocks with right MagicMock class.""" return MagicMock(**kw) def refresh(self): """Mock refresh of node value.""" value_changed(self) class MockEntityValues: """Mock Z-Wave entity values.""" def __init__(self, **kwargs): """Initialize the mock zwave values.""" self.primary = None self.wakeup = None self.battery = None self.power = None for name in kwargs: setattr(self, name, kwargs[name]) def __iter__(self): """Allow iteration over all values.""" return iter(self.__dict__.values())<|fim▁end|>
<|file_name|>loadbalancers.go<|end_file_name|><|fim▁begin|>package network // Copyright (c) Microsoft and contributors. 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "net/http" ) // LoadBalancersClient is the network Client type LoadBalancersClient struct { BaseClient } // NewLoadBalancersClient creates an instance of the LoadBalancersClient client. func NewLoadBalancersClient(subscriptionID string) LoadBalancersClient { return NewLoadBalancersClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewLoadBalancersClientWithBaseURI creates an instance of the LoadBalancersClient client. func NewLoadBalancersClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancersClient { return LoadBalancersClient{NewWithBaseURI(baseURI, subscriptionID)} } // CreateOrUpdate creates or updates a load balancer. // // resourceGroupName is the name of the resource group. loadBalancerName is the name of the load balancer. // parameters is parameters supplied to the create or update load balancer operation. func (client LoadBalancersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters LoadBalancer) (result LoadBalancersCreateOrUpdateFuture, err error) { req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, loadBalancerName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", nil, "Failure preparing request") return } result, err = client.CreateOrUpdateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", result.Response(), "Failure sending request") return } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client LoadBalancersClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters LoadBalancer) (*http.Request, error) { pathParameters := map[string]interface{}{ "loadBalancerName": autorest.Encode("path", loadBalancerName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-09-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client LoadBalancersClient) CreateOrUpdateSender(req *http.Request) (future LoadBalancersCreateOrUpdateFuture, err error) { sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client)) future.Future = azure.NewFuture(req) future.req = req _, err = future.Done(sender) if err != nil { return } err = autorest.Respond(future.Response(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated)) return } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client LoadBalancersClient) CreateOrUpdateResponder(resp *http.Response) (result LoadBalancer, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Delete deletes the specified load balancer. // // resourceGroupName is the name of the resource group. loadBalancerName is the name of the load balancer. func (client LoadBalancersClient) Delete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancersDeleteFuture, err error) { req, err := client.DeletePreparer(ctx, resourceGroupName, loadBalancerName) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", nil, "Failure preparing request") return } result, err = client.DeleteSender(req) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", result.Response(), "Failure sending request") return } return } // DeletePreparer prepares the Delete request. func (client LoadBalancersClient) DeletePreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "loadBalancerName": autorest.Encode("path", loadBalancerName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-09-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client LoadBalancersClient) DeleteSender(req *http.Request) (future LoadBalancersDeleteFuture, err error) { sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client)) future.Future = azure.NewFuture(req) future.req = req _, err = future.Done(sender) if err != nil { return } err = autorest.Respond(future.Response(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent)) return } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client LoadBalancersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } // Get gets the specified load balancer. // // resourceGroupName is the name of the resource group. loadBalancerName is the name of the load balancer. expand // is expands referenced resources. func (client LoadBalancersClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, expand string) (result LoadBalancer, err error) { req, err := client.GetPreparer(ctx, resourceGroupName, loadBalancerName, expand) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", resp, "Failure responding to request") } return } // GetPreparer prepares the Get request. func (client LoadBalancersClient) GetPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, expand string) (*http.Request, error) { pathParameters := map[string]interface{}{ "loadBalancerName": autorest.Encode("path", loadBalancerName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID),<|fim▁hole|> queryParameters := map[string]interface{}{ "api-version": APIVersion, } if len(expand) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client LoadBalancersClient) GetSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client LoadBalancersClient) GetResponder(resp *http.Response) (result LoadBalancer, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List gets all the load balancers in a resource group. // // resourceGroupName is the name of the resource group. func (client LoadBalancersClient) List(ctx context.Context, resourceGroupName string) (result LoadBalancerListResultPage, err error) { result.fn = client.listNextResults req, err := client.ListPreparer(ctx, resourceGroupName) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.lblr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure sending request") return } result.lblr, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. func (client LoadBalancersClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-09-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client LoadBalancersClient) ListSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client LoadBalancersClient) ListResponder(resp *http.Response) (result LoadBalancerListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listNextResults retrieves the next set of results, if any. func (client LoadBalancersClient) listNextResults(lastResults LoadBalancerListResult) (result LoadBalancerListResult, err error) { req, err := lastResults.loadBalancerListResultPreparer() if err != nil { return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "listNextResults", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "listNextResults", resp, "Failure responding to next results request") } return } // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client LoadBalancersClient) ListComplete(ctx context.Context, resourceGroupName string) (result LoadBalancerListResultIterator, err error) { result.page, err = client.List(ctx, resourceGroupName) return } // ListAll gets all the load balancers in a subscription. func (client LoadBalancersClient) ListAll(ctx context.Context) (result LoadBalancerListResultPage, err error) { result.fn = client.listAllNextResults req, err := client.ListAllPreparer(ctx) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", nil, "Failure preparing request") return } resp, err := client.ListAllSender(req) if err != nil { result.lblr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure sending request") return } result.lblr, err = client.ListAllResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure responding to request") } return } // ListAllPreparer prepares the ListAll request. func (client LoadBalancersClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { pathParameters := map[string]interface{}{ "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-09-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/loadBalancers", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListAllSender sends the ListAll request. The method will close the // http.Response Body if it receives an error. func (client LoadBalancersClient) ListAllSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // ListAllResponder handles the response to the ListAll request. The method always // closes the http.Response Body. func (client LoadBalancersClient) ListAllResponder(resp *http.Response) (result LoadBalancerListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listAllNextResults retrieves the next set of results, if any. func (client LoadBalancersClient) listAllNextResults(lastResults LoadBalancerListResult) (result LoadBalancerListResult, err error) { req, err := lastResults.loadBalancerListResultPreparer() if err != nil { return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "listAllNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "listAllNextResults", resp, "Failure sending next results request") } result, err = client.ListAllResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "listAllNextResults", resp, "Failure responding to next results request") } return } // ListAllComplete enumerates all values, automatically crossing page boundaries as required. func (client LoadBalancersClient) ListAllComplete(ctx context.Context) (result LoadBalancerListResultIterator, err error) { result.page, err = client.ListAll(ctx) return } // UpdateTags updates a load balancer tags. // // resourceGroupName is the name of the resource group. loadBalancerName is the name of the load balancer. // parameters is parameters supplied to update load balancer tags. func (client LoadBalancersClient) UpdateTags(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters TagsObject) (result LoadBalancersUpdateTagsFuture, err error) { req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, loadBalancerName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "UpdateTags", nil, "Failure preparing request") return } result, err = client.UpdateTagsSender(req) if err != nil { err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "UpdateTags", result.Response(), "Failure sending request") return } return } // UpdateTagsPreparer prepares the UpdateTags request. func (client LoadBalancersClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters TagsObject) (*http.Request, error) { pathParameters := map[string]interface{}{ "loadBalancerName": autorest.Encode("path", loadBalancerName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-09-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPatch(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // UpdateTagsSender sends the UpdateTags request. The method will close the // http.Response Body if it receives an error. func (client LoadBalancersClient) UpdateTagsSender(req *http.Request) (future LoadBalancersUpdateTagsFuture, err error) { sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client)) future.Future = azure.NewFuture(req) future.req = req _, err = future.Done(sender) if err != nil { return } err = autorest.Respond(future.Response(), azure.WithErrorUnlessStatusCode(http.StatusOK)) return } // UpdateTagsResponder handles the response to the UpdateTags request. The method always // closes the http.Response Body. func (client LoadBalancersClient) UpdateTagsResponder(resp *http.Response) (result LoadBalancer, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }<|fim▁end|>
} const APIVersion = "2017-09-01"
<|file_name|>length.js<|end_file_name|><|fim▁begin|>// Copyright (C) 2015 André Bargull. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-string.prototype.valueof description: > String.prototype.valueOf.length is 0. info: | String.prototype.valueOf ( ) 17 ECMAScript Standard Built-in Objects: Every built-in Function object, including constructors, has a length property whose value is an integer. Unless otherwise specified, this value is equal to the largest number of named arguments shown in the subclause headings for the function description, including optional parameters. However, rest parameters shown using the form “...name” are not included in the default argument count. Unless otherwise specified, the length property of a built-in Function<|fim▁hole|> [[Configurable]]: true }. includes: [propertyHelper.js] ---*/ verifyProperty(String.prototype.valueOf, 'length', { value: 0, writable: false, enumerable: false, configurable: true, });<|fim▁end|>
object has the attributes { [[Writable]]: false, [[Enumerable]]: false,
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible <|fim▁hole|> name = models.CharField(max_length=255, unique=True) def __str__(self): return "%s" % self.name class KeeJobsCategory(models.Model): name = models.CharField(max_length=255, unique=True) def __str__(self): return "%s" % self.name<|fim▁end|>
@python_2_unicode_compatible class TanitJobsCategory(models.Model):
<|file_name|>ABigSum.py<|end_file_name|><|fim▁begin|>#!/bin/python3 def aVeryBigSum(n, ar):<|fim▁hole|> n = int(input().strip()) ar = list(map(int, input().strip().split(' '))) result = aVeryBigSum(n, ar) print(result)<|fim▁end|>
return sum(ar)
<|file_name|>catalogExample.py<|end_file_name|><|fim▁begin|>from yos.rt import BaseTasklet from yos.ipc import Catalog class CatalogExample(BaseTasklet): def on_startup(self):<|fim▁hole|> if val == 'test2': print("Test passed") else: print("Test failed")<|fim▁end|>
Catalog.store('test1', 'test2', catname='test3') Catalog.get('test1', self.on_read, catname='test3') def on_read(self, val):
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf8 -*- from .player import PlayerEntity from .base import MobEntity from .item import ItemEntity __all__ = [ 'PlayerEntity',<|fim▁hole|> 'MobEntity', 'ItemEntity', ]<|fim▁end|>
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from glob import glob from io import open import os import re import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') os.system('python setup.py bdist_wheel upload') sys.exit() options = { 'build_exe': { 'packages': ['lxml', 'bs4', 'requests', 'html5lib', 'argparse', 'shanbay'], 'icon': 'shanbay.ico', 'include_files': [ 'README.md', 'LICENSE', 'CHANGELOG.md', 'settings.ini.example', ] + glob('templates/*.example') + glob('templates/*/*.example'), 'include_msvcr': True, } } try: from cx_Freeze import setup, Executable kwargs = dict( options=options, executables=[Executable('assistant.py')], ) except ImportError: kwargs = {} current_dir = os.path.dirname(os.path.realpath(__file__)) requirements = [ 'argparse', 'shanbay==0.3.6', ] packages = [ 'shanbay_assistant', ] def read_f(name): with open(os.path.join(current_dir, name), encoding='utf8') as f: return f.read() def long_description(): return read_f('README.md') + '\n\n' + read_f('CHANGELOG.md') def meta_info(meta, filename='shanbay_assistant/__init__.py', default=''): meta = re.escape(meta) m = re.search(r"""%s\s+=\s+(?P<quote>['"])(?P<meta>.+?)(?P=quote)""" % meta, read_f(filename)) return m.group('meta') if m else default setup( name=meta_info('__title__'), version=meta_info('__version__'), description='shanbay.com team assistant', long_description=long_description(), url='https://github.com/mozillazg/python-shanbay-team-assistant', download_url='', author=meta_info('__author__'), author_email=meta_info('__email__'), license=meta_info('__license__'), packages=packages, package_data={'': ['LICENSE', 'settings.ini.example', 'templates/*.example', 'templates/*/*.example', ] }, package_dir={'shanbay_assistant': 'shanbay_assistant'}, include_package_data=True, install_requires=requirements, zip_safe=False, entry_points={ 'console_scripts': [ 'shanbay_assistant = shanbay_assistant.assistant:main', ], }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', # 'Programming Language :: Python :: 3', # 'Programming Language :: Python :: 3.3', # 'Programming Language :: Python :: 3.4', 'Environment :: Console',<|fim▁hole|> **kwargs )<|fim▁end|>
'Topic :: Utilities', 'Topic :: Terminals', ], keywords='shanbay, 扇贝网',
<|file_name|>replicator.py<|end_file_name|><|fim▁begin|># Copyright (c) 2010-2012 OpenStack Foundation # # 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 os import itertools import json import time from collections import defaultdict from eventlet import Timeout from swift.container.sync_store import ContainerSyncStore from swift.container.backend import ContainerBroker, DATADIR from swift.container.reconciler import ( MISPLACED_OBJECTS_ACCOUNT, incorrect_policy_index, get_reconciler_container_name, get_row_to_q_entry_translator) from swift.common import db_replicator from swift.common.storage_policy import POLICIES from swift.common.exceptions import DeviceUnavailable from swift.common.http import is_success from swift.common.db import DatabaseAlreadyExists from swift.common.utils import (Timestamp, hash_path, storage_directory, majority_size) class ContainerReplicator(db_replicator.Replicator): server_type = 'container' brokerclass = ContainerBroker datadir = DATADIR default_port = 6201 def report_up_to_date(self, full_info): reported_key_map = { 'reported_put_timestamp': 'put_timestamp', 'reported_delete_timestamp': 'delete_timestamp', 'reported_bytes_used': 'bytes_used', 'reported_object_count': 'count', } for reported, value_key in reported_key_map.items(): if full_info[reported] != full_info[value_key]: return False return True def _gather_sync_args(self, replication_info): parent = super(ContainerReplicator, self) sync_args = parent._gather_sync_args(replication_info) if len(POLICIES) > 1: sync_args += tuple(replication_info[k] for k in ('status_changed_at', 'count', 'storage_policy_index')) return sync_args def _handle_sync_response(self, node, response, info, broker, http, different_region): parent = super(ContainerReplicator, self) if is_success(response.status): remote_info = json.loads(response.data) if incorrect_policy_index(info, remote_info): status_changed_at = Timestamp(time.time()) broker.set_storage_policy_index( remote_info['storage_policy_index'], timestamp=status_changed_at.internal) sync_timestamps = ('created_at', 'put_timestamp', 'delete_timestamp') if any(info[key] != remote_info[key] for key in sync_timestamps): broker.merge_timestamps(*(remote_info[key] for key in sync_timestamps)) rv = parent._handle_sync_response( node, response, info, broker, http, different_region) return rv def find_local_handoff_for_part(self, part): """ Look through devices in the ring for the first handoff device that was identified during job creation as available on this node. :returns: a node entry from the ring """ nodes = self.ring.get_part_nodes(part) more_nodes = self.ring.get_more_nodes(part) for node in itertools.chain(nodes, more_nodes): if node['id'] in self._local_device_ids: return node return None def get_reconciler_broker(self, timestamp): """ Get a local instance of the reconciler container broker that is appropriate to enqueue the given timestamp. :param timestamp: the timestamp of the row to be enqueued :returns: a local reconciler broker """ container = get_reconciler_container_name(timestamp) if self.reconciler_containers and \ container in self.reconciler_containers: return self.reconciler_containers[container][1] account = MISPLACED_OBJECTS_ACCOUNT part = self.ring.get_part(account, container) node = self.find_local_handoff_for_part(part) if not node: raise DeviceUnavailable( 'No mounted devices found suitable to Handoff reconciler ' 'container %s in partition %s' % (container, part)) hsh = hash_path(account, container) db_dir = storage_directory(DATADIR, part, hsh) db_path = os.path.join(self.root, node['device'], db_dir, hsh + '.db') broker = ContainerBroker(db_path, account=account, container=container) if not os.path.exists(broker.db_file): try: broker.initialize(timestamp, 0) except DatabaseAlreadyExists: pass if self.reconciler_containers is not None: self.reconciler_containers[container] = part, broker, node['id'] return broker def feed_reconciler(self, container, item_list): """ Add queue entries for rows in item_list to the local reconciler container database. :param container: the name of the reconciler container :param item_list: the list of rows to enqueue :returns: True if successfully enqueued """ try: reconciler = self.get_reconciler_broker(container) except DeviceUnavailable as e: self.logger.warning('DeviceUnavailable: %s', e) return False self.logger.debug('Adding %d objects to the reconciler at %s', len(item_list), reconciler.db_file) try: reconciler.merge_items(item_list) except (Exception, Timeout): self.logger.exception('UNHANDLED EXCEPTION: trying to merge ' '%d items to reconciler container %s', len(item_list), reconciler.db_file) return False return True def dump_to_reconciler(self, broker, point): """ Look for object rows for objects updates in the wrong storage policy in broker with a ``ROWID`` greater than the rowid given as point. :param broker: the container broker with misplaced objects :param point: the last verified ``reconciler_sync_point`` :returns: the last successful enqueued rowid """ max_sync = broker.get_max_row() misplaced = broker.get_misplaced_since(point, self.per_diff) if not misplaced: return max_sync translator = get_row_to_q_entry_translator(broker) errors = False low_sync = point while misplaced: batches = defaultdict(list) for item in misplaced: container = get_reconciler_container_name(item['created_at']) batches[container].append(translator(item)) for container, item_list in batches.items(): success = self.feed_reconciler(container, item_list) if not success: errors = True point = misplaced[-1]['ROWID'] if not errors: low_sync = point misplaced = broker.get_misplaced_since(point, self.per_diff) return low_sync def _post_replicate_hook(self, broker, info, responses): if info['account'] == MISPLACED_OBJECTS_ACCOUNT: return try: self.sync_store.update_sync_store(broker) except Exception: self.logger.exception('Failed to update sync_store %s' % broker.db_file) point = broker.get_reconciler_sync() if not broker.has_multiple_policies() and info['max_row'] != point: broker.update_reconciler_sync(info['max_row']) return max_sync = self.dump_to_reconciler(broker, point) success = responses.count(True) >= majority_size(len(responses)) if max_sync > point and success: # to be safe, only slide up the sync point with a majority on # replication broker.update_reconciler_sync(max_sync) def delete_db(self, broker): """ Ensure that reconciler databases are only cleaned up at the end of the replication run. """ if (self.reconciler_cleanups is not None and broker.account == MISPLACED_OBJECTS_ACCOUNT): # this container shouldn't be here, make sure it's cleaned up self.reconciler_cleanups[broker.container] = broker return try: # DB is going to get deleted. Be preemptive about it self.sync_store.remove_synced_container(broker) except Exception: self.logger.exception('Failed to remove sync_store entry %s' % broker.db_file) return super(ContainerReplicator, self).delete_db(broker) def replicate_reconcilers(self): """ Ensure any items merged to reconciler containers during replication are pushed out to correct nodes and any reconciler containers that do not belong on this node are removed. """ self.logger.info('Replicating %d reconciler containers', len(self.reconciler_containers)) for part, reconciler, node_id in self.reconciler_containers.values(): self.cpool.spawn_n( self._replicate_object, part, reconciler.db_file, node_id)<|fim▁hole|> self.logger.info('Cleaning up %d reconciler containers', len(cleanups)) for reconciler in cleanups.values(): self.cpool.spawn_n(self.delete_db, reconciler) self.cpool.waitall() self.logger.info('Finished reconciler replication') def run_once(self, *args, **kwargs): self.reconciler_containers = {} self.reconciler_cleanups = {} self.sync_store = ContainerSyncStore(self.root, self.logger, self.mount_check) rv = super(ContainerReplicator, self).run_once(*args, **kwargs) if any([self.reconciler_containers, self.reconciler_cleanups]): self.replicate_reconcilers() return rv class ContainerReplicatorRpc(db_replicator.ReplicatorRpc): def _parse_sync_args(self, args): parent = super(ContainerReplicatorRpc, self) remote_info = parent._parse_sync_args(args) if len(args) > 9: remote_info['status_changed_at'] = args[7] remote_info['count'] = args[8] remote_info['storage_policy_index'] = args[9] return remote_info def _get_synced_replication_info(self, broker, remote_info): """ Sync the remote_info storage_policy_index if needed and return the newly synced replication info. :param broker: the database broker :param remote_info: the remote replication info :returns: local broker replication info """ info = broker.get_replication_info() if incorrect_policy_index(info, remote_info): status_changed_at = Timestamp(time.time()).internal broker.set_storage_policy_index( remote_info['storage_policy_index'], timestamp=status_changed_at) info = broker.get_replication_info() return info<|fim▁end|>
self.cpool.waitall() # wipe out the cache do disable bypass in delete_db cleanups = self.reconciler_cleanups self.reconciler_cleanups = self.reconciler_containers = None
<|file_name|>views.py<|end_file_name|><|fim▁begin|># Eve W-Space # Copyright (C) 2013 Andrew Austin and other contributors # # 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. An additional term under section # 7 of the GPL is included in the LICENSE file. # # 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/>. from datetime import datetime, timedelta import json import csv import pytz from django.core.exceptions import PermissionDenied, ObjectDoesNotExist from django.http import Http404, HttpResponseRedirect, HttpResponse from django.template.response import TemplateResponse from django.core.urlresolvers import reverse from django.template import RequestContext from django.template.loader import render_to_string from django.contrib.auth.decorators import login_required, permission_required from django.contrib.auth.models import Group, Permission from django.shortcuts import render, get_object_or_404 from django.db.models import Q from django.views.decorators.cache import cache_page from Map.models import * from Map import utils, signals from core.utils import get_config from POS.models import POS # Decorator to check map permissions. Takes request and map_id # Permissions are 0 = None, 1 = View, 2 = Change # When used without a permission=x specification, requires Change access def require_map_permission(permission=2): def _dec(view_func): def _view(request, map_id, *args, **kwargs): current_map = get_object_or_404(Map, pk=map_id) if current_map.get_permission(request.user) < permission: raise PermissionDenied else: return view_func(request, map_id, *args, **kwargs) _view.__name__ = view_func.__name__ _view.__doc__ = view_func.__doc__ _view.__dict__ = view_func.__dict__ return _view return _dec @login_required @require_map_permission(permission=1) def get_map(request, map_id): """Get the map and determine if we have permissions to see it. If we do, then return a TemplateResponse for the map. If map does not exist, return 404. If we don't have permission, return PermissionDenied. """ current_map = get_object_or_404(Map, pk=map_id) context = { 'map': current_map, 'access': current_map.get_permission(request.user), } return TemplateResponse(request, 'map.html', context) @login_required @require_map_permission(permission=1) def map_checkin(request, map_id): # Initialize json return dict json_values = {} current_map = get_object_or_404(Map, pk=map_id) # AJAX requests should post a JSON datetime called loadtime # back that we use to get recent logs. if 'loadtime' not in request.POST: return HttpResponse(json.dumps({'error': "No loadtime"}), mimetype="application/json") time_string = request.POST['loadtime'] if time_string == 'null': return HttpResponse(json.dumps({'error': "No loadtime"}), mimetype="application/json") load_time = datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S.%f") load_time = load_time.replace(tzinfo=pytz.utc) if request.is_igb_trusted: dialog_html = _checkin_igb_trusted(request, current_map) if dialog_html is not None: json_values.update({'dialogHTML': dialog_html}) log_list = MapLog.objects.filter(timestamp__gt=load_time, visible=True, map=current_map) log_string = render_to_string('log_div.html', {'logs': log_list}) json_values.update({'logs': log_string}) return HttpResponse(json.dumps(json_values), mimetype="application/json") @login_required @require_map_permission(permission=1) def map_refresh(request, map_id): """ Returns an HttpResponse with the updated systemJSON for an asynchronous map refresh. """ if not request.is_ajax(): raise PermissionDenied current_map = get_object_or_404(Map, pk=map_id) if request.is_igb: char_cache_key = 'char_%s_location' % request.eve_charid old_location = cache.get(char_cache_key) if old_location: my_sys = get_object_or_404(System, pk=old_location[0]) my_sys.remove_active_pilot(request.eve_charid) my_sys.add_active_pilot(request.user.username, request.eve_charid, request.eve_charname, request.eve_shipname, request.eve_shiptypename) result = None result = [ datetime.strftime(datetime.now(pytz.utc), "%Y-%m-%d %H:%M:%S.%f"), utils.MapJSONGenerator(current_map, request.user).get_systems_json() ] # TODO update active pilots # get users current system #map_sys = get_object_or_404(MapSystem, pk=ms_id) # if this system is on the map, update. Otherwise, don't.. #remove_active_pilot(request.eve_charid) #map_sys.remove_active_pilot(request.eve_charid) #map_sys.add_active_pilot(request.user.username, request.eve_charid, # request.eve_charname, request.eve_shipname, # request.eve_shiptypename) return HttpResponse(json.dumps(result)) def log_movement(oldSys, newSys, charName, shipType, current_map, user): # get msid for oldsys # print oldSys # print newSys try: oldSysMapId = current_map.systems.filter(system=oldSys).all()[0] newSysMapId = current_map.systems.filter(system=newSys).all()[0] # BUG wh = Wormhole.objects.filter(top__in=[oldSysMapId,newSysMapId],bottom__in=[oldSysMapId,newSysMapId]).all()[0] # get current ship size #print shipType shipSize = Ship.objects.get(shipname=shipType).shipmass # get old mass if wh.mass_amount != None: wh.mass_amount = (wh.mass_amount + shipSize) else: wh.mass_amount = shipSize wh.save() except: print "Hole didn't exist yet" # jumplog jl = JumpLog.objects.create(user_id=user.id, char_name=charName, src=oldSys, dest=newSys) jl.save() def _checkin_igb_trusted(request, current_map): """ Runs the specific code for the case that the request came from an igb that trusts us, returns None if no further action is required, returns a string containing the html for a system add dialog if we detect that a new system needs to be added """ # XXX possibly where the logging needs to happen can_edit = current_map.get_permission(request.user) == 2 current_location = (request.eve_systemid, request.eve_charname, request.eve_shipname, request.eve_shiptypename) char_cache_key = 'char_%s_location' % request.eve_charid old_location = cache.get(char_cache_key) result = None #print old_location if old_location != current_location: current_system = get_object_or_404(System, pk=current_location[0]) if old_location: old_system = get_object_or_404(System, pk=old_location[0]) old_system.remove_active_pilot(request.eve_charid) log_movement(old_system, current_system, request.eve_charname, request.eve_shiptypename, current_map, request.user) #XXX vtadd current_system.add_active_pilot(request.user.username, request.eve_charid, request.eve_charname, request.eve_shipname, request.eve_shiptypename) request.user.get_profile().update_location(current_system.pk, request.eve_charid, request.eve_charname, request.eve_shipname, request.eve_shiptypename) cache.set(char_cache_key, current_location, 60 * 5) #Conditions for the system to be automagically added to the map. if (can_edit and old_location and old_system in current_map and current_system not in current_map and not _is_moving_from_kspace_to_kspace(old_system, current_system) ): context = { 'oldsystem': current_map.systems.filter( system=old_system).all()[0], 'newsystem': current_system, 'wormholes': utils.get_possible_wh_types(old_system, current_system), } if request.POST.get('silent', 'false') != 'true': result = render_to_string('igb_system_add_dialog.html', context, context_instance=RequestContext(request)) else: new_ms = current_map.add_system(request.user, current_system, '', context['oldsystem']) k162_type = WormholeType.objects.get(name="K162") new_ms.connect_to(context['oldsystem'], k162_type, k162_type) result = 'silent' # maybe fixes else: cache.set(char_cache_key, current_location, 60 * 5) return result def _is_moving_from_kspace_to_kspace(old_system, current_system): """ returns whether we are moving through kspace :param old_system: :param current_system: :return: """ return old_system.is_kspace() and current_system.is_kspace() def get_system_context(ms_id, user): map_system = get_object_or_404(MapSystem, pk=ms_id) if map_system.map.get_permission(user) == 2: can_edit = True else: can_edit = False #If map_system represents a k-space system get the relevant KSystem object if map_system.system.is_kspace(): system = map_system.system.ksystem else: system = map_system.system.wsystem scan_threshold = datetime.now(pytz.utc) - timedelta( hours=int(get_config("MAP_SCAN_WARNING", None).value) ) interest_offset = int(get_config("MAP_INTEREST_TIME", None).value) interest_threshold = (datetime.now(pytz.utc) - timedelta(minutes=interest_offset)) scan_warning = system.lastscanned < scan_threshold if interest_offset > 0: interest = (map_system.interesttime and map_system.interesttime > interest_threshold) else: interest = map_system.interesttime # Include any SiteTracker fleets that are active st_fleets = map_system.system.stfleets.filter(ended=None).all() locations = cache.get('sys_%s_locations' % map_system.system.pk) if not locations: locations = {} return {'system': system, 'mapsys': map_system, 'scanwarning': scan_warning, 'isinterest': interest, 'stfleets': st_fleets, 'locations': locations, 'can_edit': can_edit} @login_required @require_map_permission(permission=2) def add_system(request, map_id): """ AJAX view to add a system to a current_map. Requires POST containing: topMsID: map_system ID of the parent map_system bottomSystem: Name of the new system topType: WormholeType name of the parent side bottomType: WormholeType name of the new side timeStatus: Wormhole time status integer value massStatus: Wormhole mass status integer value topBubbled: 1 if Parent side bubbled bottomBubbled: 1 if new side bubbled friendlyName: Friendly name for the new map_system """ if not request.is_ajax(): raise PermissionDenied try: # Prepare data current_map = Map.objects.get(pk=map_id) top_ms = MapSystem.objects.get(pk=request.POST.get('topMsID')) bottom_sys = System.objects.get( name=request.POST.get('bottomSystem') ) top_type = WormholeType.objects.get( name=request.POST.get('topType') ) bottom_type = WormholeType.objects.get( name=request.POST.get('bottomType') ) time_status = int(request.POST.get('timeStatus')) mass_status = int(request.POST.get('massStatus')) if request.POST.get('topBubbled', '0') != "0": top_bubbled = True else: top_bubbled = False if request.POST.get('bottomBubbled', '0') != "0": bottom_bubbled = True else: bottom_bubbled = False # Add System bottom_ms = current_map.add_system( request.user, bottom_sys, request.POST.get('friendlyName'), top_ms ) # Add Wormhole bottom_ms.connect_to(top_ms, top_type, bottom_type, top_bubbled, bottom_bubbled, time_status, mass_status) current_map.clear_caches() return HttpResponse() except ObjectDoesNotExist: return HttpResponse(status=400) # noinspection PyUnusedLocal @login_required @require_map_permission(permission=2) def remove_system(request, map_id, ms_id): """ Removes the supplied map_system from a map. """ system = get_object_or_404(MapSystem, pk=ms_id) system.remove_system(request.user) return HttpResponse() # noinspection PyUnusedLocal @login_required @require_map_permission(permission=1) def system_details(request, map_id, ms_id): """ Returns a html div representing details of the System given by ms_id in map map_id """ if not request.is_ajax(): raise PermissionDenied return render(request, 'system_details.html', get_system_context(ms_id, request.user)) # noinspection PyUnusedLocal @login_required @require_map_permission(permission=1) def system_menu(request, map_id, ms_id): """ Returns the html for system menu """ if not request.is_ajax(): raise PermissionDenied return render(request, 'system_menu.html', get_system_context(ms_id, request.user)) # noinspection PyUnusedLocal @login_required @require_map_permission(permission=1) def system_tooltips(request, map_id): """ Returns the system tooltips for map_id """ if not request.is_ajax(): raise PermissionDenied cache_key = 'map_%s_sys_tooltip' % map_id cached_tips = cache.get(cache_key) if not cached_tips: ms_list = MapSystem.objects.filter(map_id=map_id)\ .select_related('parent_wormhole', 'system__region')\ .iterator() new_tips = render_to_string('system_tooltip.html', {'map_systems': ms_list}, RequestContext(request)) cache.set(cache_key, new_tips, 60) return HttpResponse(new_tips) else: return HttpResponse(cached_tips) # noinspection PyUnusedLocal @login_required @require_map_permission(permission=1) def wormhole_tooltips(request, map_id): """Takes a POST request from AJAX with a Wormhole ID and renders the wormhole tooltip for that ID to response. """ if not request.is_ajax(): raise PermissionDenied cache_key = 'map_%s_wh_tooltip' % map_id cached_tips = cache.get(cache_key) if not cached_tips: cur_map = get_object_or_404(Map, pk=map_id) ms_list = MapSystem.objects.filter(map=cur_map).all() whs = Wormhole.objects.filter(top__in=ms_list).all() new_tips = render_to_string('wormhole_tooltip.html', {'wormholes': whs}, RequestContext(request)) cache.set(cache_key, new_tips, 60) return HttpResponse(new_tips) else: return HttpResponse(cached_tips) # noinspection PyUnusedLocal @login_required() @require_map_permission(permission=2) def collapse_system(request, map_id, ms_id): """ Mark the system as collapsed. """ if not request.is_ajax(): raise PermissionDenied map_sys = get_object_or_404(MapSystem, pk=ms_id) parent_wh = map_sys.parent_wormhole parent_wh.collapsed = True parent_wh.save() return HttpResponse() # noinspection PyUnusedLocal @login_required() @require_map_permission(permission=2) def resurrect_system(request, map_id, ms_id): """ Unmark the system as collapsed. """ if not request.is_ajax(): raise PermissionDenied map_sys = get_object_or_404(MapSystem, pk=ms_id) parent_wh = map_sys.parent_wormhole parent_wh.collapsed = False parent_wh.save() return HttpResponse() # noinspection PyUnusedLocal @login_required() @require_map_permission(permission=2) def mark_scanned(request, map_id, ms_id): """Takes a POST request from AJAX with a system ID and marks that system as scanned. """ if request.is_ajax(): map_system = get_object_or_404(MapSystem, pk=ms_id) map_system.system.lastscanned = datetime.now(pytz.utc) map_system.system.save() return HttpResponse() else: raise PermissionDenied # noinspection PyUnusedLocal @login_required() def manual_location(request, map_id, ms_id): """Takes a POST request form AJAX with a System ID and marks the user as being active in that system. """ if not request.is_ajax(): raise PermissionDenied user_locations = cache.get('user_%s_locations' % request.user.pk) if user_locations: old_location = user_locations.pop(request.user.pk, None) if old_location: old_sys = get_object_or_404(System, pk=old_location[0]) old_sys.remove_active_pilot(request.user.pk) map_sys = get_object_or_404(MapSystem, pk=ms_id) map_sys.system.add_active_pilot(request.user.username, request.user.pk, 'OOG Browser', 'Unknown', 'Unknown') request.user.get_profile().update_location(map_sys.system.pk, request.user.pk, 'OOG Browser', 'Unknown', 'Unknown') map_sys.map.clear_caches() return HttpResponse() # noinspection PyUnusedLocal @login_required() @require_map_permission(permission=2) def set_interest(request, map_id, ms_id): """Takes a POST request from AJAX with an action and marks that system as having either utcnow or None as interesttime. The action can be either "set" or "remove". """ if request.is_ajax(): action = request.POST.get("action", "none") if action == "none": raise Http404 system = get_object_or_404(MapSystem, pk=ms_id) if action == "set": system.interesttime = datetime.now(pytz.utc) system.save() return HttpResponse() if action == "remove": system.interesttime = None system.save() return HttpResponse() system.map.clear_caches() return HttpResponse(status=418) else: raise PermissionDenied def _update_sig_from_tsv(signature, row): COL_SIG = 0 COL_SIG_TYPE = 3 COL_SIG_GROUP = 2 COL_SIG_SCAN_GROUP = 1 COL_SIG_STRENGTH = 4 COL_DISTANCE = 5 info = row[COL_SIG_TYPE] updated = False sig_type = None if (row[COL_SIG_SCAN_GROUP] == "Cosmic Signature" or row[COL_SIG_SCAN_GROUP] == "Cosmic Anomaly" ): try: sig_type = SignatureType.objects.get( longname=row[COL_SIG_GROUP]) except: sig_type = None else: sig_type = None if sig_type: updated = True if sig_type: signature.sigtype = sig_type signature.updated = updated or signature.updated if info: signature.info = info if signature.info == None: signature.info = '' return signature # noinspection PyUnusedLocal @login_required @require_map_permission(permission=2) def bulk_sig_import(request, map_id, ms_id): """ GET gets a bulk signature import form. POST processes it, creating sigs with blank info and type for each sig ID detected. """ if not request.is_ajax(): raise PermissionDenied map_system = get_object_or_404(MapSystem, pk=ms_id) k = 0 if request.method == 'POST': reader = csv.reader(request.POST.get('paste', '').decode( 'utf-8').splitlines(), delimiter="\t") COL_SIG = 0 COL_STRENGTH = 4 for row in reader: # To prevent pasting of POSes into the sig importer, make sure # the strength column is present try: test_var = row[COL_STRENGTH] except IndexError: return HttpResponse('A valid signature paste was not found', status=400) if k < 75: sig_id = utils.convert_signature_id(row[COL_SIG]) sig = Signature.objects.get_or_create(sigid=sig_id, system=map_system.system)[0] sig = _update_sig_from_tsv(sig, row) sig.modified_by = request.user sig.save() signals.signature_update.send_robust(sig, user=request.user, map=map_system.map, signal_strength=row[COL_STRENGTH]) k += 1 map_system.map.add_log(request.user, "Imported %s signatures for %s(%s)." % (k, map_system.system.name, map_system.friendlyname), True) map_system.system.lastscanned = datetime.now(pytz.utc) map_system.system.save() return HttpResponse() else: return TemplateResponse(request, "bulk_sig_form.html", {'mapsys': map_system}) @login_required @require_map_permission(permission=2) def toggle_sig_owner(request, map_id, ms_id, sig_id=None): if not request.is_ajax(): raise PermissionDenied sig = get_object_or_404(Signature, pk=sig_id) sig.toggle_ownership(request.user) return HttpResponse() # noinspection PyUnusedLocal @login_required @require_map_permission(permission=1) def edit_signature(request, map_id, ms_id, sig_id=None): """ GET gets a pre-filled edit signature form. POST updates the signature with the new information and returns a blank add form. """ if not request.is_ajax(): raise PermissionDenied map_system = get_object_or_404(MapSystem, pk=ms_id) # If the user can't edit signatures, return a blank response if map_system.map.get_permission(request.user) != 2: return HttpResponse() action = None if sig_id != None: signature = get_object_or_404(Signature, pk=sig_id) created = False if not signature.owned_by: signature.toggle_ownership(request.user) if request.method == 'POST': form = SignatureForm(request.POST) if form.is_valid(): ingame_id = utils.convert_signature_id(form.cleaned_data['sigid']) if sig_id == None: signature, created = Signature.objects.get_or_create( system=map_system.system, sigid=ingame_id) signature.sigid = ingame_id signature.updated = True signature.info = form.cleaned_data['info'] if request.POST['sigtype'] != '': sigtype = form.cleaned_data['sigtype'] else: sigtype = None signature.sigtype = sigtype signature.modified_by = request.user signature.save() map_system.system.lastscanned = datetime.now(pytz.utc) map_system.system.save() if created: action = 'Created' else: action = 'Updated' if signature.owned_by: signature.toggle_ownership(request.user) map_system.map.add_log(request.user, "%s signature %s in %s (%s)" % (action, signature.sigid, map_system.system.name, map_system.friendlyname)) signals.signature_update.send_robust(signature, user=request.user, map=map_system.map) else: return TemplateResponse(request, "edit_sig_form.html", {'form': form, 'system': map_system, 'sig': signature}) form = SignatureForm() if sig_id == None or action == 'Updated': return TemplateResponse(request, "add_sig_form.html", {'form': form, 'system': map_system}) else: return TemplateResponse(request, "edit_sig_form.html", {'form': SignatureForm(instance=signature), 'system': map_system, 'sig': signature}) # noinspection PyUnusedLocal @login_required() @require_map_permission(permission=1) @cache_page(1) def get_signature_list(request, map_id, ms_id): """ Determines the proper escalationThreshold time and renders system_signatures.html """ if not request.is_ajax(): raise PermissionDenied system = get_object_or_404(MapSystem, pk=ms_id) escalation_downtimes = int(get_config("MAP_ESCALATION_BURN", request.user).value) return TemplateResponse(request, "system_signatures.html", {'system': system, 'downtimes': escalation_downtimes}) # noinspection PyUnusedLocal @login_required @require_map_permission(permission=2) def mark_signature_cleared(request, map_id, ms_id, sig_id): """ Marks a signature as having its NPCs cleared. """ if not request.is_ajax(): raise PermissionDenied sig = get_object_or_404(Signature, pk=sig_id) sig.clear_rats() return HttpResponse() # noinspection PyUnusedLocal @login_required @require_map_permission(permission=2) def escalate_site(request, map_id, ms_id, sig_id): """ Marks a site as having been escalated. """ if not request.is_ajax(): raise PermissionDenied sig = get_object_or_404(Signature, pk=sig_id) sig.escalate() return HttpResponse() # noinspection PyUnusedLocal @login_required @require_map_permission(permission=2) def activate_signature(request, map_id, ms_id, sig_id): """ Marks a site activated. """ if not request.is_ajax(): raise PermissionDenied sig = get_object_or_404(Signature, pk=sig_id) sig.activate() return HttpResponse() # noinspection PyUnusedLocal @login_required @require_map_permission(permission=2) def delete_signature(request, map_id, ms_id, sig_id): """ Deletes a signature. """ if not request.is_ajax(): raise PermissionDenied map_system = get_object_or_404(MapSystem, pk=ms_id) sig = get_object_or_404(Signature, pk=sig_id) sig.delete() map_system.map.add_log(request.user, "Deleted signature %s in %s (%s)." % (sig.sigid, map_system.system.name, map_system.friendlyname)) return HttpResponse() # noinspection PyUnusedLocal @login_required @require_map_permission(permission=2) def manual_add_system(request, map_id, ms_id): """ A GET request gets a blank add system form with the provided MapSystem as top system. The form is then POSTed to the add_system view. """ if request.is_igb_trusted: current_system = System.objects.get(name=request.eve_systemname) else: current_system = "" top_map_system = get_object_or_404(MapSystem, pk=ms_id) systems = System.objects.all() wormholes = WormholeType.objects.all() return render(request, 'add_system_box.html', {'topMs': top_map_system, 'sysList': systems, 'whList': wormholes,'newsystem': current_system}) # noinspection PyUnusedLocal @login_required @require_map_permission(permission=2) def edit_system(request, map_id, ms_id): """ A GET request gets the edit system dialog pre-filled with current information. A POST request saves the posted data as the new information. POST values are friendlyName, info, and occupied. """ if not request.is_ajax(): raise PermissionDenied map_system = get_object_or_404(MapSystem, pk=ms_id) if request.method == 'GET': occupied = map_system.system.occupied.replace("<br />", "\n") info = map_system.system.info.replace("<br />", "\n") return TemplateResponse(request, 'edit_system.html', {'mapsys': map_system, 'occupied': occupied, 'info': info} ) if request.method == 'POST': map_system.friendlyname = request.POST.get('friendlyName', '') if ( (map_system.system.info != request.POST.get('info', '')) or (map_system.system.occupied != request.POST.get('occupied', '')) ): map_system.system.info = request.POST.get('info', '') map_system.system.occupied = request.POST.get('occupied', '') map_system.system.save() map_system.save() map_system.map.add_log(request.user, "Edited System: %s (%s)" % (map_system.system.name, map_system.friendlyname)) return HttpResponse() raise PermissionDenied # noinspection PyUnusedLocal @login_required @require_map_permission(permission=2) def edit_wormhole(request, map_id, wh_id): """ A GET request gets the edit wormhole dialog pre-filled with current info. A POST request saves the posted data as the new info. POST values are topType, bottomType, massStatus, timeStatus, topBubbled, and bottomBubbled. """ if not request.is_ajax(): raise PermissionDenied wormhole = get_object_or_404(Wormhole, pk=wh_id) if request.method == 'GET': return TemplateResponse(request, 'edit_wormhole.html', {'wormhole': wormhole} ) if request.method == 'POST': manualShipMassAdd = request.POST.get('massAdd',0) if manualShipMassAdd != "": addedMass = Ship.objects.get(shipname=manualShipMassAdd).shipmass wormhole.mass_amount = (wormhole.mass_amount + addedMass) wormhole.mass_status = int(request.POST.get('massStatus', 0)) wormhole.time_status = int(request.POST.get('timeStatus', 0)) wormhole.top_type = get_object_or_404( WormholeType, name=request.POST.get('topType', 'K162') ) wormhole.bottom_type = get_object_or_404( WormholeType, name=request.POST.get('bottomType', 'K162') ) wormhole.top_bubbled = request.POST.get('topBubbled', '1') == '1' wormhole.bottom_bubbled = request.POST.get('bottomBubbled', '1') == '1' wormhole.save() wormhole.map.add_log(request.user, ("Updated the wormhole between %s(%s) and %s(%s)." % (wormhole.top.system.name, wormhole.top.friendlyname, wormhole.bottom.system.name, wormhole.bottom.friendlyname))) return HttpResponse() raise PermissiondDenied @permission_required('Map.add_map') def create_map(request): """ This function creates a map and then redirects to the new map. """ if request.method == 'POST': form = MapForm(request.POST) if form.is_valid(): new_map = form.save() new_map.add_log(request.user, "Created the %s map." % new_map.name) new_map.add_system(request.user, new_map.root, "Root", None) return HttpResponseRedirect(reverse('Map.views.get_map', kwargs={'map_id': new_map.pk})) else: return TemplateResponse(request, 'new_map.html', {'form': form}) else: form = MapForm return TemplateResponse(request, 'new_map.html', {'form': form, }) def _sort_destinations(destinations): """ Takes a list of destination tuples and returns the same list, sorted in order of the jumps. """ results = [] onVal = 0 for dest in destinations: if len(results) == 0: results.append(dest) else: while onVal <= len(results): if onVal == len(results): results.append(dest) onVal = 0 break else: if dest[1] > results[onVal][1]: onVal += 1 else: results.insert(onVal, dest) onVal = 0 break return results # noinspection PyUnusedLocal @require_map_permission(permission=1) def destination_list(request, map_id, ms_id): """ Returns the destinations of interest tuple for K-space systems and a blank response for w-space systems. """ if not request.is_ajax(): raise PermissionDenied destinations = Destination.objects.filter(Q(user=None) | Q(user=request.user)) map_system = get_object_or_404(MapSystem, pk=ms_id) try: system = KSystem.objects.get(pk=map_system.system.pk) rf = utils.RouteFinder() result = [] for destination in destinations: result.append((destination.system, rf.route_length(system, destination.system) - 1, round(rf.ly_distance(system, destination.system), 3) )) except ObjectDoesNotExist: return HttpResponse() return render(request, 'system_destinations.html', {'system': system, 'destinations': _sort_destinations(result)}) # noinspection PyUnusedLocal def site_spawns(request, map_id, ms_id, sig_id): """ Returns the spawns for a given signature and system. """ sig = get_object_or_404(Signature, pk=sig_id) spawns = SiteSpawn.objects.filter(sigtype=sig.sigtype).all() if spawns[0].sysclass != 0: spawns = SiteSpawn.objects.filter(sigtype=sig.sigtype, sysclass=sig.system.sysclass).all() return render(request, 'site_spawns.html', {'spawns': spawns}) ######################### #Settings Views # ######################### @permission_required('Map.map_admin') def general_settings(request): """ Returns and processes the general settings section. """ npc_threshold = get_config("MAP_NPC_THRESHOLD", None) pvp_threshold = get_config("MAP_PVP_THRESHOLD", None) scan_threshold = get_config("MAP_SCAN_WARNING", None) interest_time = get_config("MAP_INTEREST_TIME", None) escalation_burn = get_config("MAP_ESCALATION_BURN", None) if request.method == "POST": scan_threshold.value = int(request.POST['scanwarn']) interest_time.value = int(request.POST['interesttimeout']) pvp_threshold.value = int(request.POST['pvpthreshold']) npc_threshold.value = int(request.POST['npcthreshold']) escalation_burn.value = int(request.POST['escdowntimes']) scan_threshold.save() interest_time.save() pvp_threshold.save() npc_threshold.save() escalation_burn.save() return HttpResponse() return TemplateResponse( request, 'general_settings.html', {'npcthreshold': npc_threshold.value, 'pvpthreshold': pvp_threshold.value, 'scanwarn': scan_threshold.value, 'interesttimeout': interest_time.value, 'escdowntimes': escalation_burn.value} ) @permission_required('Map.map_admin') def sites_settings(request): """ Returns the site spawns section. """ return TemplateResponse(request, 'spawns_settings.html', {'spawns': SiteSpawn.objects.all()}) @permission_required('Map.map_admin') def add_spawns(request): """ Adds a site spawn. """ return HttpResponse() # noinspection PyUnusedLocal @permission_required('Map.map_admin') def delete_spawns(request, spawn_id): """ Deletes a site spawn. """ return HttpResponse() # noinspection PyUnusedLocal @permission_required('Map.map_admin') def edit_spawns(request, spawn_id): """ Alters a site spawn. """ return HttpResponse() def destination_settings(request, user=None): """ Returns the destinations section. """ if not user: dest_list = Destination.objects.filter(user=None) else: dest_list = Destination.objects.filter(Q(user=None) | Q(user=request.user)) return TemplateResponse(request, 'dest_settings.html', {'destinations': dest_list, 'user_context': user}) def add_destination(request, dest_user=None): """ Add a destination. """ if not dest_user and not request.user.has_perm('Map.map_admin'): raise PermissionDenied system = get_object_or_404(KSystem, name=request.POST['systemName']) Destination(system=system, user=dest_user).save() return HttpResponse() def add_personal_destination(request): """ Add a personal destination. """ return add_destination(request, dest_user=request.user) def delete_destination(request, dest_id): """ Deletes a destination. """ destination = get_object_or_404(Destination, pk=dest_id) if not request.user.has_perm('Map.map_admin') and not destination.user: raise PermissionDenied if destination.user and not request.user == destination.user: raise PermissionDenied destination.delete() return HttpResponse() @permission_required('Map.map_admin') def sigtype_settings(request): """ Returns the signature types section. """ return TemplateResponse(request, 'sigtype_settings.html', {'sigtypes': SignatureType.objects.all()}) # noinspection PyUnusedLocal @permission_required('Map.map_admin') def edit_sigtype(request, sigtype_id): """ Alters a signature type. """ return HttpResponse() @permission_required('Map.map_admin') def add_sigtype(request): """ Adds a signature type. """ return HttpResponse() # noinspection PyUnusedLocal @permission_required('Map.map_admin') def delete_sigtype(request, sigtype_id): """ Deletes a signature type. """ return HttpResponse() @permission_required('Map.map_admin') def map_settings(request, map_id): """ Returns and processes the settings section for a map. """ saved = False subject = get_object_or_404(Map, pk=map_id) if request.method == 'POST': name = request.POST.get('name', None) explicit_perms = request.POST.get('explicitperms', False) if not name: return HttpResponse('The map name cannot be blank', status=400) subject.name = name subject.explicitperms = explicit_perms for group in Group.objects.all(): MapPermission.objects.filter(group=group, map=subject).delete() setting = request.POST.get('map-%s-group-%s-permission' % ( subject.pk, group.pk), 0) if setting != 0: MapPermission(group=group, map=subject, access=setting).save() subject.save() saved = True groups = [] for group in Group.objects.all(): if MapPermission.objects.filter(map=subject, group=group).exists(): perm = MapPermission.objects.get(map=subject, group=group).access else: perm = 0 groups.append((group,perm)) return TemplateResponse(request, 'map_settings_single.html', {'map': subject, 'groups': groups, 'saved': saved}) @permission_required('Map.map_admin') def delete_map(request, map_id): """ Deletes a map. """ subject = get_object_or_404(Map, pk=map_id) subject.delete() return HttpResponse() # noinspection PyUnusedLocal @permission_required('Map.map_admin') def edit_map(request, map_id): """ Alters a map. """ return HttpResponse('[]') @permission_required('Map.map_admin') def global_permissions(request): """ Returns and processes the global permissions section. """ if not request.is_ajax(): raise PermissionDenied group_list = [] admin_perm = Permission.objects.get(codename="map_admin") unrestricted_perm = Permission.objects.get(codename="map_unrestricted")<|fim▁hole|> add_map_perm = Permission.objects.get(codename="add_map") if request.method == "POST": for group in Group.objects.all(): if request.POST.get('%s_unrestricted' % group.pk, None): if unrestricted_perm not in group.permissions.all(): group.permissions.add(unrestricted_perm) else: if unrestricted_perm in group.permissions.all(): group.permissions.remove(unrestricted_perm) if request.POST.get('%s_add' % group.pk, None): if add_map_perm not in group.permissions.all(): group.permissions.add(add_map_perm) else: if add_map_perm in group.permissions.all(): group.permissions.remove(add_map_perm) if request.POST.get('%s_admin' % group.pk, None): if admin_perm not in group.permissions.all(): group.permissions.add(admin_perm) else: if admin_perm in group.permissions.all(): group.permissions.remove(admin_perm) return HttpResponse() for group in Group.objects.all(): entry = { 'group': group, 'admin': admin_perm in group.permissions.all(), 'unrestricted': unrestricted_perm in group.permissions.all(), 'add_map': add_map_perm in group.permissions.all() } group_list.append(entry) return TemplateResponse(request, 'global_perms.html', {'groups': group_list}) @require_map_permission(permission=2) def purge_signatures(request, map_id, ms_id): if not request.is_ajax(): raise PermissionDenied mapsys = get_object_or_404(MapSystem, pk=ms_id) if request.method == "POST": mapsys.system.signatures.all().delete() return HttpResponse() else: return HttpResponse(status=400)<|fim▁end|>
<|file_name|>signals.py<|end_file_name|><|fim▁begin|>from django.dispatch import Signal pre_save = Signal(providing_args=['instance', 'action', ]) post_save = Signal(providing_args=['instance', 'action', ])<|fim▁hole|> pre_delete = Signal(providing_args=['instance', 'action', ]) post_delete = Signal(providing_args=['instance', 'action', ])<|fim▁end|>
<|file_name|>conical-dendrite-trees.js<|end_file_name|><|fim▁begin|>export default [ { radius: 6, sizeReduction: .85, branchProbability: 0.12, rotation: new THREE.Vector3(0, 1, 0), color: 'blue' },{ radius: 6, sizeReduction: .85, branchProbability: 0.21, rotation: new THREE.Vector3(0, 1, 0), color: 'blue' },{ radius: 3, sizeReduction: .87, branchProbability: 0.25, rotation: new THREE.Vector3(0, 1, 0), color: 'blue' }, { radius: 7, sizeReduction: .82, branchProbability: 0.22, rotation: new THREE.Vector3(0, 1, 0), color: 'blue' },{ radius: 7, sizeReduction: .82, branchProbability: 0.22, rotation: new THREE.Vector3(0, 1, 0), color: 'blue' },{<|fim▁hole|> color: 'blue' }, { radius: 10, sizeReduction: .9, branchProbability: 0.2, rotation: new THREE.Vector3(0, 1, 0), color: 'pink' },{ radius: 10, sizeReduction: .75, branchProbability: 0.3, rotation: new THREE.Vector3(0, 1, 0), color: 'pink' } ];<|fim▁end|>
radius: 7, sizeReduction: .82, branchProbability: 0.27, rotation: new THREE.Vector3(0, 1, 0),
<|file_name|>_match.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2013 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. use middle::pat_util::{PatIdMap, pat_id_map, pat_is_binding, pat_is_const}; use middle::ty; use middle::typeck::check::demand; use middle::typeck::check::{check_block, check_expr_has_type, FnCtxt}; use middle::typeck::check::{instantiate_path, lookup_def}; use middle::typeck::check::{structure_of, valid_range_bounds}; use middle::typeck::infer; use middle::typeck::require_same_types; use std::hashmap::{HashMap, HashSet}; use syntax::ast; use syntax::ast_util; use syntax::parse::token; use syntax::codemap::Span; use syntax::print::pprust; pub fn check_match(fcx: @mut FnCtxt, expr: @ast::Expr, discrim: @ast::Expr, arms: &[ast::Arm]) { let tcx = fcx.ccx.tcx; let discrim_ty = fcx.infcx().next_ty_var(); check_expr_has_type(fcx, discrim, discrim_ty); // Typecheck the patterns first, so that we get types for all the // bindings. for arm in arms.iter() { let mut pcx = pat_ctxt { fcx: fcx, map: pat_id_map(tcx.def_map, arm.pats[0]), }; for p in arm.pats.iter() { check_pat(&mut pcx, *p, discrim_ty);} } // The result of the match is the common supertype of all the // arms. Start out the value as bottom, since it's the, well, // bottom the type lattice, and we'll be moving up the lattice as // we process each arm. (Note that any match with 0 arms is matching // on any empty type and is therefore unreachable; should the flow // of execution reach it, we will fail, so bottom is an appropriate // type in that case) let mut result_ty = ty::mk_bot(); // Now typecheck the blocks. let mut saw_err = ty::type_is_error(discrim_ty); for arm in arms.iter() { let mut guard_err = false; let mut guard_bot = false; match arm.guard { Some(e) => { check_expr_has_type(fcx, e, ty::mk_bool()); let e_ty = fcx.expr_ty(e); if ty::type_is_error(e_ty) { guard_err = true; } else if ty::type_is_bot(e_ty) { guard_bot = true; } }, None => () } check_block(fcx, &arm.body); let bty = fcx.node_ty(arm.body.id); saw_err = saw_err || ty::type_is_error(bty); if guard_err { fcx.write_error(arm.body.id); saw_err = true; } else if guard_bot { fcx.write_bot(arm.body.id); } result_ty = infer::common_supertype( fcx.infcx(), infer::MatchExpression(expr.span), true, // result_ty is "expected" here result_ty, bty); } if saw_err { result_ty = ty::mk_err(); } else if ty::type_is_bot(discrim_ty) { result_ty = ty::mk_bot(); } fcx.write_ty(expr.id, result_ty); } pub struct pat_ctxt { fcx: @mut FnCtxt, map: PatIdMap, } pub fn check_pat_variant(pcx: &pat_ctxt, pat: @ast::Pat, path: &ast::Path, subpats: &Option<~[@ast::Pat]>, expected: ty::t) { // Typecheck the path. let fcx = pcx.fcx; let tcx = pcx.fcx.ccx.tcx; let arg_types; let kind_name; // structure_of requires type variables to be resolved. // So when we pass in <expected>, it's an error if it // contains type variables. // Check to see whether this is an enum or a struct. match *structure_of(pcx.fcx, pat.span, expected) { ty::ty_enum(_, ref expected_substs) => { // Lookup the enum and variant def ids: let v_def = lookup_def(pcx.fcx, pat.span, pat.id); match ast_util::variant_def_ids(v_def) { Some((enm, var)) => { // Assign the pattern the type of the *enum*, not the variant. let enum_tpt = ty::lookup_item_type(tcx, enm); instantiate_path(pcx.fcx, path, enum_tpt, v_def, pat.span, pat.id); // check that the type of the value being matched is a subtype // of the type of the pattern: let pat_ty = fcx.node_ty(pat.id); demand::subtype(fcx, pat.span, expected, pat_ty); // Get the expected types of the arguments. arg_types = { let vinfo = ty::enum_variant_with_id(tcx, enm, var); let var_tpt = ty::lookup_item_type(tcx, var); vinfo.args.map(|t| { if var_tpt.generics.type_param_defs.len() == expected_substs.tps.len() { ty::subst(tcx, expected_substs, *t) } else { *t // In this case, an error was already signaled // anyway } }) }; kind_name = "variant"; } None => { // See [Note-Type-error-reporting] in middle/typeck/infer/mod.rs fcx.infcx().type_error_message_str_with_expected(pat.span, |expected, actual| { expected.map_default(~"", |e| { format!("mismatched types: expected `{}` but found {}", e, actual)})}, Some(expected), ~"a structure pattern", None); fcx.write_error(pat.id); kind_name = "[error]"; arg_types = (*subpats).clone() .unwrap_or_default() .map(|_| ty::mk_err()); } } } ty::ty_struct(struct_def_id, ref expected_substs) => { // Lookup the struct ctor def id let s_def = lookup_def(pcx.fcx, pat.span, pat.id); let s_def_id = ast_util::def_id_of_def(s_def); // Assign the pattern the type of the struct. let ctor_tpt = ty::lookup_item_type(tcx, s_def_id); let struct_tpt = if ty::is_fn_ty(ctor_tpt.ty) { ty::ty_param_bounds_and_ty {ty: ty::ty_fn_ret(ctor_tpt.ty), ..ctor_tpt} } else { ctor_tpt }; instantiate_path(pcx.fcx, path, struct_tpt, s_def, pat.span, pat.id); // Check that the type of the value being matched is a subtype of // the type of the pattern. let pat_ty = fcx.node_ty(pat.id); demand::subtype(fcx, pat.span, expected, pat_ty); // Get the expected types of the arguments. let class_fields = ty::struct_fields( tcx, struct_def_id, expected_substs); arg_types = class_fields.map(|field| field.mt.ty); kind_name = "structure"; } _ => { // See [Note-Type-error-reporting] in middle/typeck/infer/mod.rs fcx.infcx().type_error_message_str_with_expected(pat.span, |expected, actual| { expected.map_default(~"", |e| { format!("mismatched types: expected `{}` but found {}", e, actual)})}, Some(expected), ~"an enum or structure pattern", None); fcx.write_error(pat.id); kind_name = "[error]"; arg_types = (*subpats).clone() .unwrap_or_default() .map(|_| ty::mk_err()); } } let arg_len = arg_types.len(); // Count the number of subpatterns. let subpats_len; match *subpats { None => subpats_len = arg_len, Some(ref subpats) => subpats_len = subpats.len() } let mut error_happened = false; if arg_len > 0 { // N-ary variant. if arg_len != subpats_len { let s = format!("this pattern has {} field{}, but the corresponding {} has {} field{}", subpats_len, if subpats_len == 1u { ~"" } else { ~"s" }, kind_name, arg_len, if arg_len == 1u { ~"" } else { ~"s" }); tcx.sess.span_err(pat.span, s); error_happened = true; } if !error_happened { for pats in subpats.iter() { for (subpat, arg_ty) in pats.iter().zip(arg_types.iter()) { check_pat(pcx, *subpat, *arg_ty); } } } } else if subpats_len > 0 { tcx.sess.span_err(pat.span, format!("this pattern has {} field{}, but the corresponding {} has no \ fields", subpats_len, if subpats_len == 1u { "" } else { "s" }, kind_name)); error_happened = true; } if error_happened { for pats in subpats.iter() { for pat in pats.iter() { check_pat(pcx, *pat, ty::mk_err()); } } } } /// `path` is the AST path item naming the type of this struct. /// `fields` is the field patterns of the struct pattern. /// `class_fields` describes the type of each field of the struct. /// `class_id` is the ID of the struct. /// `substitutions` are the type substitutions applied to this struct type /// (e.g. K,V in HashMap<K,V>). /// `etc` is true if the pattern said '...' and false otherwise. pub fn check_struct_pat_fields(pcx: &pat_ctxt, span: Span, path: &ast::Path, fields: &[ast::FieldPat], class_fields: ~[ty::field_ty], class_id: ast::DefId, substitutions: &ty::substs, etc: bool) { let tcx = pcx.fcx.ccx.tcx; // Index the class fields. let mut field_map = HashMap::new(); for (i, class_field) in class_fields.iter().enumerate() { field_map.insert(class_field.name, i); } // Typecheck each field. let mut found_fields = HashSet::new(); for field in fields.iter() { match field_map.find(&field.ident.name) { Some(&index) => { let class_field = class_fields[index]; let field_type = ty::lookup_field_type(tcx, class_id,<|fim▁hole|> } None => { let name = pprust::path_to_str(path, tcx.sess.intr()); // Check the pattern anyway, so that attempts to look // up its type won't fail check_pat(pcx, field.pat, ty::mk_err()); tcx.sess.span_err(span, format!("struct `{}` does not have a field named `{}`", name, tcx.sess.str_of(field.ident))); } } } // Report an error if not all the fields were specified. if !etc { for (i, field) in class_fields.iter().enumerate() { if found_fields.contains(&i) { continue; } tcx.sess.span_err(span, format!("pattern does not mention field `{}`", token::interner_get(field.name))); } } } pub fn check_struct_pat(pcx: &pat_ctxt, pat_id: ast::NodeId, span: Span, expected: ty::t, path: &ast::Path, fields: &[ast::FieldPat], etc: bool, struct_id: ast::DefId, substitutions: &ty::substs) { let fcx = pcx.fcx; let tcx = pcx.fcx.ccx.tcx; let class_fields = ty::lookup_struct_fields(tcx, struct_id); // Check to ensure that the struct is the one specified. match tcx.def_map.find(&pat_id) { Some(&ast::DefStruct(supplied_def_id)) if supplied_def_id == struct_id => { // OK. } Some(&ast::DefStruct(*)) | Some(&ast::DefVariant(*)) => { let name = pprust::path_to_str(path, tcx.sess.intr()); tcx.sess.span_err(span, format!("mismatched types: expected `{}` but found `{}`", fcx.infcx().ty_to_str(expected), name)); } _ => { tcx.sess.span_bug(span, "resolve didn't write in struct ID"); } } check_struct_pat_fields(pcx, span, path, fields, class_fields, struct_id, substitutions, etc); } pub fn check_struct_like_enum_variant_pat(pcx: &pat_ctxt, pat_id: ast::NodeId, span: Span, expected: ty::t, path: &ast::Path, fields: &[ast::FieldPat], etc: bool, enum_id: ast::DefId, substitutions: &ty::substs) { let fcx = pcx.fcx; let tcx = pcx.fcx.ccx.tcx; // Find the variant that was specified. match tcx.def_map.find(&pat_id) { Some(&ast::DefVariant(found_enum_id, variant_id, _)) if found_enum_id == enum_id => { // Get the struct fields from this struct-like enum variant. let class_fields = ty::lookup_struct_fields(tcx, variant_id); check_struct_pat_fields(pcx, span, path, fields, class_fields, variant_id, substitutions, etc); } Some(&ast::DefStruct(*)) | Some(&ast::DefVariant(*)) => { let name = pprust::path_to_str(path, tcx.sess.intr()); tcx.sess.span_err(span, format!("mismatched types: expected `{}` but \ found `{}`", fcx.infcx().ty_to_str(expected), name)); } _ => { tcx.sess.span_bug(span, "resolve didn't write in variant"); } } } // Pattern checking is top-down rather than bottom-up so that bindings get // their types immediately. pub fn check_pat(pcx: &pat_ctxt, pat: @ast::Pat, expected: ty::t) { let fcx = pcx.fcx; let tcx = pcx.fcx.ccx.tcx; match pat.node { ast::PatWild => { fcx.write_ty(pat.id, expected); } ast::PatLit(lt) => { check_expr_has_type(fcx, lt, expected); fcx.write_ty(pat.id, fcx.expr_ty(lt)); } ast::PatRange(begin, end) => { check_expr_has_type(fcx, begin, expected); check_expr_has_type(fcx, end, expected); let b_ty = fcx.infcx().resolve_type_vars_if_possible(fcx.expr_ty(begin)); let e_ty = fcx.infcx().resolve_type_vars_if_possible(fcx.expr_ty(end)); debug2!("pat_range beginning type: {:?}", b_ty); debug2!("pat_range ending type: {:?}", e_ty); if !require_same_types( tcx, Some(fcx.infcx()), false, pat.span, b_ty, e_ty, || ~"mismatched types in range") { // no-op } else if !ty::type_is_numeric(b_ty) && !ty::type_is_char(b_ty) { tcx.sess.span_err(pat.span, "non-numeric type used in range"); } else { match valid_range_bounds(fcx.ccx, begin, end) { Some(false) => { tcx.sess.span_err(begin.span, "lower range bound must be less than upper"); }, None => { tcx.sess.span_err(begin.span, "mismatched types in range"); }, _ => { }, } } fcx.write_ty(pat.id, b_ty); } ast::PatEnum(*) | ast::PatIdent(*) if pat_is_const(tcx.def_map, pat) => { let const_did = ast_util::def_id_of_def(tcx.def_map.get_copy(&pat.id)); let const_tpt = ty::lookup_item_type(tcx, const_did); demand::suptype(fcx, pat.span, expected, const_tpt.ty); fcx.write_ty(pat.id, const_tpt.ty); } ast::PatIdent(bm, ref name, sub) if pat_is_binding(tcx.def_map, pat) => { let typ = fcx.local_ty(pat.span, pat.id); match bm { ast::BindByRef(mutbl) => { // if the binding is like // ref x | ref const x | ref mut x // then the type of x is &M T where M is the mutability // and T is the expected type let region_var = fcx.infcx().next_region_var( infer::PatternRegion(pat.span)); let mt = ty::mt {ty: expected, mutbl: mutbl}; let region_ty = ty::mk_rptr(tcx, region_var, mt); demand::eqtype(fcx, pat.span, region_ty, typ); } // otherwise the type of x is the expected type T ast::BindInfer => { demand::eqtype(fcx, pat.span, expected, typ); } } let canon_id = *pcx.map.get(&ast_util::path_to_ident(name)); if canon_id != pat.id { let ct = fcx.local_ty(pat.span, canon_id); demand::eqtype(fcx, pat.span, ct, typ); } fcx.write_ty(pat.id, typ); debug2!("(checking match) writing type for pat id {}", pat.id); match sub { Some(p) => check_pat(pcx, p, expected), _ => () } } ast::PatIdent(_, ref path, _) => { check_pat_variant(pcx, pat, path, &Some(~[]), expected); } ast::PatEnum(ref path, ref subpats) => { check_pat_variant(pcx, pat, path, subpats, expected); } ast::PatStruct(ref path, ref fields, etc) => { // Grab the class data that we care about. let structure = structure_of(fcx, pat.span, expected); let mut error_happened = false; match *structure { ty::ty_struct(cid, ref substs) => { check_struct_pat(pcx, pat.id, pat.span, expected, path, *fields, etc, cid, substs); } ty::ty_enum(eid, ref substs) => { check_struct_like_enum_variant_pat( pcx, pat.id, pat.span, expected, path, *fields, etc, eid, substs); } _ => { // See [Note-Type-error-reporting] in middle/typeck/infer/mod.rs fcx.infcx().type_error_message_str_with_expected(pat.span, |expected, actual| { expected.map_default(~"", |e| { format!("mismatched types: expected `{}` but found {}", e, actual)})}, Some(expected), ~"a structure pattern", None); match tcx.def_map.find(&pat.id) { Some(&ast::DefStruct(supplied_def_id)) => { check_struct_pat(pcx, pat.id, pat.span, ty::mk_err(), path, *fields, etc, supplied_def_id, &ty::substs { self_ty: None, tps: ~[], regions: ty::ErasedRegions} ); } _ => () // Error, but we're already in an error case } error_happened = true; } } // Finally, write in the type. if error_happened { fcx.write_error(pat.id); } else { fcx.write_ty(pat.id, expected); } } ast::PatTup(ref elts) => { let s = structure_of(fcx, pat.span, expected); let e_count = elts.len(); match *s { ty::ty_tup(ref ex_elts) if e_count == ex_elts.len() => { for (i, elt) in elts.iter().enumerate() { check_pat(pcx, *elt, ex_elts[i]); } fcx.write_ty(pat.id, expected); } _ => { for elt in elts.iter() { check_pat(pcx, *elt, ty::mk_err()); } // use terr_tuple_size if both types are tuples let type_error = match *s { ty::ty_tup(ref ex_elts) => ty::terr_tuple_size(ty::expected_found{expected: ex_elts.len(), found: e_count}), _ => ty::terr_mismatch }; // See [Note-Type-error-reporting] in middle/typeck/infer/mod.rs fcx.infcx().type_error_message_str_with_expected(pat.span, |expected, actual| { expected.map_default(~"", |e| { format!("mismatched types: expected `{}` but found {}", e, actual)})}, Some(expected), ~"tuple", Some(&type_error)); fcx.write_error(pat.id); } } } ast::PatBox(inner) => { check_pointer_pat(pcx, Managed, inner, pat.id, pat.span, expected); } ast::PatUniq(inner) => { check_pointer_pat(pcx, Send, inner, pat.id, pat.span, expected); } ast::PatRegion(inner) => { check_pointer_pat(pcx, Borrowed, inner, pat.id, pat.span, expected); } ast::PatVec(ref before, slice, ref after) => { let default_region_var = fcx.infcx().next_region_var( infer::PatternRegion(pat.span)); let (elt_type, region_var) = match *structure_of(fcx, pat.span, expected) { ty::ty_evec(mt, vstore) => { let region_var = match vstore { ty::vstore_slice(r) => r, ty::vstore_box | ty::vstore_uniq | ty::vstore_fixed(_) => { default_region_var } }; (mt, region_var) } ty::ty_unboxed_vec(mt) => { (mt, default_region_var) }, _ => { for &elt in before.iter() { check_pat(pcx, elt, ty::mk_err()); } for &elt in slice.iter() { check_pat(pcx, elt, ty::mk_err()); } for &elt in after.iter() { check_pat(pcx, elt, ty::mk_err()); } // See [Note-Type-error-reporting] in middle/typeck/infer/mod.rs fcx.infcx().type_error_message_str_with_expected( pat.span, |expected, actual| { expected.map_default(~"", |e| { format!("mismatched types: expected `{}` but found {}", e, actual)})}, Some(expected), ~"a vector pattern", None); fcx.write_error(pat.id); return; } }; for elt in before.iter() { check_pat(pcx, *elt, elt_type.ty); } match slice { Some(slice_pat) => { let slice_ty = ty::mk_evec(tcx, ty::mt {ty: elt_type.ty, mutbl: elt_type.mutbl}, ty::vstore_slice(region_var) ); check_pat(pcx, slice_pat, slice_ty); } None => () } for elt in after.iter() { check_pat(pcx, *elt, elt_type.ty); } fcx.write_ty(pat.id, expected); } } } // Helper function to check @, ~ and & patterns pub fn check_pointer_pat(pcx: &pat_ctxt, pointer_kind: PointerKind, inner: @ast::Pat, pat_id: ast::NodeId, span: Span, expected: ty::t) { let fcx = pcx.fcx; let check_inner: &fn(ty::mt) = |e_inner| { check_pat(pcx, inner, e_inner.ty); fcx.write_ty(pat_id, expected); }; match *structure_of(fcx, span, expected) { ty::ty_box(e_inner) if pointer_kind == Managed => { check_inner(e_inner); } ty::ty_uniq(e_inner) if pointer_kind == Send => { check_inner(e_inner); } ty::ty_rptr(_, e_inner) if pointer_kind == Borrowed => { check_inner(e_inner); } _ => { check_pat(pcx, inner, ty::mk_err()); // See [Note-Type-error-reporting] in middle/typeck/infer/mod.rs fcx.infcx().type_error_message_str_with_expected( span, |expected, actual| { expected.map_default(~"", |e| { format!("mismatched types: expected `{}` but found {}", e, actual)})}, Some(expected), format!("{} pattern", match pointer_kind { Managed => "an @-box", Send => "a ~-box", Borrowed => "an &-pointer" }), None); fcx.write_error(pat_id); } } } #[deriving(Eq)] enum PointerKind { Managed, Send, Borrowed }<|fim▁end|>
class_field.id, substitutions); check_pat(pcx, field.pat, field_type); found_fields.insert(index);
<|file_name|>file_scanning.py<|end_file_name|><|fim▁begin|>## simple file type detection. ## if i had unlimited api access, i would send every single md5 to something like VirusTotal forbidden_types = ['text/x-bash', 'text/scriptlet', 'application/x-opc+zip', 'application/com', 'application/x-msmetafile', 'application/x-shellscript', 'text/x-sh', 'text/x-csh', 'application/x-com', 'application/x-helpfile', 'application/hta', 'application/x-bat', 'application/x-php', 'application/x-winexe', 'application/x-msdownload', 'text/x-javascript', 'application/x-msdos-program', 'application/bat', 'application/x-winhelp', 'application/vnd.ms-powerpoint', 'text/x-perl', 'application/x-javascript', 'application/x-ms-shortcut', 'application/vnd.msexcel', 'application/x-msdos-windows', 'text/x-python', 'application/x-download', 'text/javascript', 'text/x-php', 'application/exe', 'application/x-exe', 'application/x-winhlp', 'application/msword', 'application/zip'] from config import * import bparser import notifiers for i in bparser.parseentries('files.log'): if not i['local_orig'] or i['mime_type'] in forbidden_types: ## scan all of these types print print "{} downloaded a file from {} via {}".format(i['rx_hosts'],i['tx_hosts'],i['source'])<|fim▁hole|><|fim▁end|>
print "Filename: {} length: {} mime type: {}".format(i['filename'],i['total_bytes'],i['mime_type']) print "MD5: {} SHA1: {}".format(i['md5'],i['sha1'])
<|file_name|>reference_audio_renderer.cc<|end_file_name|><|fim▁begin|>// Copyright (c) 2012 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 "media/filters/reference_audio_renderer.h" #include <math.h> #include "base/bind.h" #include "base/synchronization/waitable_event.h" namespace media { ReferenceAudioRenderer::ReferenceAudioRenderer(AudioManager* audio_manager) : AudioRendererBase(), audio_manager_(audio_manager), bytes_per_second_(0), has_buffered_data_(true), buffer_capacity_(0) { } ReferenceAudioRenderer::~ReferenceAudioRenderer() { // Close down the audio device. if (controller_) { base::WaitableEvent closed_event(true, false); controller_->Close(base::Bind(&base::WaitableEvent::Signal, base::Unretained(&closed_event))); closed_event.Wait(); } } void ReferenceAudioRenderer::SetPlaybackRate(float rate) { // TODO(fbarchard): limit rate to reasonable values AudioRendererBase::SetPlaybackRate(rate); if (controller_ && rate > 0.0f) controller_->Play(); } void ReferenceAudioRenderer::SetVolume(float volume) { if (controller_) controller_->SetVolume(volume); } void ReferenceAudioRenderer::OnCreated(AudioOutputController* controller) { NOTIMPLEMENTED(); } void ReferenceAudioRenderer::OnPlaying(AudioOutputController* controller) { NOTIMPLEMENTED(); } void ReferenceAudioRenderer::OnPaused(AudioOutputController* controller) { NOTIMPLEMENTED(); } void ReferenceAudioRenderer::OnError(AudioOutputController* controller, int error_code) { NOTIMPLEMENTED(); } void ReferenceAudioRenderer::OnMoreData(AudioOutputController* controller, AudioBuffersState buffers_state) { // TODO(fbarchard): Waveout_output_win.h should handle zero length buffers // without clicking. uint32 pending_bytes = static_cast<uint32>(ceil(buffers_state.total_bytes() * GetPlaybackRate())); base::TimeDelta delay = base::TimeDelta::FromMicroseconds( base::Time::kMicrosecondsPerSecond * pending_bytes / bytes_per_second_); has_buffered_data_ = buffers_state.pending_bytes != 0; uint32 read = FillBuffer(buffer_.get(), buffer_capacity_, delay); controller->EnqueueData(buffer_.get(), read); } void ReferenceAudioRenderer::OnRenderEndOfStream() { // We cannot signal end of stream as long as we have buffered data. // In such case eventually host would playback all the data, and OnMoreData() // would be called with buffers_state.pending_bytes == 0. At that moment // we'll call SignalEndOfStream(); if (!has_buffered_data_) SignalEndOfStream(); } bool ReferenceAudioRenderer::OnInitialize(int bits_per_channel, ChannelLayout channel_layout, int sample_rate) { int samples_per_packet = sample_rate / 10; int hardware_buffer_size = samples_per_packet * ChannelLayoutToChannelCount(channel_layout) * bits_per_channel / 8; // Allocate audio buffer based on hardware buffer size. buffer_capacity_ = 3 * hardware_buffer_size; buffer_.reset(new uint8[buffer_capacity_]); AudioParameters params(AudioParameters::AUDIO_PCM_LINEAR, channel_layout, sample_rate, bits_per_channel, samples_per_packet); bytes_per_second_ = params.GetBytesPerSecond(); controller_ = AudioOutputController::Create(audio_manager_, this, params,<|fim▁hole|> buffer_capacity_); return controller_ != NULL; } void ReferenceAudioRenderer::OnStop() { if (controller_) controller_->Pause(); } } // namespace media<|fim▁end|>
<|file_name|>IntellijModulesListParser.java<|end_file_name|><|fim▁begin|>/* * Copyright (c) Facebook, Inc. and 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 com.facebook.buck.features.project.intellij; import com.facebook.buck.core.exceptions.HumanReadableException; import com.facebook.buck.core.util.log.Logger; import com.facebook.buck.features.project.intellij.model.ModuleIndexEntry; import com.facebook.buck.util.xml.XmlDomParser; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet.Builder; import java.io.IOException; import java.io.InputStream; import java.nio.file.Paths; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** Responsible for parsing an existing modules.xml file */ public class IntellijModulesListParser { private static Logger LOG = Logger.get(IntellijModulesListParser.class); /** * @param modulesFile modules.xml input stream * @return A list of module entries as specified by the modules.xml file * @throws IOException */ public ImmutableSet<ModuleIndexEntry> getAllModules(InputStream modulesFile) throws IOException { final Document doc; try { doc = XmlDomParser.parse(modulesFile);<|fim▁hole|> } final Builder<ModuleIndexEntry> builder = ImmutableSet.builder(); try { XPath xpath = XPathFactory.newInstance().newXPath(); final NodeList moduleList = (NodeList) xpath .compile("/project/component/modules/module") .evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < moduleList.getLength(); i++) { final Element moduleEntry = (Element) moduleList.item(i); if (!moduleEntry.hasAttribute("filepath")) { continue; } String filepath = moduleEntry.getAttribute("filepath"); String fileurl = moduleEntry.getAttribute("fileurl"); String filepathWithoutProjectPrefix; // The template has a hardcoded $PROJECT_DIR$/ prefix, so we need to strip that out // of the value we pass to ST if (filepath.startsWith("$PROJECT_DIR$")) { filepathWithoutProjectPrefix = filepath.substring("$PROJECT_DIR$".length() + 1); } else { filepathWithoutProjectPrefix = filepath; } builder.add( ModuleIndexEntry.builder() .setFilePath(Paths.get(filepathWithoutProjectPrefix)) .setFileUrl(fileurl) .setGroup( moduleEntry.hasAttribute("group") ? moduleEntry.getAttribute("group") : null) .build()); } } catch (XPathExpressionException e) { throw new HumanReadableException("Illegal xpath expression.", e); } return builder.build(); } }<|fim▁end|>
} catch (SAXException e) { LOG.error("Cannot read modules.xml file", e); throw new HumanReadableException( "Could not update 'modules.xml' file because it is malformed", e);
<|file_name|>apps.py<|end_file_name|><|fim▁begin|>from django.apps import AppConfig <|fim▁hole|><|fim▁end|>
class BallerShotCallerConfig(AppConfig): name = 'baller_shot_caller'
<|file_name|>stordb_it_test.go<|end_file_name|><|fim▁begin|>//go:build integration // +build integration /* Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments Copyright (C) ITsysCOM GmbH 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/> */ package services import ( "path" "sync" "testing" "time" "github.com/cgrates/cgrates/config" "github.com/cgrates/cgrates/cores" "github.com/cgrates/cgrates/engine" "github.com/cgrates/cgrates/servmanager" "github.com/cgrates/cgrates/utils" "github.com/cgrates/rpcclient" ) func TestStorDBReload(t *testing.T) { cfg := config.NewDefaultCGRConfig() utils.Logger, _ = utils.Newlogger(utils.MetaSysLog, cfg.GeneralCfg().NodeID) utils.Logger.SetLogLevel(7) filterSChan := make(chan *engine.FilterS, 1) filterSChan <- nil shdChan := utils.NewSyncedChan() shdWg := new(sync.WaitGroup) chS := engine.NewCacheS(cfg, nil, nil) cfg.ChargerSCfg().Enabled = true server := cores.NewServer(nil) srvMngr := servmanager.NewServiceManager(cfg, shdChan, shdWg, nil) srvDep := map[string]*sync.WaitGroup{utils.DataDB: new(sync.WaitGroup)} db := NewDataDBService(cfg, nil, srvDep) cfg.StorDbCfg().Password = "CGRateS.org" stordb := NewStorDBService(cfg, srvDep) anz := NewAnalyzerService(cfg, server, filterSChan, shdChan, make(chan rpcclient.ClientConnector, 1), srvDep) chrS := NewChargerService(cfg, db, chS, filterSChan, server, make(chan rpcclient.ClientConnector, 1), nil, anz, srvDep) schS := NewSchedulerService(cfg, db, chS, filterSChan, server, make(chan rpcclient.ClientConnector, 1), nil, anz, srvDep) ralS := NewRalService(cfg, chS, server, make(chan rpcclient.ClientConnector, 1), make(chan rpcclient.ClientConnector, 1), shdChan, nil, anz, srvDep, filterSChan) cdrsRPC := make(chan rpcclient.ClientConnector, 1) cdrS := NewCDRServer(cfg, db, stordb, filterSChan, server, cdrsRPC, nil, anz, srvDep) srvMngr.AddServices(cdrS, ralS, schS, chrS, NewLoaderService(cfg, db, filterSChan, server, make(chan rpcclient.ClientConnector, 1), nil, anz, srvDep), db, stordb) if err := engine.InitStorDb(cfg); err != nil { t.Fatal(err) } if err := srvMngr.StartServices(); err != nil { t.Error(err) } if cdrS.IsRunning() { t.Errorf("Expected service to be down") } if stordb.IsRunning() { t.Errorf("Expected service to be down") } cfg.RalsCfg().Enabled = true var reply string if err := cfg.V1ReloadConfig(&config.ReloadArgs{ Path: path.Join("/usr", "share", "cgrates", "conf", "samples", "tutmongo"), Section: config.CDRS_JSN, }, &reply); err != nil { t.Error(err) } else if reply != utils.OK { t.Errorf("Expecting OK ,received %s", reply) } select { case d := <-cdrsRPC: cdrsRPC <- d case <-time.After(time.Second): t.Fatal("It took to long to reload the cache") } if !cdrS.IsRunning() { t.Errorf("Expected service to be running") } if !stordb.IsRunning() { t.Errorf("Expected service to be running") } time.Sleep(10 * time.Millisecond) if err := stordb.Reload(); err != nil { t.Fatalf("\nExpecting <nil>,\n Received <%+v>", err) } time.Sleep(10 * time.Millisecond) cfg.StorDbCfg().Password = "" if err := cfg.V1ReloadConfig(&config.ReloadArgs{ Path: path.Join("/usr", "share", "cgrates", "conf", "samples", "tutmongo"), Section: config.STORDB_JSN, }, &reply); err != nil { t.Error(err) } else if reply != utils.OK { t.Errorf("Expecting OK ,received %s", reply) } if err := cdrS.Reload(); err != nil { t.Errorf("\nExpecting <nil>,\n Received <%+v>", err) } if err := stordb.Reload(); err != nil { t.Fatalf("\nExpecting <nil>,\n Received <%+v>", err) } cfg.StorDbCfg().Type = utils.Internal if err := stordb.Reload(); err != nil { t.Errorf("\nExpecting <nil>,\n Received <%+v>", err)<|fim▁hole|> } err := stordb.Start() if err != utils.ErrServiceAlreadyRunning { t.Errorf("\nExpecting <%+v>,\n Received <%+v>", utils.ErrServiceAlreadyRunning, err) } if err := stordb.Reload(); err != nil { t.Errorf("\nExpecting <nil>,\n Received <%+v>", err) } if err := db.Start(); err == nil || err != utils.ErrServiceAlreadyRunning { t.Errorf("\nExpecting <%+v>,\n Received <%+v>", utils.ErrServiceAlreadyRunning, err) } if err := cdrS.Start(); err == nil || err != utils.ErrServiceAlreadyRunning { t.Errorf("\nExpecting <%+v>,\n Received <%+v>", utils.ErrServiceAlreadyRunning, err) } if err := cdrS.Reload(); err != nil { t.Errorf("\nExpecting <nil>,\n Received <%+v>", err) } cfg.CdrsCfg().Enabled = false cfg.GetReloadChan(config.CDRS_JSN) <- struct{}{} time.Sleep(10 * time.Millisecond) if cdrS.IsRunning() { t.Errorf("Expected service to be down") } shdChan.CloseOnce() time.Sleep(10 * time.Millisecond) } func TestStorDBReloadVersion1(t *testing.T) { cfg, err := config.NewCGRConfigFromPath(path.Join("/usr", "share", "cgrates", "conf", "samples", "tutmongo")) if err != nil { t.Fatal(err) } storageDb, err := engine.NewStorDBConn(cfg.StorDbCfg().Type, cfg.StorDbCfg().Host, cfg.StorDbCfg().Port, cfg.StorDbCfg().Name, cfg.StorDbCfg().User, cfg.StorDbCfg().Password, cfg.GeneralCfg().DBDataEncoding, cfg.StorDbCfg().StringIndexedFields, cfg.StorDbCfg().PrefixIndexedFields, cfg.StorDbCfg().Opts, cfg.StorDbCfg().Items) if err != nil { t.Fatal(err) } defer func() { storageDb.Flush("") storageDb.Close() }() err = storageDb.SetVersions(engine.Versions{ utils.CostDetails: 2, utils.SessionSCosts: 3, //old version for CDRs utils.CDRs: 1, utils.TpRatingPlans: 1, utils.TpFilters: 1, utils.TpDestinationRates: 1, utils.TpActionTriggers: 1, utils.TpAccountActionsV: 1, utils.TpActionPlans: 1, utils.TpActions: 1, utils.TpThresholds: 1, utils.TpRoutes: 1, utils.TpStats: 1, utils.TpSharedGroups: 1, utils.TpRatingProfiles: 1, utils.TpResources: 1, utils.TpRates: 1, utils.TpTiming: 1, utils.TpResource: 1, utils.TpDestinations: 1, utils.TpRatingPlan: 1, utils.TpRatingProfile: 1, utils.TpChargers: 1, utils.TpDispatchers: 1, }, true) utils.Logger, _ = utils.Newlogger(utils.MetaSysLog, cfg.GeneralCfg().NodeID) utils.Logger.SetLogLevel(7) filterSChan := make(chan *engine.FilterS, 1) filterSChan <- nil shdChan := utils.NewSyncedChan() cfg.ChargerSCfg().Enabled = true srvDep := map[string]*sync.WaitGroup{utils.DataDB: new(sync.WaitGroup)} stordb := NewStorDBService(cfg, srvDep) stordb.oldDBCfg = cfg.StorDbCfg().Clone() if err := engine.InitStorDb(cfg); err != nil { t.Fatal(err) } err = stordb.Start() if err != nil { t.Fatal(err) } stordb.db = nil err = stordb.Reload() if err == nil || err.Error() != "can't conver StorDB of type mongo to MongoStorage" { t.Fatal(err) } cfg.CdrsCfg().Enabled = false err = stordb.Reload() if err == nil || err.Error() != "can't conver StorDB of type mongo to MongoStorage" { t.Fatal(err) } time.Sleep(10 * time.Millisecond) shdChan.CloseOnce() time.Sleep(10 * time.Millisecond) } func TestStorDBReloadVersion2(t *testing.T) { cfg, err := config.NewCGRConfigFromPath(path.Join("/usr", "share", "cgrates", "conf", "samples", "tutmysql")) if err != nil { t.Fatal(err) } storageDb, err := engine.NewStorDBConn(cfg.StorDbCfg().Type, cfg.StorDbCfg().Host, cfg.StorDbCfg().Port, cfg.StorDbCfg().Name, cfg.StorDbCfg().User, cfg.StorDbCfg().Password, cfg.GeneralCfg().DBDataEncoding, cfg.StorDbCfg().StringIndexedFields, cfg.StorDbCfg().PrefixIndexedFields, cfg.StorDbCfg().Opts, cfg.StorDbCfg().Items) if err != nil { t.Fatal(err) } defer func() { storageDb.Flush("") storageDb.Close() }() err = storageDb.SetVersions(engine.Versions{ utils.CostDetails: 2, utils.SessionSCosts: 3, //old version for CDRs utils.CDRs: 1, utils.TpRatingPlans: 1, utils.TpFilters: 1, utils.TpDestinationRates: 1, utils.TpActionTriggers: 1, utils.TpAccountActionsV: 1, utils.TpActionPlans: 1, utils.TpActions: 1, utils.TpThresholds: 1, utils.TpRoutes: 1, utils.TpStats: 1, utils.TpSharedGroups: 1, utils.TpRatingProfiles: 1, utils.TpResources: 1, utils.TpRates: 1, utils.TpTiming: 1, utils.TpResource: 1, utils.TpDestinations: 1, utils.TpRatingPlan: 1, utils.TpRatingProfile: 1, utils.TpChargers: 1, utils.TpDispatchers: 1, }, true) utils.Logger, _ = utils.Newlogger(utils.MetaSysLog, cfg.GeneralCfg().NodeID) utils.Logger.SetLogLevel(7) filterSChan := make(chan *engine.FilterS, 1) filterSChan <- nil shdChan := utils.NewSyncedChan() cfg.ChargerSCfg().Enabled = true srvDep := map[string]*sync.WaitGroup{utils.DataDB: new(sync.WaitGroup)} cfg.StorDbCfg().Password = "CGRateS.org" stordb := NewStorDBService(cfg, srvDep) stordb.oldDBCfg = cfg.StorDbCfg().Clone() if err := engine.InitStorDb(cfg); err != nil { t.Fatal(err) } err = stordb.Start() if err != nil { t.Fatal(err) } stordb.db = nil err = stordb.Reload() if err == nil || err.Error() != "can't conver StorDB of type mysql to SQLStorage" { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", "can't convert StorDB of type mysql to SQLStorage", err) } cfg.CdrsCfg().Enabled = false err = stordb.Reload() if err == nil || err.Error() != "can't conver StorDB of type mysql to SQLStorage" { t.Errorf("\nExpected <%+v>, \nReceived <%+v>", "can't convert StorDB of type mysql to SQLStorage", err) time.Sleep(10 * time.Millisecond) shdChan.CloseOnce() time.Sleep(10 * time.Millisecond) } } func TestStorDBReloadVersion3(t *testing.T) { cfg, err := config.NewCGRConfigFromPath(path.Join("/usr", "share", "cgrates", "conf", "samples", "tutinternal")) if err != nil { t.Fatal(err) } storageDb, err := engine.NewStorDBConn(cfg.StorDbCfg().Type, cfg.StorDbCfg().Host, cfg.StorDbCfg().Port, cfg.StorDbCfg().Name, cfg.StorDbCfg().User, cfg.StorDbCfg().Password, cfg.GeneralCfg().DBDataEncoding, cfg.StorDbCfg().StringIndexedFields, cfg.StorDbCfg().PrefixIndexedFields, cfg.StorDbCfg().Opts, cfg.StorDbCfg().Items) if err != nil { t.Fatal(err) } defer func() { storageDb.Flush("") storageDb.Close() }() err = storageDb.SetVersions(engine.Versions{ utils.CostDetails: 2, utils.SessionSCosts: 3, //old version for CDRs utils.CDRs: 1, utils.TpRatingPlans: 1, utils.TpFilters: 1, utils.TpDestinationRates: 1, utils.TpActionTriggers: 1, utils.TpAccountActionsV: 1, utils.TpActionPlans: 1, utils.TpActions: 1, utils.TpThresholds: 1, utils.TpRoutes: 1, utils.TpStats: 1, utils.TpSharedGroups: 1, utils.TpRatingProfiles: 1, utils.TpResources: 1, utils.TpRates: 1, utils.TpTiming: 1, utils.TpResource: 1, utils.TpDestinations: 1, utils.TpRatingPlan: 1, utils.TpRatingProfile: 1, utils.TpChargers: 1, utils.TpDispatchers: 1, }, true) utils.Logger, _ = utils.Newlogger(utils.MetaSysLog, cfg.GeneralCfg().NodeID) utils.Logger.SetLogLevel(7) filterSChan := make(chan *engine.FilterS, 1) filterSChan <- nil // shdChan := utils.NewSyncedChan() cfg.ChargerSCfg().Enabled = true srvDep := map[string]*sync.WaitGroup{utils.DataDB: new(sync.WaitGroup)} cfg.StorDbCfg().Password = "CGRateS.org" stordb := NewStorDBService(cfg, srvDep) stordb.oldDBCfg = cfg.StorDbCfg().Clone() stordb.db = nil err = stordb.Reload() if err == nil || err.Error() != "can't conver StorDB of type internal to InternalDB" { t.Fatal(err) } /* the internal now uses its own cache err = stordb.Start() if err == nil { t.Fatal(err) } cfg.CdrsCfg().Enabled = false err = stordb.Reload() if err != nil { t.Fatal(err) } time.Sleep(10 * time.Millisecond) shdChan.CloseOnce() time.Sleep(10 * time.Millisecond) */ } func TestStorDBReloadNewStorDBConnError(t *testing.T) { cfg := config.NewDefaultCGRConfig() utils.Logger, _ = utils.Newlogger(utils.MetaSysLog, cfg.GeneralCfg().NodeID) utils.Logger.SetLogLevel(7) filterSChan := make(chan *engine.FilterS, 1) filterSChan <- nil shdChan := utils.NewSyncedChan() cfg.ChargerSCfg().Enabled = true srvDep := map[string]*sync.WaitGroup{utils.DataDB: new(sync.WaitGroup)} cfg.StorDbCfg().Password = "CGRateS.org" stordb := NewStorDBService(cfg, srvDep) stordb.oldDBCfg = &config.StorDbCfg{ Type: utils.Internal, Host: "test_host", Port: "test_port", Name: "test_name", User: "test_user", Password: "test_pass", } cfg.StorDbCfg().Type = "badType" err := stordb.Reload() if err == nil || err.Error() != "unknown db 'badType' valid options are [mysql, mongo, postgres, internal]" { t.Errorf("\nExpecting <%+v>,\n Received <%+v>", "unknown db 'badType' valid options are [mysql, mongo, postgres, internal]", err) } shdChan.CloseOnce() } func TestStorDBReloadCanCastError(t *testing.T) { cfg := config.NewDefaultCGRConfig() utils.Logger, _ = utils.Newlogger(utils.MetaSysLog, cfg.GeneralCfg().NodeID) utils.Logger.SetLogLevel(7) filterSChan := make(chan *engine.FilterS, 1) filterSChan <- nil shdChan := utils.NewSyncedChan() cfg.ChargerSCfg().Enabled = true srvDep := map[string]*sync.WaitGroup{utils.DataDB: new(sync.WaitGroup)} cfg.StorDbCfg().Password = "CGRateS.org" cfg.StorDbCfg().Type = utils.Mongo stordb := NewStorDBService(cfg, srvDep) stordb.cfg.StorDbCfg().Opts = map[string]interface{}{ utils.MongoQueryTimeoutCfg: false, } stordb.db = &engine.MongoStorage{} stordb.oldDBCfg = cfg.StorDbCfg().Clone() err := stordb.Reload() if err == nil || err.Error() != "cannot convert field: false to time.Duration" { t.Errorf("\nExpecting <%+v>,\n Received <%+v>", "cannot convert field: false to time.Duration", err) } shdChan.CloseOnce() } func TestStorDBReloadIfaceAsTIntMaxOpenConnsCfgError(t *testing.T) { cfg := config.NewDefaultCGRConfig() utils.Logger, _ = utils.Newlogger(utils.MetaSysLog, cfg.GeneralCfg().NodeID) utils.Logger.SetLogLevel(7) filterSChan := make(chan *engine.FilterS, 1) filterSChan <- nil shdChan := utils.NewSyncedChan() cfg.ChargerSCfg().Enabled = true srvDep := map[string]*sync.WaitGroup{utils.DataDB: new(sync.WaitGroup)} cfg.StorDbCfg().Password = "CGRateS.org" cfg.StorDbCfg().Type = utils.MySQL stordb := NewStorDBService(cfg, srvDep) stordb.cfg.StorDbCfg().Opts = map[string]interface{}{ utils.SQLMaxOpenConnsCfg: false, } stordb.db = &engine.SQLStorage{} stordb.oldDBCfg = cfg.StorDbCfg().Clone() err := stordb.Reload() expected := "cannot convert field<bool>: false to int" if err == nil || err.Error() != expected { t.Errorf("\nExpecting <%+v>,\n Received <%+v>", expected, err) } shdChan.CloseOnce() } func TestStorDBReloadIfaceAsTIntConnMaxLifetimeCfgError(t *testing.T) { cfg := config.NewDefaultCGRConfig() utils.Logger, _ = utils.Newlogger(utils.MetaSysLog, cfg.GeneralCfg().NodeID) utils.Logger.SetLogLevel(7) filterSChan := make(chan *engine.FilterS, 1) filterSChan <- nil shdChan := utils.NewSyncedChan() cfg.ChargerSCfg().Enabled = true srvDep := map[string]*sync.WaitGroup{utils.DataDB: new(sync.WaitGroup)} cfg.StorDbCfg().Password = "CGRateS.org" cfg.StorDbCfg().Type = utils.MySQL stordb := NewStorDBService(cfg, srvDep) stordb.cfg.StorDbCfg().Opts = map[string]interface{}{ utils.SQLMaxOpenConnsCfg: 1, utils.SQLMaxIdleConnsCfg: 1, utils.SQLConnMaxLifetimeCfg: false, } stordb.db = &engine.SQLStorage{} stordb.oldDBCfg = cfg.StorDbCfg().Clone() err := stordb.Reload() expected := "cannot convert field<bool>: false to int" if err == nil || err.Error() != expected { t.Errorf("\nExpecting <%+v>,\n Received <%+v>", expected, err) } shdChan.CloseOnce() } func TestStorDBReloadIfaceAsTIntMaxIdleConnsCfgError(t *testing.T) { cfg := config.NewDefaultCGRConfig() utils.Logger, _ = utils.Newlogger(utils.MetaSysLog, cfg.GeneralCfg().NodeID) utils.Logger.SetLogLevel(7) filterSChan := make(chan *engine.FilterS, 1) filterSChan <- nil shdChan := utils.NewSyncedChan() cfg.ChargerSCfg().Enabled = true srvDep := map[string]*sync.WaitGroup{utils.DataDB: new(sync.WaitGroup)} cfg.StorDbCfg().Password = "CGRateS.org" cfg.StorDbCfg().Type = utils.MySQL stordb := NewStorDBService(cfg, srvDep) stordb.cfg.StorDbCfg().Opts = map[string]interface{}{ utils.SQLMaxOpenConnsCfg: 1, utils.SQLMaxIdleConnsCfg: false, utils.SQLConnMaxLifetimeCfg: 1, } stordb.db = &engine.SQLStorage{} stordb.oldDBCfg = cfg.StorDbCfg().Clone() err := stordb.Reload() expected := "cannot convert field<bool>: false to int" if err == nil || err.Error() != expected { t.Errorf("\nExpecting <%+v>,\n Received <%+v>", expected, err) } shdChan.CloseOnce() } func TestStorDBReloadStartDBError(t *testing.T) { cfg := config.NewDefaultCGRConfig() utils.Logger, _ = utils.Newlogger(utils.MetaSysLog, cfg.GeneralCfg().NodeID) utils.Logger.SetLogLevel(7) filterSChan := make(chan *engine.FilterS, 1) filterSChan <- nil shdChan := utils.NewSyncedChan() cfg.ChargerSCfg().Enabled = true srvDep := map[string]*sync.WaitGroup{utils.DataDB: new(sync.WaitGroup)} cfg.StorDbCfg().Password = "CGRateS.org" stordb := NewStorDBService(cfg, srvDep) cfg.StorDbCfg().Type = "badType" err := stordb.Start() expected := "unknown db 'badType' valid options are [mysql, mongo, postgres, internal]" if err == nil || err.Error() != expected { t.Errorf("\nExpecting <%+v>,\n Received <%+v>", expected, err) } shdChan.CloseOnce() }<|fim▁end|>
<|file_name|>state-machine.js<|end_file_name|><|fim▁begin|>import Ember from 'ember'; import StatefulMixin from './mixins/stateful';<|fim▁hole|><|fim▁end|>
export default Ember.Object.extend(StatefulMixin);
<|file_name|>observable.ts<|end_file_name|><|fim▁begin|>import "core-js/es6/promise"; import "core-js/es6/array" import "core-js/es6/set" import {IObservable} from "./interfaces/observable"; import {IObservableEvent} from "./interfaces/observable-event"; import {IObserver, ObserverCallback} from "./interfaces/observer"; import {IObserverItem} from "./interfaces/obervable-item" import {ICancel} from "./interfaces/cancel"; export class Observable implements IObservable { private observers : IObserverItem[] = []; constructor() {} count(): number { return this.observers.length; } clear(): void { this.observers.splice(0, this.observers.length); } on(type: string | IObservableEvent | (string | IObservableEvent)[], callback: ObserverCallback | IObserver) : ICancel { let cancel : ICancel = { cancel: () => { let index : number = this.observers.findIndex((item : IObserverItem) => item.id === cancel); // If the index is larger than -1, then remove the item if (index > -1) {<|fim▁hole|> } // Else the remove failed return false; } }; // If type is an array then push that to the observers if (Array.isArray(type)) { this.observers.push({ id: cancel, types: new Set<string>(type.map(item => isObservableEvent(item) ? item.name : item)), callback: callback }); } // If type is not an array else { this.observers.push({ id: cancel, types: new Set<string>([isObservableEvent(type) ? type.name : type]), callback: callback }); } return cancel; } off(observer: IObserver): boolean { // Find the index of the array let index : number = this.observers.findIndex((item : IObserverItem) => item.callback === observer); // If the index is larger than -1, then remove the item if (index > -1) { this.observers.splice(index, 1); return true; } // Else the remove failed return false; } notify(event: IObservableEvent, data: any): Promise<void> { // Make function decoupled return Promise.resolve().then(() => { let types: string[] = [event.name], calledEventName: string = event.name; // Select all events to be called while (event.parent !== undefined && event.parent !== null) { event = event.parent; types.push(event.name); } // Call all observers having the type this.observers.forEach(observer => { if (types.some(type => observer.types.has(type))) { if (isObserver(observer.callback)) { observer.callback.update(data, calledEventName); } else { observer.callback(data, calledEventName); } } }); }); } } /** * Check if the item is of type IObservableEvent * @param tested is the parameter to be tested * @return {boolean} true if the item is instance of IObservableEvent, otherwise false */ function isObservableEvent(tested: any) : tested is IObservableEvent { return tested !== undefined && tested !== null && tested.hasOwnProperty('name') && tested.hasOwnProperty('parent'); } /** * Check if the item is of type IObserver * @param tested is the parameter to be tested * @return {boolean} true if the item is instance of IObserver, otherwise false */ function isObserver(tested: any) : tested is IObserver { return tested !== undefined && tested !== null && typeof tested.update === 'function'; }<|fim▁end|>
this.observers.splice(index, 1); return true;
<|file_name|>keepass.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) 2014 The Darkcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "keepass.h" #include <exception> #include <openssl/rand.h> #include <boost/lexical_cast.hpp> #include <boost/foreach.hpp> //#include <boost/asio.hpp> #include "util.h" //#include "random.h" #include "serialize.h" //#include "utilstrencodings.h" #include "clientversion.h" #include "json/json_spirit_writer_template.h" #include "json/json_spirit_reader_template.h" #include "rpcprotocol.h" #include "script.h" //#include "script/script.h" // Necessary to prevent compile errors due to forward declaration of //CScript in serialize.h (included from crypter.h) #include "wallet.h" using boost::asio::ip::tcp; CKeePassIntegrator keePassInt; CKeePassIntegrator::CKeePassIntegrator() :sKeyBase64(" "), sKey(" "), sUrl(" ") // Prevent LockedPageManagerBase complaints { sKeyBase64.clear(); // Prevent LockedPageManagerBase complaints sKey.clear(); // Prevent LockedPageManagerBase complaints sUrl.clear(); // Prevent LockedPageManagerBase complaints bIsActive = false; nPort = KEEPASS_KEEPASSHTTP_PORT; } // Initialze from application context void CKeePassIntegrator::init() { bIsActive = GetBoolArg("-keepass", false); nPort = boost::lexical_cast<unsigned int>(GetArg("-keepassport", KEEPASS_KEEPASSHTTP_PORT)); sKeyBase64 = SecureString(GetArg("-keepasskey", "").c_str()); sKeePassId = GetArg("-keepassid", ""); sKeePassEntryName = GetArg("-keepassname", ""); // Convert key if available if(sKeyBase64.size() > 0) { sKey = DecodeBase64Secure(sKeyBase64); } // Construct url if available if(sKeePassEntryName.size() > 0) { sUrl = SecureString("http://"); sUrl += SecureString(sKeePassEntryName.c_str()); sUrl += SecureString("/"); //sSubmitUrl = "http://"; //sSubmitUrl += SecureString(sKeePassEntryName.c_str()); } } void CKeePassIntegrator::CKeePassRequest::addStrParameter(std::string sName, std::string sValue) { requestObj.push_back(json_spirit::Pair(sName, sValue)); } void CKeePassIntegrator::CKeePassRequest::addStrParameter(std::string sName, SecureString sValue) { std::string sCipherValue; if(!EncryptAES256(sKey, sValue, sIV, sCipherValue)) { throw std::runtime_error("Unable to encrypt Verifier"); } addStrParameter(sName, EncodeBase64(sCipherValue)); } std::string CKeePassIntegrator::CKeePassRequest::getJson() { return json_spirit::write_string(json_spirit::Value(requestObj), false); } void CKeePassIntegrator::CKeePassRequest::init() { SecureString sIVSecure = generateRandomKey(KEEPASS_CRYPTO_BLOCK_SIZE); sIV = std::string(&sIVSecure[0], sIVSecure.size()); // Generate Nonce, Verifier and RequestType SecureString sNonceBase64Secure = EncodeBase64Secure(sIVSecure); addStrParameter("Nonce", std::string(&sNonceBase64Secure[0], sNonceBase64Secure.size())); // Plain addStrParameter("Verifier", sNonceBase64Secure); // Encoded addStrParameter("RequestType", sType); } void CKeePassIntegrator::CKeePassResponse::parseResponse(std::string sResponse) { json_spirit::Value responseValue; if(!json_spirit::read_string(sResponse, responseValue)) { throw std::runtime_error("Unable to parse KeePassHttp response"); } responseObj = responseValue.get_obj(); // retrieve main values bSuccess = json_spirit::find_value(responseObj, "Success").get_bool(); sType = getStr("RequestType"); sIV = DecodeBase64(getStr("Nonce")); } std::string CKeePassIntegrator::CKeePassResponse::getStr(std::string sName) { std::string sValue(json_spirit::find_value(responseObj, sName).get_str()); return sValue; } SecureString CKeePassIntegrator::CKeePassResponse::getSecureStr(std::string sName) { std::string sValueBase64Encrypted(json_spirit::find_value(responseObj, sName).get_str()); SecureString sValue; try { sValue = decrypt(sValueBase64Encrypted); } catch (std::exception &e) { std::string sErrorMessage = "Exception occured while decrypting "; sErrorMessage += sName + ": " + e.what(); throw std::runtime_error(sErrorMessage); } return sValue; } SecureString CKeePassIntegrator::CKeePassResponse::decrypt(std::string sValueBase64Encrypted) { std::string sValueEncrypted = DecodeBase64(sValueBase64Encrypted); SecureString sValue; if(!DecryptAES256(sKey, sValueEncrypted, sIV, sValue)) { throw std::runtime_error("Unable to decrypt value."); } return sValue; } std::vector<CKeePassIntegrator::CKeePassEntry> CKeePassIntegrator::CKeePassResponse::getEntries() { std::vector<CKeePassEntry> vEntries; json_spirit::Array aEntries = json_spirit::find_value(responseObj, "Entries").get_array(); for(json_spirit::Array::iterator it = aEntries.begin(); it != aEntries.end(); ++it) { SecureString sEntryUuid(decrypt(json_spirit::find_value((*it).get_obj(), "Uuid").get_str().c_str())); SecureString sEntryName(decrypt(json_spirit::find_value((*it).get_obj(), "Name").get_str().c_str())); SecureString sEntryLogin(decrypt(json_spirit::find_value((*it).get_obj(), "Login").get_str().c_str())); SecureString sEntryPassword(decrypt(json_spirit::find_value((*it).get_obj(), "Password").get_str().c_str())); CKeePassEntry entry(sEntryUuid, sEntryUuid, sEntryLogin, sEntryPassword); vEntries.push_back(entry); } return vEntries; } SecureString CKeePassIntegrator::generateRandomKey(size_t nSize) { // Generates random key SecureString key; key.resize(nSize); RandAddSeedPerfmon(); RAND_bytes((unsigned char *) &key[0], nSize); return key; } // Construct POST body for RPC JSON call std::string CKeePassIntegrator::constructHTTPPost(const std::string& strMsg, const std::map<std::string,std::string>& mapRequestHeaders) { std::ostringstream s; s << "POST / HTTP/1.1\r\n" << "User-Agent: crave-json-rpc/" << FormatFullVersion() << "\r\n" << "Host: localhost\r\n" << "Content-Type: application/json\r\n" << "Content-Length: " << strMsg.size() << "\r\n" << "Connection: close\r\n" << "Accept: application/json\r\n"; BOOST_FOREACH(const PAIRTYPE(std::string, std::string)& item, mapRequestHeaders) s << item.first << ": " << item.second << "\r\n"; s << "\r\n" << strMsg; return s.str(); } // Send RPC message to KeePassHttp void CKeePassIntegrator::doHTTPPost(const std::string& sRequest, int& nStatus, std::string& sResponse) { // Prepare communication boost::asio::io_service io_service; // Get a list of endpoints corresponding to the server name. tcp::resolver resolver(io_service); tcp::resolver::query query(KEEPASS_KEEPASSHTTP_HOST, boost::lexical_cast<std::string>(nPort)); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); tcp::resolver::iterator end; // Try each endpoint until we successfully establish a connection. tcp::socket socket(io_service); boost::system::error_code error = boost::asio::error::host_not_found; while (error && endpoint_iterator != end) { socket.close(); socket.connect(*endpoint_iterator++, error); } if(error) { throw boost::system::system_error(error); } // Form the request. std::map<std::string, std::string> mapRequestHeaders; std::string strPost = constructHTTPPost(sRequest, mapRequestHeaders); // Logging of actual post data disabled as to not write passphrase in debug.log. Only enable temporarily when needed //if(fDebug) LogPrintf("CKeePassIntegrator::doHTTPPost - send POST data: %s\n", strPost.c_str()); if(fDebug) LogPrintf("CKeePassIntegrator::doHTTPPost - send POST data\n"); boost::asio::streambuf request; std::ostream request_stream(&request); request_stream << strPost; // Send the request. boost::asio::write(socket, request); if(fDebug) LogPrintf("CKeePassIntegrator::doHTTPPost - request written\n"); // Read the response status line. The response streambuf will automatically // grow to accommodate the entire line. The growth may be limited by passing // a maximum size to the streambuf constructor. boost::asio::streambuf response; boost::asio::read_until(socket, response, "\r\n"); if(fDebug) LogPrintf("CKeePassIntegrator::doHTTPPost - request status line read\n");<|fim▁hole|> // Receive HTTP reply status int nProto = 0; std::istream response_stream(&response); nStatus = ReadHTTPStatus(response_stream, nProto); if(fDebug) LogPrintf("CKeePassIntegrator::doHTTPPost - reading response body start\n"); // Read until EOF, writing data to output as we go. while (boost::asio::read(socket, response, boost::asio::transfer_at_least(1), error)) { if (error != boost::asio::error::eof) { if (error != 0) { // 0 is success throw boost::system::system_error(error); } } } if(fDebug) LogPrintf("CKeePassIntegrator::doHTTPPost - reading response body end\n"); // Receive HTTP reply message headers and body std::map<std::string, std::string> mapHeaders; ReadHTTPMessage(response_stream, mapHeaders, sResponse, nProto, MAX_SIZE); if(fDebug) LogPrintf("CKeePassIntegrator::doHTTPPost - Processed body\n"); } void CKeePassIntegrator::rpcTestAssociation(bool bTriggerUnlock) { CKeePassRequest request(sKey, "test-associate"); request.addStrParameter("TriggerUnlock", std::string(bTriggerUnlock ? "true" : "false")); int nStatus; std::string sResponse; doHTTPPost(request.getJson(), nStatus, sResponse); if(fDebug) LogPrintf("CKeePassIntegrator::rpcTestAssociation - send result: status: %d response: %s\n", nStatus, sResponse.c_str()); } std::vector<CKeePassIntegrator::CKeePassEntry> CKeePassIntegrator::rpcGetLogins() { // Convert key format SecureString sKey = DecodeBase64Secure(sKeyBase64); CKeePassRequest request(sKey, "get-logins"); request.addStrParameter("addStrParameter", std::string("true")); request.addStrParameter("TriggerUnlock", std::string("true")); request.addStrParameter("Id", sKeePassId); request.addStrParameter("Url", sUrl); int nStatus; std::string sResponse; doHTTPPost(request.getJson(), nStatus, sResponse); // Logging of actual response data disabled as to not write passphrase in debug.log. Only enable temporarily when needed //if(fDebug) LogPrintf("CKeePassIntegrator::rpcGetLogins - send result: status: %d response: %s\n", nStatus, sResponse.c_str()); if(fDebug) LogPrintf("CKeePassIntegrator::rpcGetLogins - send result: status: %d\n", nStatus); if(nStatus != 200) { std::string sErrorMessage = "Error returned by KeePassHttp: HTTP code "; sErrorMessage += boost::lexical_cast<std::string>(nStatus); sErrorMessage += " - Response: "; sErrorMessage += " response: ["; sErrorMessage += sResponse; sErrorMessage += "]"; throw std::runtime_error(sErrorMessage); } // Parse the response CKeePassResponse response(sKey, sResponse); if(!response.getSuccess()) { std::string sErrorMessage = "KeePassHttp returned failure status"; throw std::runtime_error(sErrorMessage); } return response.getEntries(); } void CKeePassIntegrator::rpcSetLogin(const SecureString& strWalletPass, const SecureString& sEntryId) { // Convert key format SecureString sKey = DecodeBase64Secure(sKeyBase64); CKeePassRequest request(sKey, "set-login"); request.addStrParameter("Id", sKeePassId); request.addStrParameter("Url", sUrl); if(fDebug) LogPrintf("CKeePassIntegrator::rpcSetLogin - send Url: %s\n", sUrl.c_str()); //request.addStrParameter("SubmitUrl", sSubmitUrl); // Is used to construct the entry title request.addStrParameter("Login", SecureString("crave")); request.addStrParameter("Password", strWalletPass); if(sEntryId.size() != 0) { request.addStrParameter("Uuid", sEntryId); // Update existing } int nStatus; std::string sResponse; doHTTPPost(request.getJson(), nStatus, sResponse); if(fDebug) LogPrintf("CKeePassIntegrator::rpcSetLogin - send result: status: %d response: %s\n", nStatus, sResponse.c_str()); if(nStatus != 200) { std::string sErrorMessage = "Error returned: HTTP code "; sErrorMessage += boost::lexical_cast<std::string>(nStatus); sErrorMessage += " - Response: "; sErrorMessage += " response: ["; sErrorMessage += sResponse; sErrorMessage += "]"; throw std::runtime_error(sErrorMessage); } // Parse the response CKeePassResponse response(sKey, sResponse); if(!response.getSuccess()) { throw std::runtime_error("KeePassHttp returned failure status"); } } SecureString CKeePassIntegrator::generateKeePassKey() { SecureString sKey = generateRandomKey(KEEPASS_CRYPTO_KEY_SIZE); SecureString sKeyBase64 = EncodeBase64Secure(sKey); return sKeyBase64; } void CKeePassIntegrator::rpcAssociate(std::string& sId, SecureString& sKeyBase64) { sKey = generateRandomKey(KEEPASS_CRYPTO_KEY_SIZE); CKeePassRequest request(sKey, "associate"); sKeyBase64 = EncodeBase64Secure(sKey); request.addStrParameter("Key", std::string(&sKeyBase64[0], sKeyBase64.size())); int nStatus; std::string sResponse; doHTTPPost(request.getJson(), nStatus, sResponse); if(fDebug) LogPrintf("CKeePassIntegrator::rpcAssociate - send result: status: %d response: %s\n", nStatus, sResponse.c_str()); if(nStatus != 200) { std::string sErrorMessage = "Error returned: HTTP code "; sErrorMessage += boost::lexical_cast<std::string>(nStatus); sErrorMessage += " - Response: "; sErrorMessage += " response: ["; sErrorMessage += sResponse; sErrorMessage += "]"; throw std::runtime_error(sErrorMessage); } // Parse the response CKeePassResponse response(sKey, sResponse); if(!response.getSuccess()) { throw std::runtime_error("KeePassHttp returned failure status"); } // If we got here, we were successful. Return the information sId = response.getStr("Id"); } // Retrieve wallet passphrase from KeePass SecureString CKeePassIntegrator::retrievePassphrase() { // Check we have all required information if(sKey.size() == 0) { throw std::runtime_error("keepasskey parameter is not defined. Please specify the configuration parameter."); } if(sKeePassId.size() == 0) { throw std::runtime_error("keepassid parameter is not defined. Please specify the configuration parameter."); } if(sKeePassEntryName == "") { throw std::runtime_error("keepassname parameter is not defined. Please specify the configuration parameter."); } // Retrieve matching logins from KeePass std::vector<CKeePassIntegrator::CKeePassEntry> entries = rpcGetLogins(); // Only accept one unique match if(entries.size() == 0) { throw std::runtime_error("KeePassHttp returned 0 matches, please verify the keepassurl setting."); } if(entries.size() > 1) { throw std::runtime_error("KeePassHttp returned multiple matches, bailing out."); } return entries[0].getPassword(); } // Update wallet passphrase in keepass void CKeePassIntegrator::updatePassphrase(const SecureString& sWalletPassphrase) { // Check we have all required information if(sKey.size() == 0) { throw std::runtime_error("keepasskey parameter is not defined. Please specify the configuration parameter."); } if(sKeePassId.size() == 0) { throw std::runtime_error("keepassid parameter is not defined. Please specify the configuration parameter."); } if(sKeePassEntryName == "") { throw std::runtime_error("keepassname parameter is not defined. Please specify the configuration parameter."); } SecureString sEntryId(""); std::string sErrorMessage; // Lookup existing entry std::vector<CKeePassIntegrator::CKeePassEntry> vEntries = rpcGetLogins(); if(vEntries.size() > 1) { throw std::runtime_error("KeePassHttp returned multiple matches, bailing out."); } if(vEntries.size() == 1) { sEntryId = vEntries[0].getUuid(); } // Update wallet passphrase in KeePass rpcSetLogin(sWalletPassphrase, sEntryId); }<|fim▁end|>
<|file_name|>noparse.rs<|end_file_name|><|fim▁begin|>macro_rules! noparse( ($name:ident, $re:expr) => ( #[test] fn $name() { let re = $re; match regex_new!(re) { Err(_) => {}, Ok(_) => panic!("Regex '{}' should cause a parse error.", re), } } ); ); noparse!(fail_double_repeat, "a**"); noparse!(fail_no_repeat_arg, "*"); noparse!(fail_incomplete_escape, "\\"); noparse!(fail_class_incomplete, "[A-"); noparse!(fail_class_not_closed, "[A"); noparse!(fail_class_no_begin, r"[\A]"); noparse!(fail_class_no_end, r"[\z]"); noparse!(fail_class_no_boundary, r"[\b]"); noparse!(fail_open_paren, "("); noparse!(fail_close_paren, ")"); noparse!(fail_invalid_range, "[a-Z]"); noparse!(fail_empty_capture_name, "(?P<>a)"); noparse!(fail_empty_capture_exp, "(?P<name>)"); noparse!(fail_bad_capture_name, "(?P<na-me>)"); noparse!(fail_bad_flag, "(?a)a"); noparse!(fail_empty_alt_before, "|a"); noparse!(fail_empty_alt_after, "a|"); noparse!(fail_too_big, "a{10000000}");<|fim▁hole|>noparse!(fail_unfinished_cap, "(?"); noparse!(fail_unfinished_escape, "\\"); noparse!(fail_octal_digit, r"\8"); noparse!(fail_hex_digit, r"\xG0"); noparse!(fail_hex_short, r"\xF"); noparse!(fail_hex_long_digits, r"\x{fffg}"); noparse!(fail_flag_bad, "(?a)"); noparse!(fail_flag_empty, "(?)"); noparse!(fail_double_neg, "(?-i-i)"); noparse!(fail_neg_empty, "(?i-)"); noparse!(fail_empty_group, "()"); noparse!(fail_dupe_named, "(?P<a>.)(?P<a>.)"); noparse!(fail_range_end_no_class, "[a-[:lower:]]"); noparse!(fail_range_end_no_begin, r"[a-\A]"); noparse!(fail_range_end_no_end, r"[a-\z]"); noparse!(fail_range_end_no_boundary, r"[a-\b]");<|fim▁end|>
noparse!(fail_counted_no_close, "a{1001");
<|file_name|>have_killed.go<|end_file_name|><|fim▁begin|>package fake_command_runner_matchers import ( "fmt" "os/exec" "github.com/cloudfoundry/gunk/command_runner/fake_command_runner"<|fim▁hole|> func HaveKilled(spec fake_command_runner.CommandSpec) *HaveKilledMatcher { return &HaveKilledMatcher{Spec: spec} } type HaveKilledMatcher struct { Spec fake_command_runner.CommandSpec killed []*exec.Cmd } func (m *HaveKilledMatcher) Match(actual interface{}) (bool, error) { runner, ok := actual.(*fake_command_runner.FakeCommandRunner) if !ok { return false, fmt.Errorf("Not a fake command runner: %#v.", actual) } m.killed = runner.KilledCommands() matched := false for _, cmd := range m.killed { if m.Spec.Matches(cmd) { matched = true break } } if matched { return true, nil } else { return false, nil } } func (m *HaveKilledMatcher) FailureMessage(actual interface{}) (message string) { return fmt.Sprintf("Expected to kill:%s\n\nActually killed:%s", prettySpec(m.Spec), prettyCommands(m.killed)) } func (m *HaveKilledMatcher) NegatedFailureMessage(actual interface{}) (message string) { return fmt.Sprintf("Expected to not kill the following commands:%s", prettySpec(m.Spec)) }<|fim▁end|>
)
<|file_name|>expand.rs<|end_file_name|><|fim▁begin|>use std::str; use memchr::memchr; use bytes::Captures; pub fn expand(caps: &Captures, mut replacement: &[u8], dst: &mut Vec<u8>) { while !replacement.is_empty() { match memchr(b'$', replacement) { None => break, Some(i) => { dst.extend(&replacement[..i]); replacement = &replacement[i..]; } } if replacement.get(1).map_or(false, |&b| b == b'$') {<|fim▁hole|> replacement = &replacement[2..]; continue; } debug_assert!(!replacement.is_empty()); let cap_ref = match find_cap_ref(replacement) { Some(cap_ref) => cap_ref, None => { dst.push(b'$'); replacement = &replacement[1..]; continue; } }; replacement = cap_ref.rest; match cap_ref.cap { Ref::Number(i) => dst.extend(caps.at(i).unwrap_or(b"")), Ref::Named(name) => dst.extend(caps.name(name).unwrap_or(b"")), } } dst.extend(replacement); } struct CaptureRef<'a> { rest: &'a [u8], cap: Ref<'a>, } enum Ref<'a> { Named(&'a str), Number(usize), } fn find_cap_ref(mut replacement: &[u8]) -> Option<CaptureRef> { if replacement.len() <= 1 || replacement[0] != b'$' { return None; } let mut brace = false; replacement = &replacement[1..]; if replacement[0] == b'{' { brace = true; replacement = &replacement[1..]; } let mut cap_end = 0; while replacement.get(cap_end).map_or(false, is_valid_cap_letter) { cap_end += 1; } if cap_end == 0 { return None; } // We just verified that the range 0..cap_end is valid ASCII, so it must // therefore be valid UTF-8. If we really cared, we could avoid this UTF-8 // check with either unsafe or by parsing the number straight from &[u8]. let cap = str::from_utf8(&replacement[..cap_end]) .ok().expect("valid UTF-8 capture name"); if brace { if !replacement.get(cap_end).map_or(false, |&b| b == b'}') { return None; } cap_end += 1; } Some(CaptureRef { rest: &replacement[cap_end..], cap: match cap.parse::<u32>() { Ok(i) => Ref::Number(i as usize), Err(_) => Ref::Named(cap), }, }) } fn is_valid_cap_letter(b: &u8) -> bool { match *b { b'0' ... b'9' | b'a' ... b'z' | b'A' ... b'Z' | b'_' => true, _ => false, } }<|fim▁end|>
dst.push(b'$');
<|file_name|>f64.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. //! Operations and constants for 64-bits floats (`f64` type) #![doc(primitive = "f64")] // FIXME: MIN_VALUE and MAX_VALUE literals are parsed as -inf and inf #14353 #![allow(type_overflow)] use intrinsics; use mem; use num::{FPNormal, FPCategory, FPZero, FPSubnormal, FPInfinite, FPNaN}; use num::Float; use option::Option; // FIXME(#5527): These constants should be deprecated once associated // constants are implemented in favour of referencing the respective // members of `Bounded` and `Float`. pub const RADIX: uint = 2u; pub const MANTISSA_DIGITS: uint = 53u; pub const DIGITS: uint = 15u; pub const EPSILON: f64 = 2.2204460492503131e-16_f64; /// Smallest finite f64 value pub const MIN_VALUE: f64 = -1.7976931348623157e+308_f64; /// Smallest positive, normalized f64 value pub const MIN_POS_VALUE: f64 = 2.2250738585072014e-308_f64; /// Largest finite f64 value pub const MAX_VALUE: f64 = 1.7976931348623157e+308_f64; pub const MIN_EXP: int = -1021; pub const MAX_EXP: int = 1024; pub const MIN_10_EXP: int = -307; pub const MAX_10_EXP: int = 308; pub const NAN: f64 = 0.0_f64/0.0_f64; pub const INFINITY: f64 = 1.0_f64/0.0_f64; pub const NEG_INFINITY: f64 = -1.0_f64/0.0_f64; /// Various useful constants. pub mod consts { // FIXME: replace with mathematical constants from cmath. // FIXME(#5527): These constants should be deprecated once associated // constants are implemented in favour of referencing the respective members // of `Float`. /// Archimedes' constant pub const PI: f64 = 3.14159265358979323846264338327950288_f64; /// pi * 2.0 pub const PI_2: f64 = 6.28318530717958647692528676655900576_f64; /// pi/2.0 pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64; /// pi/3.0 pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64; /// pi/4.0 pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64; /// pi/6.0 pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64; /// pi/8.0 pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64; /// 1.0/pi pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64; /// 2.0/pi pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64; /// 2.0/sqrt(pi) pub const FRAC_2_SQRTPI: f64 = 1.12837916709551257389615890312154517_f64; /// sqrt(2.0) pub const SQRT2: f64 = 1.41421356237309504880168872420969808_f64; /// 1.0/sqrt(2.0)<|fim▁hole|> /// log2(e) pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64; /// log10(e) pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64; /// ln(2.0) pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64; /// ln(10.0) pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64; } impl Float for f64 { #[inline] fn nan() -> f64 { NAN } #[inline] fn infinity() -> f64 { INFINITY } #[inline] fn neg_infinity() -> f64 { NEG_INFINITY } #[inline] fn neg_zero() -> f64 { -0.0 } /// Returns `true` if the number is NaN. #[inline] fn is_nan(self) -> bool { self != self } /// Returns `true` if the number is infinite. #[inline] fn is_infinite(self) -> bool { self == Float::infinity() || self == Float::neg_infinity() } /// Returns `true` if the number is neither infinite or NaN. #[inline] fn is_finite(self) -> bool { !(self.is_nan() || self.is_infinite()) } /// Returns `true` if the number is neither zero, infinite, subnormal or NaN. #[inline] fn is_normal(self) -> bool { self.classify() == FPNormal } /// Returns the floating point category of the number. If only one property /// is going to be tested, it is generally faster to use the specific /// predicate instead. fn classify(self) -> FPCategory { const EXP_MASK: u64 = 0x7ff0000000000000; const MAN_MASK: u64 = 0x000fffffffffffff; let bits: u64 = unsafe { mem::transmute(self) }; match (bits & MAN_MASK, bits & EXP_MASK) { (0, 0) => FPZero, (_, 0) => FPSubnormal, (0, EXP_MASK) => FPInfinite, (_, EXP_MASK) => FPNaN, _ => FPNormal, } } #[inline] fn mantissa_digits(_: Option<f64>) -> uint { MANTISSA_DIGITS } #[inline] fn digits(_: Option<f64>) -> uint { DIGITS } #[inline] fn epsilon() -> f64 { EPSILON } #[inline] fn min_exp(_: Option<f64>) -> int { MIN_EXP } #[inline] fn max_exp(_: Option<f64>) -> int { MAX_EXP } #[inline] fn min_10_exp(_: Option<f64>) -> int { MIN_10_EXP } #[inline] fn max_10_exp(_: Option<f64>) -> int { MAX_10_EXP } #[inline] fn min_pos_value(_: Option<f64>) -> f64 { MIN_POS_VALUE } /// Returns the mantissa, exponent and sign as integers. fn integer_decode(self) -> (u64, i16, i8) { let bits: u64 = unsafe { mem::transmute(self) }; let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 }; let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16; let mantissa = if exponent == 0 { (bits & 0xfffffffffffff) << 1 } else { (bits & 0xfffffffffffff) | 0x10000000000000 }; // Exponent bias + mantissa shift exponent -= 1023 + 52; (mantissa, exponent, sign) } /// Rounds towards minus infinity. #[inline] fn floor(self) -> f64 { unsafe { intrinsics::floorf64(self) } } /// Rounds towards plus infinity. #[inline] fn ceil(self) -> f64 { unsafe { intrinsics::ceilf64(self) } } /// Rounds to nearest integer. Rounds half-way cases away from zero. #[inline] fn round(self) -> f64 { unsafe { intrinsics::roundf64(self) } } /// Returns the integer part of the number (rounds towards zero). #[inline] fn trunc(self) -> f64 { unsafe { intrinsics::truncf64(self) } } /// The fractional part of the number, satisfying: /// /// ```rust /// let x = 1.65f64; /// assert!(x == x.trunc() + x.fract()) /// ``` #[inline] fn fract(self) -> f64 { self - self.trunc() } /// Fused multiply-add. Computes `(self * a) + b` with only one rounding /// error. This produces a more accurate result with better performance than /// a separate multiplication operation followed by an add. #[inline] fn mul_add(self, a: f64, b: f64) -> f64 { unsafe { intrinsics::fmaf64(self, a, b) } } /// Returns the reciprocal (multiplicative inverse) of the number. #[inline] fn recip(self) -> f64 { 1.0 / self } #[inline] fn powf(self, n: f64) -> f64 { unsafe { intrinsics::powf64(self, n) } } #[inline] fn powi(self, n: i32) -> f64 { unsafe { intrinsics::powif64(self, n) } } /// sqrt(2.0) #[inline] fn sqrt2() -> f64 { consts::SQRT2 } /// 1.0 / sqrt(2.0) #[inline] fn frac_1_sqrt2() -> f64 { consts::FRAC_1_SQRT2 } #[inline] fn sqrt(self) -> f64 { unsafe { intrinsics::sqrtf64(self) } } #[inline] fn rsqrt(self) -> f64 { self.sqrt().recip() } /// Archimedes' constant #[inline] fn pi() -> f64 { consts::PI } /// 2.0 * pi #[inline] fn two_pi() -> f64 { consts::PI_2 } /// pi / 2.0 #[inline] fn frac_pi_2() -> f64 { consts::FRAC_PI_2 } /// pi / 3.0 #[inline] fn frac_pi_3() -> f64 { consts::FRAC_PI_3 } /// pi / 4.0 #[inline] fn frac_pi_4() -> f64 { consts::FRAC_PI_4 } /// pi / 6.0 #[inline] fn frac_pi_6() -> f64 { consts::FRAC_PI_6 } /// pi / 8.0 #[inline] fn frac_pi_8() -> f64 { consts::FRAC_PI_8 } /// 1.0 / pi #[inline] fn frac_1_pi() -> f64 { consts::FRAC_1_PI } /// 2.0 / pi #[inline] fn frac_2_pi() -> f64 { consts::FRAC_2_PI } /// 2.0 / sqrt(pi) #[inline] fn frac_2_sqrtpi() -> f64 { consts::FRAC_2_SQRTPI } /// Euler's number #[inline] fn e() -> f64 { consts::E } /// log2(e) #[inline] fn log2_e() -> f64 { consts::LOG2_E } /// log10(e) #[inline] fn log10_e() -> f64 { consts::LOG10_E } /// ln(2.0) #[inline] fn ln_2() -> f64 { consts::LN_2 } /// ln(10.0) #[inline] fn ln_10() -> f64 { consts::LN_10 } /// Returns the exponential of the number. #[inline] fn exp(self) -> f64 { unsafe { intrinsics::expf64(self) } } /// Returns 2 raised to the power of the number. #[inline] fn exp2(self) -> f64 { unsafe { intrinsics::exp2f64(self) } } /// Returns the natural logarithm of the number. #[inline] fn ln(self) -> f64 { unsafe { intrinsics::logf64(self) } } /// Returns the logarithm of the number with respect to an arbitrary base. #[inline] fn log(self, base: f64) -> f64 { self.ln() / base.ln() } /// Returns the base 2 logarithm of the number. #[inline] fn log2(self) -> f64 { unsafe { intrinsics::log2f64(self) } } /// Returns the base 10 logarithm of the number. #[inline] fn log10(self) -> f64 { unsafe { intrinsics::log10f64(self) } } /// Converts to degrees, assuming the number is in radians. #[inline] fn to_degrees(self) -> f64 { self * (180.0f64 / Float::pi()) } /// Converts to radians, assuming the number is in degrees. #[inline] fn to_radians(self) -> f64 { let value: f64 = Float::pi(); self * (value / 180.0) } }<|fim▁end|>
pub const FRAC_1_SQRT2: f64 = 0.707106781186547524400844362104849039_f64; /// Euler's number pub const E: f64 = 2.71828182845904523536028747135266250_f64;
<|file_name|>metrics.py<|end_file_name|><|fim▁begin|># Copyright 2020 The FedLearner 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. # coding: utf-8 import atexit import datetime import json import os import threading import time import logging from functools import wraps import elasticsearch as es7 import elasticsearch6 as es6 import pytz from elasticsearch import helpers as helpers7 from elasticsearch6 import helpers as helpers6 from .common import Config, INDEX_NAME, INDEX_TYPE, get_es_template from . import fl_logging class Handler(object): def __init__(self, name): self._name = name def emit(self, name, value, tags=None, index_type='metrics'): """ Do whatever it takes to actually log the specified logging record. This version is intended to be implemented by subclasses and so raises a NotImplementedError. """ raise NotImplementedError('emit must be implemented ' 'by Handler subclasses') def get_name(self): return self._name def flush(self): pass class LoggingHandler(Handler): def __init__(self): super(LoggingHandler, self).__init__('logging') def emit(self, name, value, tags=None, index_type='metrics'): fl_logging.debug('[metrics] name[%s] value[%s] tags[%s]', name, value, str(tags)) class ElasticSearchHandler(Handler): """ Emit documents to ElasticSearch """ def __init__(self, ip, port): super(ElasticSearchHandler, self).__init__('elasticsearch') self._es = es7.Elasticsearch([ip], port=port, http_auth=(Config.ES_USERNAME, Config.ES_PASSWORD)) self._helpers = helpers7 self._version = int(self._es.info()['version']['number'].split('.')[0]) # ES 6.8 has differences in APIs compared to ES 7.6, # These `put_template`s is supposed to be done during deployment, here # is for old clients. if self._version == 6: self._es = es6.Elasticsearch([ip], port=port) self._helpers = helpers6 for index_type, index_name in INDEX_NAME.items(): if not self._es.indices.exists_template( '{}-template'.format(index_name) ): self._create_template_and_index(index_type) # suppress ES logger logging.getLogger('elasticsearch').setLevel(logging.CRITICAL) self._emit_batch = [] self._batch_size = Config.ES_BATCH_SIZE self._lock = threading.RLock() def emit(self, name, value, tags=None, index_type='metrics'): assert index_type in INDEX_TYPE if tags is None: tags = {} document = self._produce_document(name, value, tags, index_type) if not Config.METRICS_TO_STDOUT: # if filebeat not yet refurbished, directly emit to ES action = {'_index': INDEX_NAME[index_type], '_source': document} if self._version == 6: action['_type'] = '_doc' with self._lock: # emit when there are enough documents self._emit_batch.append(action) if len(self._emit_batch) >= self._batch_size: self.flush() else: # if filebeat refurbished, # print to std out and use filebeat to ship to ES document['index_type__'] = index_type print(json.dumps(document)) def flush(self): emit_batch = [] with self._lock: if self._emit_batch: emit_batch = self._emit_batch self._emit_batch = [] if emit_batch: fl_logging.info('Emitting %d documents to ES', len(emit_batch)) self._helpers.bulk(self._es, emit_batch) @staticmethod def _produce_document(name, value, tags, index_type): application_id = os.environ.get('APPLICATION_ID', '') if application_id: tags['application_id'] = str(application_id) if index_type == 'metrics': tags['process_time'] = datetime.datetime.now(tz=pytz.utc) \ .isoformat(timespec='microseconds') document = { "name": name, "value": value, "tags": tags } else: document = { "tags": tags } return document def _create_template_and_index(self, index_type): """ Args: index_type: ES index type. Creates a template and an index on ES. """ assert index_type in INDEX_TYPE self._es.indices.put_template( name='{}-template'.format(INDEX_NAME[index_type]), body=get_es_template(index_type, self._version) ) try: self._es.indices.create(index=INDEX_NAME[index_type]) return # index may have been created by other jobs except (es6.exceptions.RequestError, es7.exceptions.RequestError) as e: # if due to other reasons, re-raise exception if e.info['error']['type'] != 'resource_already_exists_exception': raise e class Metrics(object): def __init__(self): self.handlers = [] self._lock = threading.RLock() self.handler_initialized = False atexit.register(self.flush_handler) def init_handlers(self): with self._lock: if self.handler_initialized: return logging_handler = LoggingHandler() self.add_handler(logging_handler) es_host = os.environ.get('ES_HOST', '') es_port = os.environ.get('ES_PORT', '') if es_host and es_port: es_handler = ElasticSearchHandler(es_host, es_port) self.add_handler(es_handler) self.handler_initialized = True def add_handler(self, hdlr): """ Add the specified handler to this logger. """ with self._lock: if hdlr not in self.handlers: self.handlers.append(hdlr) def remove_handler(self, hdlr): """ Remove the specified handler from this logger. """ with self._lock: if hdlr in self.handlers: self.handlers.remove(hdlr) def emit(self, name, value, tags=None, index_type='metrics'): self.init_handlers() if not self.handlers or len(self.handlers) == 0: fl_logging.info('No handlers. Not emitting.') return for hdlr in self.handlers: try: hdlr.emit(name, value, tags, index_type) except Exception as e: # pylint: disable=broad-except fl_logging.warning('Handler [%s] emit failed. Error repr: [%s]', hdlr.get_name(), repr(e)) def flush_handler(self): for hdlr in self.handlers: try: hdlr.flush()<|fim▁hole|> except Exception as e: # pylint: disable=broad-except fl_logging.warning('Handler [%s] flush failed. ' 'Some metrics might not be emitted. ' 'Error repr: %s', hdlr.get_name(), repr(e)) _metrics_client = Metrics() def emit(name, value, tags=None, index_type='metrics'): _metrics_client.emit(name, value, tags, index_type) # Currently no actual differences among the methods below emit_counter = emit emit_store = emit emit_timer = emit def timer(func_name, tags=None): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): time_start = time.time() result = func(*args, **kwargs) time_end = time.time() time_spend = time_end - time_start emit(func_name, time_spend, tags) return result return wrapper return decorator<|fim▁end|>
<|file_name|>test_carbonara.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*- # # Copyright © 2014-2016 eNovance # # 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 datetime import functools import math import operator import fixtures import iso8601 import numpy import six from gnocchi import carbonara from gnocchi.tests import base def datetime64(*args): return numpy.datetime64(datetime.datetime(*args)) class TestBoundTimeSerie(base.BaseTestCase): def test_benchmark(self): self.useFixture(fixtures.Timeout(300, gentle=True)) carbonara.BoundTimeSerie.benchmark() @staticmethod def test_base(): carbonara.BoundTimeSerie.from_data( [datetime64(2014, 1, 1, 12, 0, 0), datetime64(2014, 1, 1, 12, 0, 4), datetime64(2014, 1, 1, 12, 0, 9)], [3, 5, 6]) def test_block_size(self): ts = carbonara.BoundTimeSerie.from_data( [datetime64(2014, 1, 1, 12, 0, 5), datetime64(2014, 1, 1, 12, 0, 9)], [5, 6], block_size=numpy.timedelta64(5, 's')) self.assertEqual(2, len(ts)) ts.set_values(numpy.array([(datetime64(2014, 1, 1, 12, 0, 10), 3), (datetime64(2014, 1, 1, 12, 0, 11), 4)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE)) self.assertEqual(2, len(ts)) def test_block_size_back_window(self): ts = carbonara.BoundTimeSerie.from_data( [datetime64(2014, 1, 1, 12, 0, 0), datetime64(2014, 1, 1, 12, 0, 4), datetime64(2014, 1, 1, 12, 0, 9)], [3, 5, 6], block_size=numpy.timedelta64(5, 's'), back_window=1) self.assertEqual(3, len(ts)) ts.set_values(numpy.array([(datetime64(2014, 1, 1, 12, 0, 10), 3), (datetime64(2014, 1, 1, 12, 0, 11), 4)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE)) self.assertEqual(3, len(ts)) def test_block_size_unordered(self): ts = carbonara.BoundTimeSerie.from_data( [datetime64(2014, 1, 1, 12, 0, 5), datetime64(2014, 1, 1, 12, 0, 9)], [5, 23], block_size=numpy.timedelta64(5, 's')) self.assertEqual(2, len(ts)) ts.set_values(numpy.array([(datetime64(2014, 1, 1, 12, 0, 11), 3), (datetime64(2014, 1, 1, 12, 0, 10), 4)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE)) self.assertEqual(2, len(ts)) def test_duplicate_timestamps(self): ts = carbonara.BoundTimeSerie.from_data( [datetime64(2014, 1, 1, 12, 0, 0), datetime64(2014, 1, 1, 12, 0, 9)], [10, 23]) self.assertEqual(2, len(ts)) self.assertEqual(10.0, ts[0][1]) self.assertEqual(23.0, ts[1][1]) ts.set_values(numpy.array([(datetime64(2014, 1, 1, 13, 0, 10), 3), (datetime64(2014, 1, 1, 13, 0, 11), 9), (datetime64(2014, 1, 1, 13, 0, 11), 8), (datetime64(2014, 1, 1, 13, 0, 11), 7), (datetime64(2014, 1, 1, 13, 0, 11), 4)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE)) self.assertEqual(4, len(ts)) self.assertEqual(10.0, ts[0][1]) self.assertEqual(23.0, ts[1][1]) self.assertEqual(3.0, ts[2][1]) self.assertEqual(9.0, ts[3][1]) class TestAggregatedTimeSerie(base.BaseTestCase): def test_benchmark(self): self.useFixture(fixtures.Timeout(300, gentle=True)) carbonara.AggregatedTimeSerie.benchmark() def test_fetch_basic(self): ts = carbonara.AggregatedTimeSerie.from_data( timestamps=[datetime64(2014, 1, 1, 12, 0, 0), datetime64(2014, 1, 1, 12, 0, 4), datetime64(2014, 1, 1, 12, 0, 9)], values=[3, 5, 6], aggregation=carbonara.Aggregation( "mean", numpy.timedelta64(1, 's'), None)) self.assertEqual( [(datetime64(2014, 1, 1, 12), 3), (datetime64(2014, 1, 1, 12, 0, 4), 5), (datetime64(2014, 1, 1, 12, 0, 9), 6)], list(ts.fetch())) self.assertEqual( [(datetime64(2014, 1, 1, 12, 0, 4), 5), (datetime64(2014, 1, 1, 12, 0, 9), 6)], list(ts.fetch( from_timestamp=datetime64(2014, 1, 1, 12, 0, 4)))) self.assertEqual( [(datetime64(2014, 1, 1, 12, 0, 4), 5), (datetime64(2014, 1, 1, 12, 0, 9), 6)], list(ts.fetch( from_timestamp=numpy.datetime64(iso8601.parse_date( "2014-01-01 12:00:04"))))) self.assertEqual( [(datetime64(2014, 1, 1, 12, 0, 4), 5), (datetime64(2014, 1, 1, 12, 0, 9), 6)], list(ts.fetch( from_timestamp=numpy.datetime64(iso8601.parse_date( "2014-01-01 13:00:04+01:00"))))) def test_before_epoch(self): ts = carbonara.TimeSerie.from_data( [datetime64(1950, 1, 1, 12), datetime64(2014, 1, 1, 12), datetime64(2014, 1, 1, 12)], [3, 5, 6]) self.assertRaises(carbonara.BeforeEpochError, ts.group_serie, 60) @staticmethod def _resample(ts, sampling, agg, derived=False): aggregation = carbonara.Aggregation(agg, sampling, None) grouped = ts.group_serie(sampling) if derived: grouped = grouped.derived() return carbonara.AggregatedTimeSerie.from_grouped_serie( grouped, aggregation) def test_derived_mean(self): ts = carbonara.TimeSerie.from_data( [datetime.datetime(2014, 1, 1, 12, 0, 0), datetime.datetime(2014, 1, 1, 12, 0, 4), datetime.datetime(2014, 1, 1, 12, 1, 2), datetime.datetime(2014, 1, 1, 12, 1, 14), datetime.datetime(2014, 1, 1, 12, 1, 24), datetime.datetime(2014, 1, 1, 12, 2, 4), datetime.datetime(2014, 1, 1, 12, 2, 35), datetime.datetime(2014, 1, 1, 12, 2, 42), datetime.datetime(2014, 1, 1, 12, 3, 2), datetime.datetime(2014, 1, 1, 12, 3, 22), # Counter reset datetime.datetime(2014, 1, 1, 12, 3, 42), datetime.datetime(2014, 1, 1, 12, 4, 9)], [50, 55, 65, 66, 70, 83, 92, 103, 105, 5, 7, 23]) ts = self._resample(ts, numpy.timedelta64(60, 's'), 'mean', derived=True) self.assertEqual(5, len(ts)) self.assertEqual( [(datetime64(2014, 1, 1, 12, 0, 0), 5), (datetime64(2014, 1, 1, 12, 1, 0), 5), (datetime64(2014, 1, 1, 12, 2, 0), 11), (datetime64(2014, 1, 1, 12, 3, 0), -32), (datetime64(2014, 1, 1, 12, 4, 0), 16)], list(ts.fetch( from_timestamp=datetime64(2014, 1, 1, 12)))) def test_derived_hole(self): ts = carbonara.TimeSerie.from_data( [datetime.datetime(2014, 1, 1, 12, 0, 0), datetime.datetime(2014, 1, 1, 12, 0, 4), datetime.datetime(2014, 1, 1, 12, 1, 2), datetime.datetime(2014, 1, 1, 12, 1, 14), datetime.datetime(2014, 1, 1, 12, 1, 24), datetime.datetime(2014, 1, 1, 12, 3, 2), datetime.datetime(2014, 1, 1, 12, 3, 22), datetime.datetime(2014, 1, 1, 12, 3, 42), datetime.datetime(2014, 1, 1, 12, 4, 9)], [50, 55, 65, 66, 70, 105, 108, 200, 202]) ts = self._resample(ts, numpy.timedelta64(60, 's'), 'last', derived=True) self.assertEqual(4, len(ts)) self.assertEqual( [(datetime64(2014, 1, 1, 12, 0, 0), 5), (datetime64(2014, 1, 1, 12, 1, 0), 4), (datetime64(2014, 1, 1, 12, 3, 0), 92), (datetime64(2014, 1, 1, 12, 4, 0), 2)], list(ts.fetch( from_timestamp=datetime64(2014, 1, 1, 12)))) def test_74_percentile_serialized(self): ts = carbonara.TimeSerie.from_data( [datetime64(2014, 1, 1, 12, 0, 0), datetime64(2014, 1, 1, 12, 0, 4), datetime64(2014, 1, 1, 12, 0, 9)], [3, 5, 6]) ts = self._resample(ts, numpy.timedelta64(60, 's'), '74pct') self.assertEqual(1, len(ts)) self.assertEqual(5.48, ts[datetime64(2014, 1, 1, 12, 0, 0)][1]) # Serialize and unserialize key = ts.get_split_key() o, s = ts.serialize(key) saved_ts = carbonara.AggregatedTimeSerie.unserialize( s, key, ts.aggregation) self.assertEqual(ts.aggregation, saved_ts.aggregation) ts = carbonara.TimeSerie.from_data( [datetime64(2014, 1, 1, 12, 0, 0), datetime64(2014, 1, 1, 12, 0, 4), datetime64(2014, 1, 1, 12, 0, 9)], [3, 5, 6]) ts = self._resample(ts, numpy.timedelta64(60, 's'), '74pct') saved_ts.merge(ts) self.assertEqual(1, len(ts)) self.assertEqual(5.48, ts[datetime64(2014, 1, 1, 12, 0, 0)][1]) def test_95_percentile(self): ts = carbonara.TimeSerie.from_data( [datetime64(2014, 1, 1, 12, 0, 0), datetime64(2014, 1, 1, 12, 0, 4), datetime64(2014, 1, 1, 12, 0, 9)], [3, 5, 6]) ts = self._resample(ts, numpy.timedelta64(60, 's'), '95pct') self.assertEqual(1, len(ts)) self.assertEqual(5.9000000000000004, ts[datetime64(2014, 1, 1, 12, 0, 0)][1]) def _do_test_aggregation(self, name, v1, v2, v3): # NOTE(gordc): test data must have a group of odd count to properly # test 50pct test case. ts = carbonara.TimeSerie.from_data( [datetime64(2014, 1, 1, 12, 0, 0), datetime64(2014, 1, 1, 12, 0, 10), datetime64(2014, 1, 1, 12, 0, 20), datetime64(2014, 1, 1, 12, 0, 30), datetime64(2014, 1, 1, 12, 0, 40), datetime64(2014, 1, 1, 12, 1, 0), datetime64(2014, 1, 1, 12, 1, 10), datetime64(2014, 1, 1, 12, 1, 20), datetime64(2014, 1, 1, 12, 1, 30), datetime64(2014, 1, 1, 12, 1, 40), datetime64(2014, 1, 1, 12, 1, 50), datetime64(2014, 1, 1, 12, 2, 0), datetime64(2014, 1, 1, 12, 2, 10)], [3, 5, 2, 3, 5, 8, 11, 22, 10, 42, 9, 4, 2]) ts = self._resample(ts, numpy.timedelta64(60, 's'), name) self.assertEqual(3, len(ts)) self.assertEqual(v1, ts[datetime64(2014, 1, 1, 12, 0, 0)][1]) self.assertEqual(v2, ts[datetime64(2014, 1, 1, 12, 1, 0)][1]) self.assertEqual(v3, ts[datetime64(2014, 1, 1, 12, 2, 0)][1]) def test_aggregation_first(self): self._do_test_aggregation('first', 3, 8, 4) def test_aggregation_last(self): self._do_test_aggregation('last', 5, 9, 2) def test_aggregation_count(self): self._do_test_aggregation('count', 5, 6, 2) def test_aggregation_sum(self): self._do_test_aggregation('sum', 18, 102, 6) def test_aggregation_mean(self): self._do_test_aggregation('mean', 3.6, 17, 3) def test_aggregation_median(self): self._do_test_aggregation('median', 3.0, 10.5, 3) def test_aggregation_50pct(self): self._do_test_aggregation('50pct', 3.0, 10.5, 3) def test_aggregation_56pct(self): self._do_test_aggregation('56pct', 3.4800000000000004, 10.8, 3.120000000000001) def test_aggregation_min(self): self._do_test_aggregation('min', 2, 8, 2) def test_aggregation_max(self): self._do_test_aggregation('max', 5, 42, 4) def test_aggregation_std(self): self._do_test_aggregation('std', 1.3416407864998738, 13.266499161421599, 1.4142135623730951) def test_aggregation_std_with_unique(self): ts = carbonara.TimeSerie.from_data( [datetime64(2014, 1, 1, 12, 0, 0)], [3]) ts = self._resample(ts, numpy.timedelta64(60, 's'), 'std') self.assertEqual(0, len(ts), ts.values) ts = carbonara.TimeSerie.from_data( [datetime64(2014, 1, 1, 12, 0, 0), datetime64(2014, 1, 1, 12, 0, 4), datetime64(2014, 1, 1, 12, 0, 9), datetime64(2014, 1, 1, 12, 1, 6)], [3, 6, 5, 9]) ts = self._resample(ts, numpy.timedelta64(60, 's'), "std") self.assertEqual(1, len(ts)) self.assertEqual(1.5275252316519465, ts[datetime64(2014, 1, 1, 12, 0, 0)][1]) def test_different_length_in_timestamps_and_data(self): self.assertRaises( ValueError, carbonara.AggregatedTimeSerie.from_data, carbonara.Aggregation('mean', numpy.timedelta64(3, 's'), None), [datetime64(2014, 1, 1, 12, 0, 0), datetime64(2014, 1, 1, 12, 0, 4), datetime64(2014, 1, 1, 12, 0, 9)], [3, 5]) def test_truncate(self): ts = carbonara.TimeSerie.from_data( [datetime64(2014, 1, 1, 12, 0, 0), datetime64(2014, 1, 1, 12, 0, 4), datetime64(2014, 1, 1, 12, 0, 9)], [3, 5, 6]) ts = self._resample(ts, numpy.timedelta64(1, 's'), 'mean') ts.truncate(datetime64(2014, 1, 1, 12, 0, 0)) self.assertEqual(2, len(ts)) self.assertEqual(5, ts[0][1]) self.assertEqual(6, ts[1][1]) def test_down_sampling(self): ts = carbonara.TimeSerie.from_data( [datetime64(2014, 1, 1, 12, 0, 0), datetime64(2014, 1, 1, 12, 0, 4), datetime64(2014, 1, 1, 12, 0, 9)], [3, 5, 7]) ts = self._resample(ts, numpy.timedelta64(300, 's'), 'mean') self.assertEqual(1, len(ts)) self.assertEqual(5, ts[datetime64(2014, 1, 1, 12, 0, 0)][1]) def test_down_sampling_and_truncate(self): ts = carbonara.TimeSerie.from_data( [datetime64(2014, 1, 1, 12, 0, 0), datetime64(2014, 1, 1, 12, 1, 4), datetime64(2014, 1, 1, 12, 1, 9), datetime64(2014, 1, 1, 12, 2, 12)], [3, 5, 7, 1]) ts = self._resample(ts, numpy.timedelta64(60, 's'), 'mean') ts.truncate(datetime64(2014, 1, 1, 12, 0, 59)) self.assertEqual(2, len(ts)) self.assertEqual(6, ts[datetime64(2014, 1, 1, 12, 1, 0)][1]) self.assertEqual(1, ts[datetime64(2014, 1, 1, 12, 2, 0)][1]) def test_down_sampling_and_truncate_and_method_max(self): ts = carbonara.TimeSerie.from_data( [datetime64(2014, 1, 1, 12, 0, 0), datetime64(2014, 1, 1, 12, 1, 4), datetime64(2014, 1, 1, 12, 1, 9), datetime64(2014, 1, 1, 12, 2, 12)], [3, 5, 70, 1]) ts = self._resample(ts, numpy.timedelta64(60, 's'), 'max') ts.truncate(datetime64(2014, 1, 1, 12, 0, 59)) self.assertEqual(2, len(ts)) self.assertEqual(70, ts[datetime64(2014, 1, 1, 12, 1, 0)][1]) self.assertEqual(1, ts[datetime64(2014, 1, 1, 12, 2, 0)][1]) @staticmethod def _resample_and_merge(ts, agg_dict): """Helper method that mimics _compute_splits_operations workflow.""" grouped = ts.group_serie(agg_dict['sampling']) existing = agg_dict.get('return') agg_dict['return'] = carbonara.AggregatedTimeSerie.from_grouped_serie( grouped, carbonara.Aggregation( agg_dict['agg'], agg_dict['sampling'], None)) if existing: existing.merge(agg_dict['return']) agg_dict['return'] = existing def test_fetch(self): ts = {'sampling': numpy.timedelta64(60, 's'), 'size': 10, 'agg': 'mean'} tsb = carbonara.BoundTimeSerie(block_size=ts['sampling']) tsb.set_values(numpy.array([ (datetime64(2014, 1, 1, 11, 46, 4), 4), (datetime64(2014, 1, 1, 11, 47, 34), 8), (datetime64(2014, 1, 1, 11, 50, 54), 50), (datetime64(2014, 1, 1, 11, 54, 45), 4), (datetime64(2014, 1, 1, 11, 56, 49), 4), (datetime64(2014, 1, 1, 11, 57, 22), 6), (datetime64(2014, 1, 1, 11, 58, 22), 5), (datetime64(2014, 1, 1, 12, 1, 4), 4), (datetime64(2014, 1, 1, 12, 1, 9), 7), (datetime64(2014, 1, 1, 12, 2, 1), 15), (datetime64(2014, 1, 1, 12, 2, 12), 1), (datetime64(2014, 1, 1, 12, 3, 0), 3), (datetime64(2014, 1, 1, 12, 4, 9), 7), (datetime64(2014, 1, 1, 12, 5, 1), 15), (datetime64(2014, 1, 1, 12, 5, 12), 1), (datetime64(2014, 1, 1, 12, 6, 0, 2), 3)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE), before_truncate_callback=functools.partial( self._resample_and_merge, agg_dict=ts)) tsb.set_values(numpy.array([(datetime64(2014, 1, 1, 12, 6), 5)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE), before_truncate_callback=functools.partial( self._resample_and_merge, agg_dict=ts)) self.assertEqual([ (numpy.datetime64('2014-01-01T11:46:00.000000000'), 4.0), (numpy.datetime64('2014-01-01T11:47:00.000000000'), 8.0), (numpy.datetime64('2014-01-01T11:50:00.000000000'), 50.0), (datetime64(2014, 1, 1, 11, 54), 4.0), (datetime64(2014, 1, 1, 11, 56), 4.0), (datetime64(2014, 1, 1, 11, 57), 6.0), (datetime64(2014, 1, 1, 11, 58), 5.0), (datetime64(2014, 1, 1, 12, 1), 5.5), (datetime64(2014, 1, 1, 12, 2), 8.0), (datetime64(2014, 1, 1, 12, 3), 3.0), (datetime64(2014, 1, 1, 12, 4), 7.0), (datetime64(2014, 1, 1, 12, 5), 8.0), (datetime64(2014, 1, 1, 12, 6), 4.0) ], list(ts['return'].fetch())) self.assertEqual([ (datetime64(2014, 1, 1, 12, 1), 5.5), (datetime64(2014, 1, 1, 12, 2), 8.0), (datetime64(2014, 1, 1, 12, 3), 3.0), (datetime64(2014, 1, 1, 12, 4), 7.0), (datetime64(2014, 1, 1, 12, 5), 8.0), (datetime64(2014, 1, 1, 12, 6), 4.0) ], list(ts['return'].fetch(datetime64(2014, 1, 1, 12, 0, 0)))) def test_fetch_agg_pct(self): ts = {'sampling': numpy.timedelta64(1, 's'), 'size': 3600 * 24, 'agg': '90pct'} tsb = carbonara.BoundTimeSerie(block_size=ts['sampling']) tsb.set_values(numpy.array([(datetime64(2014, 1, 1, 12, 0, 0), 3), (datetime64(2014, 1, 1, 12, 0, 0, 123), 4), (datetime64(2014, 1, 1, 12, 0, 2), 4)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE), before_truncate_callback=functools.partial( self._resample_and_merge, agg_dict=ts)) result = ts['return'].fetch(datetime64(2014, 1, 1, 12, 0, 0)) reference = [ (datetime64( 2014, 1, 1, 12, 0, 0 ), 3.9), (datetime64( 2014, 1, 1, 12, 0, 2 ), 4) ] self.assertEqual(len(reference), len(list(result))) for ref, res in zip(reference, result): self.assertEqual(ref[0], res[0]) # Rounding \o/ self.assertAlmostEqual(ref[1], res[1]) tsb.set_values(numpy.array([ (datetime64(2014, 1, 1, 12, 0, 2, 113), 110)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE), before_truncate_callback=functools.partial( self._resample_and_merge, agg_dict=ts)) result = ts['return'].fetch(datetime64(2014, 1, 1, 12, 0, 0)) reference = [ (datetime64( 2014, 1, 1, 12, 0, 0 ), 3.9), (datetime64( 2014, 1, 1, 12, 0, 2 ), 99.4) ] self.assertEqual(len(reference), len(list(result))) for ref, res in zip(reference, result): self.assertEqual(ref[0], res[0]) # Rounding \o/ self.assertAlmostEqual(ref[1], res[1]) def test_fetch_nano(self): ts = {'sampling': numpy.timedelta64(200, 'ms'), 'size': 10, 'agg': 'mean'} tsb = carbonara.BoundTimeSerie(block_size=ts['sampling']) tsb.set_values(numpy.array([ (datetime64(2014, 1, 1, 11, 46, 0, 200123), 4), (datetime64(2014, 1, 1, 11, 46, 0, 340000), 8), (datetime64(2014, 1, 1, 11, 47, 0, 323154), 50), (datetime64(2014, 1, 1, 11, 48, 0, 590903), 4), (datetime64(2014, 1, 1, 11, 48, 0, 903291), 4)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE), before_truncate_callback=functools.partial( self._resample_and_merge, agg_dict=ts)) tsb.set_values(numpy.array([ (datetime64(2014, 1, 1, 11, 48, 0, 821312), 5)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE), before_truncate_callback=functools.partial( self._resample_and_merge, agg_dict=ts)) self.assertEqual([ (datetime64(2014, 1, 1, 11, 46, 0, 200000), 6.0), (datetime64(2014, 1, 1, 11, 47, 0, 200000), 50.0), (datetime64(2014, 1, 1, 11, 48, 0, 400000), 4.0), (datetime64(2014, 1, 1, 11, 48, 0, 800000), 4.5) ], list(ts['return'].fetch())) self.assertEqual(numpy.timedelta64(200000000, 'ns'), ts['return'].aggregation.granularity) def test_fetch_agg_std(self): # NOTE (gordc): this is a good test to ensure we drop NaN entries # 2014-01-01 12:00:00 will appear if we don't dropna() ts = {'sampling': numpy.timedelta64(60, 's'), 'size': 60, 'agg': 'std'} tsb = carbonara.BoundTimeSerie(block_size=ts['sampling']) tsb.set_values(numpy.array([(datetime64(2014, 1, 1, 12, 0, 0), 3), (datetime64(2014, 1, 1, 12, 1, 4), 4), (datetime64(2014, 1, 1, 12, 1, 9), 7), (datetime64(2014, 1, 1, 12, 2, 1), 15), (datetime64(2014, 1, 1, 12, 2, 12), 1)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE), before_truncate_callback=functools.partial( self._resample_and_merge, agg_dict=ts)) self.assertEqual([ (datetime64(2014, 1, 1, 12, 1, 0), 2.1213203435596424), (datetime64(2014, 1, 1, 12, 2, 0), 9.8994949366116654), ], list(ts['return'].fetch(datetime64(2014, 1, 1, 12, 0, 0)))) tsb.set_values(numpy.array([(datetime64(2014, 1, 1, 12, 2, 13), 110)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE), before_truncate_callback=functools.partial( self._resample_and_merge, agg_dict=ts)) self.assertEqual([ (datetime64(2014, 1, 1, 12, 1, 0), 2.1213203435596424), (datetime64(2014, 1, 1, 12, 2, 0), 59.304300012730948), ], list(ts['return'].fetch(datetime64(2014, 1, 1, 12, 0, 0)))) def test_fetch_agg_max(self): ts = {'sampling': numpy.timedelta64(60, 's'), 'size': 60, 'agg': 'max'} tsb = carbonara.BoundTimeSerie(block_size=ts['sampling']) tsb.set_values(numpy.array([(datetime64(2014, 1, 1, 12, 0, 0), 3), (datetime64(2014, 1, 1, 12, 1, 4), 4), (datetime64(2014, 1, 1, 12, 1, 9), 7), (datetime64(2014, 1, 1, 12, 2, 1), 15), (datetime64(2014, 1, 1, 12, 2, 12), 1)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE), before_truncate_callback=functools.partial( self._resample_and_merge, agg_dict=ts)) self.assertEqual([ (datetime64(2014, 1, 1, 12, 0, 0), 3), (datetime64(2014, 1, 1, 12, 1, 0), 7), (datetime64(2014, 1, 1, 12, 2, 0), 15), ], list(ts['return'].fetch(datetime64(2014, 1, 1, 12, 0, 0)))) tsb.set_values(numpy.array([(datetime64(2014, 1, 1, 12, 2, 13), 110)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE), before_truncate_callback=functools.partial( self._resample_and_merge, agg_dict=ts)) self.assertEqual([ (datetime64(2014, 1, 1, 12, 0, 0), 3), (datetime64(2014, 1, 1, 12, 1, 0), 7), (datetime64(2014, 1, 1, 12, 2, 0), 110), ], list(ts['return'].fetch(datetime64(2014, 1, 1, 12, 0, 0)))) def test_serialize(self): ts = {'sampling': numpy.timedelta64(500, 'ms'), 'agg': 'mean'} tsb = carbonara.BoundTimeSerie(block_size=ts['sampling']) tsb.set_values(numpy.array([ (datetime64(2014, 1, 1, 12, 0, 0, 1234), 3), (datetime64(2014, 1, 1, 12, 0, 0, 321), 6), (datetime64(2014, 1, 1, 12, 1, 4, 234), 5), (datetime64(2014, 1, 1, 12, 1, 9, 32), 7), (datetime64(2014, 1, 1, 12, 2, 12, 532), 1)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE), before_truncate_callback=functools.partial( self._resample_and_merge, agg_dict=ts)) key = ts['return'].get_split_key() o, s = ts['return'].serialize(key) self.assertEqual(ts['return'], carbonara.AggregatedTimeSerie.unserialize( s, key, ts['return'].aggregation)) def test_no_truncation(self): ts = {'sampling': numpy.timedelta64(60, 's'), 'agg': 'mean'} tsb = carbonara.BoundTimeSerie() for i in six.moves.range(1, 11): tsb.set_values(numpy.array([ (datetime64(2014, 1, 1, 12, i, i), float(i))], dtype=carbonara.TIMESERIES_ARRAY_DTYPE), before_truncate_callback=functools.partial( self._resample_and_merge, agg_dict=ts)) tsb.set_values(numpy.array([ (datetime64(2014, 1, 1, 12, i, i + 1), float(i + 1))], dtype=carbonara.TIMESERIES_ARRAY_DTYPE), before_truncate_callback=functools.partial( self._resample_and_merge, agg_dict=ts)) self.assertEqual(i, len(list(ts['return'].fetch()))) def test_back_window(self): """Back window testing. Test the back window on an archive is not longer than the window we aggregate on. """ ts = {'sampling': numpy.timedelta64(1, 's'), 'size': 60, 'agg': 'mean'} tsb = carbonara.BoundTimeSerie(block_size=ts['sampling']) tsb.set_values(numpy.array([ (datetime64(2014, 1, 1, 12, 0, 1, 2300), 1), (datetime64(2014, 1, 1, 12, 0, 1, 4600), 2), (datetime64(2014, 1, 1, 12, 0, 2, 4500), 3), (datetime64(2014, 1, 1, 12, 0, 2, 7800), 4), (datetime64(2014, 1, 1, 12, 0, 3, 8), 2.5)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE), before_truncate_callback=functools.partial( self._resample_and_merge, agg_dict=ts)) self.assertEqual( [ (datetime64(2014, 1, 1, 12, 0, 1), 1.5), (datetime64(2014, 1, 1, 12, 0, 2), 3.5), (datetime64(2014, 1, 1, 12, 0, 3), 2.5), ], list(ts['return'].fetch())) def test_back_window_ignore(self): """Back window testing. Test the back window on an archive is not longer than the window we aggregate on. """ ts = {'sampling': numpy.timedelta64(1, 's'), 'size': 60, 'agg': 'mean'} tsb = carbonara.BoundTimeSerie(block_size=ts['sampling']) tsb.set_values(numpy.array([ (datetime64(2014, 1, 1, 12, 0, 1, 2300), 1), (datetime64(2014, 1, 1, 12, 0, 1, 4600), 2), (datetime64(2014, 1, 1, 12, 0, 2, 4500), 3), (datetime64(2014, 1, 1, 12, 0, 2, 7800), 4), (datetime64(2014, 1, 1, 12, 0, 3, 8), 2.5)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE), before_truncate_callback=functools.partial( self._resample_and_merge, agg_dict=ts)) self.assertEqual( [ (datetime64(2014, 1, 1, 12, 0, 1), 1.5), (datetime64(2014, 1, 1, 12, 0, 2), 3.5), (datetime64(2014, 1, 1, 12, 0, 3), 2.5), ], list(ts['return'].fetch())) tsb.set_values(numpy.array([ (datetime64(2014, 1, 1, 12, 0, 2, 99), 9)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE), before_truncate_callback=functools.partial( self._resample_and_merge, agg_dict=ts)) self.assertEqual( [ (datetime64(2014, 1, 1, 12, 0, 1), 1.5), (datetime64(2014, 1, 1, 12, 0, 2), 3.5), (datetime64(2014, 1, 1, 12, 0, 3), 2.5), ], list(ts['return'].fetch())) tsb.set_values(numpy.array([ (datetime64(2014, 1, 1, 12, 0, 2, 99), 9), (datetime64(2014, 1, 1, 12, 0, 3, 9), 4.5)], dtype=carbonara.TIMESERIES_ARRAY_DTYPE), before_truncate_callback=functools.partial( self._resample_and_merge, agg_dict=ts)) self.assertEqual( [ (datetime64(2014, 1, 1, 12, 0, 1), 1.5), (datetime64(2014, 1, 1, 12, 0, 2), 3.5), (datetime64(2014, 1, 1, 12, 0, 3), 3.5), ], list(ts['return'].fetch())) def test_split_key(self): self.assertEqual( numpy.datetime64("2014-10-07"), carbonara.SplitKey.from_timestamp_and_sampling( numpy.datetime64("2015-01-01T15:03"), numpy.timedelta64(3600, 's'))) self.assertEqual( numpy.datetime64("2014-12-31 18:00"), carbonara.SplitKey.from_timestamp_and_sampling( numpy.datetime64("2015-01-01 15:03:58"), numpy.timedelta64(58, 's'))) key = carbonara.SplitKey.from_timestamp_and_sampling( numpy.datetime64("2015-01-01 15:03"), numpy.timedelta64(3600, 's')) self.assertGreater(key, numpy.datetime64("1970")) self.assertGreaterEqual(key, numpy.datetime64("1970")) def test_split_key_cmp(self): dt1 = numpy.datetime64("2015-01-01T15:03") dt1_1 = numpy.datetime64("2015-01-01T15:03") dt2 = numpy.datetime64("2015-01-05T15:03") td = numpy.timedelta64(60, 's') td2 = numpy.timedelta64(300, 's') self.assertEqual( carbonara.SplitKey.from_timestamp_and_sampling(dt1, td), carbonara.SplitKey.from_timestamp_and_sampling(dt1, td)) self.assertEqual( carbonara.SplitKey.from_timestamp_and_sampling(dt1, td), carbonara.SplitKey.from_timestamp_and_sampling(dt1_1, td)) self.assertNotEqual( carbonara.SplitKey.from_timestamp_and_sampling(dt1, td), carbonara.SplitKey.from_timestamp_and_sampling(dt2, td)) self.assertNotEqual( carbonara.SplitKey.from_timestamp_and_sampling(dt1, td), carbonara.SplitKey.from_timestamp_and_sampling(dt1, td2)) self.assertLess( carbonara.SplitKey.from_timestamp_and_sampling(dt1, td), carbonara.SplitKey.from_timestamp_and_sampling(dt2, td)) self.assertLessEqual(<|fim▁hole|> carbonara.SplitKey.from_timestamp_and_sampling(dt2, td), carbonara.SplitKey.from_timestamp_and_sampling(dt1, td)) self.assertGreaterEqual( carbonara.SplitKey.from_timestamp_and_sampling(dt2, td), carbonara.SplitKey.from_timestamp_and_sampling(dt2, td)) def test_split_key_cmp_negative(self): dt1 = numpy.datetime64("2015-01-01T15:03") dt1_1 = numpy.datetime64("2015-01-01T15:03") dt2 = numpy.datetime64("2015-01-05T15:03") td = numpy.timedelta64(60, 's') td2 = numpy.timedelta64(300, 's') self.assertFalse( carbonara.SplitKey.from_timestamp_and_sampling(dt1, td) != carbonara.SplitKey.from_timestamp_and_sampling(dt1, td)) self.assertFalse( carbonara.SplitKey.from_timestamp_and_sampling(dt1, td) != carbonara.SplitKey.from_timestamp_and_sampling(dt1_1, td)) self.assertFalse( carbonara.SplitKey.from_timestamp_and_sampling(dt1, td) == carbonara.SplitKey.from_timestamp_and_sampling(dt2, td)) self.assertFalse( carbonara.SplitKey.from_timestamp_and_sampling(dt1, td) == carbonara.SplitKey.from_timestamp_and_sampling(dt2, td2)) self.assertRaises( TypeError, operator.le, carbonara.SplitKey.from_timestamp_and_sampling(dt1, td), carbonara.SplitKey.from_timestamp_and_sampling(dt2, td2)) self.assertRaises( TypeError, operator.ge, carbonara.SplitKey.from_timestamp_and_sampling(dt1, td), carbonara.SplitKey.from_timestamp_and_sampling(dt2, td2)) self.assertRaises( TypeError, operator.gt, carbonara.SplitKey.from_timestamp_and_sampling(dt1, td), carbonara.SplitKey.from_timestamp_and_sampling(dt2, td2)) self.assertRaises( TypeError, operator.lt, carbonara.SplitKey.from_timestamp_and_sampling(dt1, td), carbonara.SplitKey.from_timestamp_and_sampling(dt2, td2)) self.assertFalse( carbonara.SplitKey.from_timestamp_and_sampling(dt1, td) >= carbonara.SplitKey.from_timestamp_and_sampling(dt2, td)) self.assertFalse( carbonara.SplitKey.from_timestamp_and_sampling(dt1, td) > carbonara.SplitKey.from_timestamp_and_sampling(dt1, td)) self.assertFalse( carbonara.SplitKey.from_timestamp_and_sampling(dt2, td) <= carbonara.SplitKey.from_timestamp_and_sampling(dt1, td)) self.assertFalse( carbonara.SplitKey.from_timestamp_and_sampling(dt2, td) < carbonara.SplitKey.from_timestamp_and_sampling(dt2, td)) def test_split_key_next(self): self.assertEqual( numpy.datetime64("2015-03-06"), next(carbonara.SplitKey.from_timestamp_and_sampling( numpy.datetime64("2015-01-01 15:03"), numpy.timedelta64(3600, 's')))) self.assertEqual( numpy.datetime64("2015-08-03"), next(next(carbonara.SplitKey.from_timestamp_and_sampling( numpy.datetime64("2015-01-01T15:03"), numpy.timedelta64(3600, 's'))))) def test_split(self): sampling = numpy.timedelta64(5, 's') points = 100000 ts = carbonara.TimeSerie.from_data( timestamps=list(map(datetime.datetime.utcfromtimestamp, six.moves.range(points))), values=list(six.moves.range(points))) agg = self._resample(ts, sampling, 'mean') grouped_points = list(agg.split()) self.assertEqual( math.ceil((points / sampling.astype(float)) / carbonara.SplitKey.POINTS_PER_SPLIT), len(grouped_points)) self.assertEqual("0.0", str(carbonara.SplitKey(grouped_points[0][0], 0))) # 3600 × 5s = 5 hours self.assertEqual(datetime64(1970, 1, 1, 5), grouped_points[1][0]) self.assertEqual(carbonara.SplitKey.POINTS_PER_SPLIT, len(grouped_points[0][1])) def test_from_timeseries(self): sampling = numpy.timedelta64(5, 's') points = 100000 ts = carbonara.TimeSerie.from_data( timestamps=list(map(datetime.datetime.utcfromtimestamp, six.moves.range(points))), values=list(six.moves.range(points))) agg = self._resample(ts, sampling, 'mean') split = [t[1] for t in list(agg.split())] self.assertEqual(agg, carbonara.AggregatedTimeSerie.from_timeseries( split, aggregation=agg.aggregation)) def test_resample(self): ts = carbonara.TimeSerie.from_data( [datetime64(2014, 1, 1, 12, 0, 0), datetime64(2014, 1, 1, 12, 0, 4), datetime64(2014, 1, 1, 12, 0, 9), datetime64(2014, 1, 1, 12, 0, 11), datetime64(2014, 1, 1, 12, 0, 12)], [3, 5, 6, 2, 4]) agg_ts = self._resample(ts, numpy.timedelta64(5, 's'), 'mean') self.assertEqual(3, len(agg_ts)) agg_ts = agg_ts.resample(numpy.timedelta64(10, 's')) self.assertEqual(2, len(agg_ts)) self.assertEqual(5, agg_ts[0][1]) self.assertEqual(3, agg_ts[1][1]) def test_iter(self): ts = carbonara.TimeSerie.from_data( [datetime64(2014, 1, 1, 12, 0, 0), datetime64(2014, 1, 1, 12, 0, 11), datetime64(2014, 1, 1, 12, 0, 12)], [3, 5, 6]) self.assertEqual([ (numpy.datetime64('2014-01-01T12:00:00'), 3.), (numpy.datetime64('2014-01-01T12:00:11'), 5.), (numpy.datetime64('2014-01-01T12:00:12'), 6.), ], list(ts))<|fim▁end|>
carbonara.SplitKey.from_timestamp_and_sampling(dt1, td), carbonara.SplitKey.from_timestamp_and_sampling(dt1, td)) self.assertGreater(
<|file_name|>can-place-flowers.py<|end_file_name|><|fim▁begin|># Time: O(n) # Space: O(1) # Suppose you have a long flowerbed in which some of the plots are planted and some are not. # However, flowers cannot be planted in adjacent plots - they would compete for water # and both would die. # # Given a flowerbed (represented as an array containing 0 and 1, # where 0 means empty and 1 means not empty), and a number n, # return if n new flowers can be planted in it without violating the no-adjacent-flowers rule. # # Example 1: # Input: flowerbed = [1,0,0,0,1], n = 1 # Output: True # Example 2: # Input: flowerbed = [1,0,0,0,1], n = 2 # Output: False # Note: # The input array won't violate no-adjacent-flowers rule. # The input array size is in the range of [1, 20000].<|fim▁hole|> class Solution(object): def canPlaceFlowers(self, flowerbed, n): """ :type flowerbed: List[int] :type n: int :rtype: bool """ for i in xrange(len(flowerbed)): if flowerbed[i] == 0 and (i == 0 or flowerbed[i-1] == 0) and \ (i == len(flowerbed)-1 or flowerbed[i+1] == 0): flowerbed[i] = 1 n -= 1 if n <= 0: return True return False<|fim▁end|>
# n is a non-negative integer which won't exceed the input array size.