prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>tabs.py<|end_file_name|><|fim▁begin|># Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.utils.translation import ugettext_lazy as _ from horizon_lib import tabs class OverviewTab(tabs.Tab): name = _("Overview") slug = "overview"<|fim▁hole|> def get_context_data(self, request): return {"volume": self.tab_group.kwargs['volume']} class VolumeDetailTabs(tabs.TabGroup): slug = "volume_details" tabs = (OverviewTab,)<|fim▁end|>
template_name = ("project/volumes/volumes/_detail_overview.html")
<|file_name|>cobalt.py<|end_file_name|><|fim▁begin|>import logging import os import time from parsl.providers.error import ScaleOutFailed from parsl.channels import LocalChannel from parsl.launchers import AprunLauncher from parsl.providers.cobalt.template import template_string from parsl.providers.cluster_provider import ClusterProvider from parsl.utils import RepresentationMixin, wtime_to_minutes logger = logging.getLogger(__name__) translate_table = { 'QUEUED': 'PENDING', 'STARTING': 'PENDING', 'RUNNING': 'RUNNING', 'EXITING': 'COMPLETED', 'KILLING': 'COMPLETED' } class CobaltProvider(ClusterProvider, RepresentationMixin): """ Cobalt Execution Provider This provider uses cobalt to submit (qsub), obtain the status of (qstat), and cancel (qdel) jobs. Theo script to be used is created from a template file in this same module. Parameters ---------- channel : Channel Channel for accessing this provider. Possible channels include :class:`~parsl.channels.LocalChannel` (the default), :class:`~parsl.channels.SSHChannel`, or :class:`~parsl.channels.SSHInteractiveLoginChannel`. nodes_per_block : int Nodes to provision per block. min_blocks : int Minimum number of blocks to maintain. max_blocks : int Maximum number of blocks to maintain. walltime : str Walltime requested per block in HH:MM:SS. account : str Account that the job will be charged against. queue : str Torque queue to request blocks from. scheduler_options : str String to prepend to the submit script to the scheduler. worker_init : str Command to be run before starting a worker, such as 'module load Anaconda; source activate env'. launcher : Launcher Launcher for this provider. Possible launchers include :class:`~parsl.launchers.AprunLauncher` (the default) or, :class:`~parsl.launchers.SingleNodeLauncher` """ def __init__(self, channel=LocalChannel(), nodes_per_block=1, init_blocks=0, min_blocks=0, max_blocks=10, parallelism=1, walltime="00:10:00", account=None, queue=None, scheduler_options='', worker_init='', launcher=AprunLauncher(), cmd_timeout=10): label = 'cobalt' super().__init__(label, channel=channel, nodes_per_block=nodes_per_block, init_blocks=init_blocks, min_blocks=min_blocks, max_blocks=max_blocks, parallelism=parallelism, walltime=walltime, launcher=launcher, cmd_timeout=cmd_timeout) self.account = account self.queue = queue self.scheduler_options = scheduler_options self.worker_init = worker_init def _status(self): """ Internal: Do not call. Returns the status list for a list of job_ids Args: self Returns: [status...] : Status list of all jobs """ jobs_missing = list(self.resources.keys()) retcode, stdout, stderr = super().execute_wait("qstat -u $USER") # Execute_wait failed. Do no update. if retcode != 0: return for line in stdout.split('\n'): if line.startswith('='): continue parts = line.upper().split() if parts and parts[0] != 'JOBID': job_id = parts[0] if job_id not in self.resources: continue status = translate_table.get(parts[4], 'UNKNOWN') self.resources[job_id]['status'] = status jobs_missing.remove(job_id) # squeue does not report on jobs that are not running. So we are filling in the # blanks for missing jobs, we might lose some information about why the jobs failed. for missing_job in jobs_missing: if self.resources[missing_job]['status'] in ['RUNNING', 'KILLING', 'EXITING']: self.resources[missing_job]['status'] = translate_table['EXITING'] def submit(self, command, blocksize, tasks_per_node, job_name="parsl.auto"): """ Submits the command onto an Local Resource Manager job of blocksize parallel elements. Submit returns an ID that corresponds to the task that was just submitted. If tasks_per_node < 1 : ! This is illegal. tasks_per_node should be integer If tasks_per_node == 1: A single node is provisioned If tasks_per_node > 1 : tasks_per_node * blocksize number of nodes are provisioned. Args: - command :(String) Commandline invocation to be made on the remote side. - blocksize :(float) - tasks_per_node (int) : command invocations to be launched per node Kwargs: - job_name (String): Name for job, must be unique Returns: - None: At capacity, cannot provision more - job_id: (string) Identifier for the job """ if self.provisioned_blocks >= self.max_blocks: logger.warn("[%s] at capacity, cannot add more blocks now", self.label) return None # Note: Fix this later to avoid confusing behavior. # We should always allocate blocks in integer counts of node_granularity if blocksize < self.nodes_per_block: blocksize = self.nodes_per_block account_opt = '-A {}'.format(self.account) if self.account is not None else '' job_name = "parsl.{0}.{1}".format(job_name, time.time()) script_path = "{0}/{1}.submit".format(self.script_dir, job_name) script_path = os.path.abspath(script_path) job_config = {} job_config["scheduler_options"] = self.scheduler_options job_config["worker_init"] = self.worker_init logger.debug("Requesting blocksize:%s nodes_per_block:%s tasks_per_node:%s", blocksize, self.nodes_per_block, tasks_per_node) # Wrap the command job_config["user_script"] = self.launcher(command, tasks_per_node, self.nodes_per_block) queue_opt = '-q {}'.format(self.queue) if self.queue is not None else '' logger.debug("Writing submit script") self._write_submit_script(template_string, script_path, job_name, job_config) channel_script_path = self.channel.push_file(script_path, self.channel.script_dir) <|fim▁hole|> self.nodes_per_block, queue_opt, wtime_to_minutes(self.walltime), account_opt, channel_script_path) logger.debug("Executing {}".format(command)) retcode, stdout, stderr = super().execute_wait(command) # TODO : FIX this block if retcode != 0: logger.error("Failed command: {0}".format(command)) logger.error("Launch failed stdout:\n{0} \nstderr:{1}\n".format(stdout, stderr)) logger.debug("Retcode:%s STDOUT:%s STDERR:%s", retcode, stdout.strip(), stderr.strip()) job_id = None if retcode == 0: # We should be getting only one line back job_id = stdout.strip() self.resources[job_id] = {'job_id': job_id, 'status': 'PENDING', 'blocksize': blocksize} else: logger.error("Submission of command to scale_out failed: {0}".format(stderr)) raise (ScaleOutFailed(self.__class__, "Request to submit job to local scheduler failed")) logger.debug("Returning job id : {0}".format(job_id)) return job_id def cancel(self, job_ids): """ Cancels the jobs specified by a list of job ids Args: job_ids : [<job_id> ...] Returns : [True/False...] : If the cancel operation fails the entire list will be False. """ job_id_list = ' '.join(job_ids) retcode, stdout, stderr = super().execute_wait("qdel {0}".format(job_id_list)) rets = None if retcode == 0: for jid in job_ids: self.resources[jid]['status'] = translate_table['KILLING'] # Setting state to cancelled rets = [True for i in job_ids] else: rets = [False for i in job_ids] return rets<|fim▁end|>
command = 'qsub -n {0} {1} -t {2} {3} {4}'.format(
<|file_name|>RemoveLayerTask.ts<|end_file_name|><|fim▁begin|>/** * Copyright © 2021 Rémi Pace. * This file is part of Abc-Map. * * Abc-Map is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * Abc-Map 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General * Public License along with Abc-Map. If not, see <https://www.gnu.org/licenses/>. */ import { Task } from '../../Task'; import { MapWrapper } from '../../../geo/map/MapWrapper'; import { LayerWrapper } from '../../../geo/layers/LayerWrapper'; export class RemoveLayerTask extends Task { constructor(private map: MapWrapper, private layer: LayerWrapper) { super(); } <|fim▁hole|> } public async redo(): Promise<void> { this.map.removeLayer(this.layer); // We activate the last layer const layers = this.map.getLayers(); if (layers.length) { this.map.setActiveLayer(layers[layers.length - 1]); } } }<|fim▁end|>
public async undo(): Promise<void> { this.map.addLayer(this.layer); this.map.setActiveLayer(this.layer);
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from HardwareInterface import *<|fim▁hole|>from DataInterface import *<|fim▁end|>
from CameraInterface import * #from ProtocolRunner import *
<|file_name|>mapa.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # TODO: PORASQUI: BUG: Cerrar la ventana no detiene el GMapCatcher y se queda # como un proceso de fondo en espera bloqueante... Ni atiende al Ctrl+C # siquiera. import sys, os.path dirfichero = os.path.realpath(os.path.dirname(__file__)) if os.path.realpath(os.path.curdir) == dirfichero: os.chdir("..") if ("utils" in os.listdir(os.path.curdir) and os.path.abspath(os.path.curdir) not in sys.path): sys.path.insert(0, ".") from utils.googlemaps import GoogleMaps, GoogleMapsError try: # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX # raise ImportError # XXX: Solo para probar... BORRAR DESPUÉS # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX import osmgpsmap # Third dependency. No está en el árbol local. from utils.mapviewer import DummyLayer, imdir OSMGPSMAP = True except ImportError, msg: OSMGPSMAP = False os.chdir(os.path.abspath( os.path.join(dirfichero, "..", "utils", "gmapcatcher"))) import maps as gmc os.chdir(os.path.join(dirfichero, "..")) import gtk APIFILENAME = "gg_api_key.txt" class Mapa(): def __init__(self, apifile = None): if not apifile: mydir = os.path.dirname(os.path.abspath(__file__)) apifile = os.path.join(mydir, APIFILENAME) fapi = open(apifile) self.__ggapi = fapi.read() fapi.close() self.ggmap = GoogleMaps(self.__ggapi) self.init_mapa() def init_mapa(self): if OSMGPSMAP: self.osm = osmgpsmap.GpsMap() self.osm.layer_add(osmgpsmap.GpsMapOsd(show_dpad = True, show_zoom = True)) self.osm.layer_add( DummyLayer()) self.osm.connect('button_release_event', self.map_clicked) self.osm.set_zoom(13) # Zoom por defecto else: logging_path = conf_path = None # Es la conf. por defecto. Ver # utils/gmapatcher/map.py para más detalles. gmc.mapLogging.init_logging(logging_path) gmc.log.info("Starting %s version %s." % (gmc.NAME, gmc.VERSION)) self.gmcw = gmc.MainWindow(config_path = conf_path) self.gmcw.do_zoom(4) # Zoom por defecto. # TODO: PORASQUI: Hacer un traslado de escala entre el zoom de # GMC que va -creo- desde -2 (cerca) a más de 10 (lejos) al de # OSM, que va al contrario y 13 es cerca. Ver las "constantes" # definidas en cada caso (MAX_ZOOM_no_sé_qué en GMC). self.osm = self.gmcw.container def map_clicked(self, osm, event): if OSMGPSMAP: lat, lon = self.osm.get_event_location(event).get_degrees() else: lat, lon = 0, 0 # PORASQUI if event.button == 1: #self.latlon_entry.set_text( # 'Map Centre: latitude %s longitude %s' % ( # self.osm.props.latitude, # self.osm.props.longitude # ) #) pass elif event.button == 2: if OSMGPSMAP: self.osm.gps_add(lat, lon, heading = osmgpsmap.INVALID); else: pass # PORASQUI elif event.button == 3: if OSMGPSMAP: pb = gtk.gdk.pixbuf_new_from_file_at_size( os.path.join(imdir, "poi.png"), 24,24) self.osm.image_add(lat,lon,pb) else: pass # PORASQUI def centrar_mapa(self, lat, lon, zoom = None, track = True, flag = False): """ @param track Indica si se debe marcar el punto con un círculo y el "track" de recorrido. @param flag Indica si se debe marcar con una bandera el punto. """ if lat == None: raise ValueError, "Mapa.centrar_mapa -> Latitud incorrecta" if lon == None: raise ValueError, "Mapa.centrar_mapa -> Longitud incorrecta" if zoom is None: if OSMGPSMAP: self.osm.set_center(lat, lon) else: self.gmcw.confirm_clicked(None, None, lat, lon) else: if OSMGPSMAP: self.osm.set_center_and_zoom(lat, lon, zoom) else: self.gmcw.confirm_clicked(None, None, lat, lon) self.gmcw.do_zoom(zoom) if track: if OSMGPSMAP: self.osm.gps_add(lat, lon, heading = osmgpsmap.INVALID); else: self.gmcw.confirm_clicked(None, None, lat, lon) # PORASQUI: No support for the moment... if flag: if OSMGPSMAP: pb = gtk.gdk.pixbuf_new_from_file_at_size( os.path.join(imdir, "poi.png"), 24, 24) self.osm.image_add(lat, lon, pb) else: self.gmcw.confirm_clicked(None, None, lat, lon) # PORASQUI: No support for the moment... def put_mapa(self, container): #m = self.wids['mapa_container'] m = container m.add(self.osm) m.show_all() if not OSMGPSMAP: # Hay que ocultar algunas cosillas... for w in (self.gmcw.export_panel, self.gmcw.top_panel, self.gmcw.status_bar): try: w.set_visible(False) except AttributeError: w.set_property("visible", False) @property def zoom(self): """Nivel actual de zoom en el mapa.""" if OSMGPSMAP: return self.osm.props.zoom else: return self.gmcw.get_zoom() def get_latlon(self, direccion): """ Devuelve la latitud y longitud como flotantes correspondiente a la dirección recibida. Si no se encuentra en Google Maps, devuelve (None, None). """ try: res = self.ggmap.address_to_latlng(direccion) except GoogleMapsError: res = (None, None) return res def test(): w = gtk.Window() m = Mapa()<|fim▁hole|> #w.show_all() w.connect("destroy", lambda *a, **kw: gtk.main_quit()) gtk.main() if __name__ == "__main__": test()<|fim▁end|>
m.put_mapa(w)
<|file_name|>remote-client.py<|end_file_name|><|fim▁begin|>from code import InteractiveConsole import sys try: import websocket except: print('Please install websocket_client') raise class InteractiveRemoteConsole(InteractiveConsole): def __init__(self, uri=None): if uri is None: uri = 'ws://localhost:44445/' InteractiveConsole.__init__(self, None, "<remoteconsole>") self.websocket = websocket.create_connection(uri) self.websocket.settimeout(5) def interact(self, banner=None, exitmsg=None): if banner is None: self.write("Remote Python to Minecraft\n") elif banner: self.write("%s\n" % str(banner)) self.recv() while 1: try: try: line = self.raw_input() except EOFError: self.write("\n") break else: self.push(line) self.recv() except KeyboardInterrupt: self.write("\nKeyboardInterrupt\n") break self.websocket.close() if exitmsg is None: self.write('now exiting %s...\n' % self.__class__.__name__) elif exitmsg != '': self.write('%s\n' % exitmsg) def recv(self, supress_prompt=False): result = None while result is None or (not result.endswith('>>> ') and not result.endswith('... ')): result = self.websocket.recv() if not supress_prompt or (not result.endswith('>>> ') and not result.endswith('... ')): print(result, end = '') def push(self, line): self.websocket.send(line) def interact(uri=None, readfunc=None, banner=None, exitmsg=None): console = InteractiveRemoteConsole(uri) if readfunc is not None: console.raw_input = readfunc else: try: import readline except ImportError:<|fim▁hole|>if __name__ == '__main__': if len(sys.argv) > 1: uri = None if len(sys.argv) <= 2 else sys.argv[2] source = sys.argv[1] console = InteractiveRemoteConsole(uri) with open(source, 'r') as sourcefile: # Wait for initial prompt console.recv(supress_prompt=True) # Send lines for line in sourcefile: line = line.rstrip() console.push(line) console.recv(supress_prompt=True) # Add final new lines console.push("") console.recv(supress_prompt=True) console.push("") console.recv(supress_prompt=True) else: interact()<|fim▁end|>
pass console.interact(banner, exitmsg)
<|file_name|>translate.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import codecs import csv import fnmatch import inspect import locale import os import openerp.sql_db as sql_db import re import logging import tarfile import tempfile import threading from babel.messages import extract from collections import defaultdict from datetime import datetime from lxml import etree from os.path import join from xml.sax.saxutils import escape import config import misc from misc import SKIPPED_ELEMENT_TYPES import osutil import openerp from openerp import SUPERUSER_ID _logger = logging.getLogger(__name__) # used to notify web client that these translations should be loaded in the UI WEB_TRANSLATION_COMMENT = "openerp-web" SKIPPED_ELEMENTS = ('script', 'style') _LOCALE2WIN32 = { 'af_ZA': 'Afrikaans_South Africa', 'sq_AL': 'Albanian_Albania', 'ar_SA': 'Arabic_Saudi Arabia', 'eu_ES': 'Basque_Spain', 'be_BY': 'Belarusian_Belarus', 'bs_BA': 'Bosnian_Bosnia and Herzegovina', 'bg_BG': 'Bulgarian_Bulgaria', 'ca_ES': 'Catalan_Spain', 'hr_HR': 'Croatian_Croatia', 'zh_CN': 'Chinese_China', 'zh_TW': 'Chinese_Taiwan', 'cs_CZ': 'Czech_Czech Republic', 'da_DK': 'Danish_Denmark', 'nl_NL': 'Dutch_Netherlands', 'et_EE': 'Estonian_Estonia', 'fa_IR': 'Farsi_Iran', 'ph_PH': 'Filipino_Philippines', 'fi_FI': 'Finnish_Finland', 'fr_FR': 'French_France', 'fr_BE': 'French_France', 'fr_CH': 'French_France', 'fr_CA': 'French_France', 'ga': 'Scottish Gaelic', 'gl_ES': 'Galician_Spain', 'ka_GE': 'Georgian_Georgia', 'de_DE': 'German_Germany', 'el_GR': 'Greek_Greece', 'gu': 'Gujarati_India', 'he_IL': 'Hebrew_Israel', 'hi_IN': 'Hindi', 'hu': 'Hungarian_Hungary', 'is_IS': 'Icelandic_Iceland', 'id_ID': 'Indonesian_indonesia', 'it_IT': 'Italian_Italy', 'ja_JP': 'Japanese_Japan', 'kn_IN': 'Kannada', 'km_KH': 'Khmer', 'ko_KR': 'Korean_Korea', 'lo_LA': 'Lao_Laos', 'lt_LT': 'Lithuanian_Lithuania', 'lat': 'Latvian_Latvia', 'ml_IN': 'Malayalam_India', 'mi_NZ': 'Maori', 'mn': 'Cyrillic_Mongolian', 'no_NO': 'Norwegian_Norway', 'nn_NO': 'Norwegian-Nynorsk_Norway', 'pl': 'Polish_Poland', 'pt_PT': 'Portuguese_Portugal', 'pt_BR': 'Portuguese_Brazil', 'ro_RO': 'Romanian_Romania', 'ru_RU': 'Russian_Russia', 'sr_CS': 'Serbian (Cyrillic)_Serbia and Montenegro', 'sk_SK': 'Slovak_Slovakia', 'sl_SI': 'Slovenian_Slovenia', #should find more specific locales for spanish countries, #but better than nothing 'es_AR': 'Spanish_Spain', 'es_BO': 'Spanish_Spain', 'es_CL': 'Spanish_Spain', 'es_CO': 'Spanish_Spain', 'es_CR': 'Spanish_Spain', 'es_DO': 'Spanish_Spain', 'es_EC': 'Spanish_Spain', 'es_ES': 'Spanish_Spain', 'es_GT': 'Spanish_Spain', 'es_HN': 'Spanish_Spain', 'es_MX': 'Spanish_Spain', 'es_NI': 'Spanish_Spain', 'es_PA': 'Spanish_Spain', 'es_PE': 'Spanish_Spain', 'es_PR': 'Spanish_Spain', 'es_PY': 'Spanish_Spain', 'es_SV': 'Spanish_Spain', 'es_UY': 'Spanish_Spain', 'es_VE': 'Spanish_Spain', 'sv_SE': 'Swedish_Sweden', 'ta_IN': 'English_Australia', 'th_TH': 'Thai_Thailand', 'tr_TR': 'Turkish_Turkey', 'uk_UA': 'Ukrainian_Ukraine', 'vi_VN': 'Vietnamese_Viet Nam', 'tlh_TLH': 'Klingon', } # These are not all english small words, just those that could potentially be isolated within views ENGLISH_SMALL_WORDS = set("as at by do go if in me no of ok on or to up us we".split()) class UNIX_LINE_TERMINATOR(csv.excel): lineterminator = '\n' csv.register_dialect("UNIX", UNIX_LINE_TERMINATOR) # # Helper functions for translating fields # def encode(s): if isinstance(s, unicode): return s.encode('utf8') return s # which elements are translated inline TRANSLATED_ELEMENTS = { 'abbr', 'b', 'bdi', 'bdo', 'br', 'cite', 'code', 'data', 'del', 'dfn', 'em', 'font', 'i', 'ins', 'kbd', 'keygen', 'mark', 'math', 'meter', 'output', 'progress', 'q', 'ruby', 's', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'time', 'u', 'var', 'wbr', 'text', } # which attributes must be translated TRANSLATED_ATTRS = { 'string', 'help', 'sum', 'avg', 'confirm', 'placeholder', 'alt', 'title', } avoid_pattern = re.compile(r"[\s\n]*<!DOCTYPE", re.IGNORECASE) class XMLTranslator(object): """ A sequence of serialized XML/HTML items, with some of them to translate (todo) and others already translated (done). The purpose of this object is to simplify the handling of phrasing elements (like <b>) that must be translated together with their surrounding text. For instance, the content of the "div" element below will be translated as a whole (without surrounding spaces): <div> Lorem ipsum dolor sit amet, consectetur adipiscing elit, <b>sed</b> do eiusmod tempor incididunt ut labore et dolore magna aliqua. <span class="more">Ut enim ad minim veniam, <em>quis nostrud exercitation</em> ullamco laboris nisi ut aliquip ex ea commodo consequat.</span> </div> """ def __init__(self, callback, method, parser=None): self.callback = callback # callback function to translate terms self.method = method # serialization method ('xml' or 'html') self.parser = parser # parser for validating translations self._done = [] # translated strings self._todo = [] # todo strings that come after _done self.needs_trans = False # whether todo needs translation def todo(self, text, needs_trans=True): self._todo.append(text) if needs_trans and text.strip(): self.needs_trans = True def all_todo(self): return not self._done def get_todo(self): return "".join(self._todo) def flush(self): if self._todo: todo = "".join(self._todo) done = self.process_text(todo) if self.needs_trans else todo self._done.append(done) del self._todo[:] self.needs_trans = False def done(self, text): self.flush() self._done.append(text) def get_done(self): """ Complete the translations and return the result. """ self.flush() return "".join(self._done) def process_text(self, text): """ Translate text.strip(), but keep the surrounding spaces from text. """ term = text.strip() trans = term and self.callback(term) if trans: try: # parse the translation to validate it etree.fromstring("<div>%s</div>" % encode(trans), parser=self.parser) except etree.ParseError: # fallback: escape the translation trans = escape(trans) text = text.replace(term, trans) return text def process_attr(self, attr): """ Translate the given node attribute value. """ term = attr.strip() trans = term and self.callback(term) return attr.replace(term, trans) if trans else attr def process(self, node): """ Process the given xml `node`: collect `todo` and `done` items. """ if ( isinstance(node, SKIPPED_ELEMENT_TYPES) or node.tag in SKIPPED_ELEMENTS or node.get("t-translation", "").strip() == "off" or node.tag == "attribute" and node.get("name") not in TRANSLATED_ATTRS ): # do not translate the contents of the node tail, node.tail = node.tail, None self.done(etree.tostring(node, method=self.method)) self.todo(escape(tail or "")) return # process children nodes locally in child_trans child_trans = XMLTranslator(self.callback, self.method, parser=self.parser) if node.text: if avoid_pattern.match(node.text): child_trans.done(escape(node.text)) # do not translate <!DOCTYPE... else: child_trans.todo(escape(node.text)) for child in node: child_trans.process(child) if (child_trans.all_todo() and node.tag in TRANSLATED_ELEMENTS and not any(attr.startswith("t-") for attr in node.attrib)): # serialize the node element as todo self.todo(self.serialize(node.tag, node.attrib, child_trans.get_todo()), child_trans.needs_trans) else: # complete translations and serialize result as done for attr in TRANSLATED_ATTRS: if node.get(attr): node.set(attr, self.process_attr(node.get(attr))) self.done(self.serialize(node.tag, node.attrib, child_trans.get_done())) # add node tail as todo self.todo(escape(node.tail or "")) def serialize(self, tag, attrib, content): """ Return a serialized element with the given `tag`, attributes `attrib`, and already-serialized `content`. """ if content: elem = etree.tostring(etree.Element(tag, attrib), method='xml') assert elem.endswith("/>") return "%s>%s</%s>" % (elem[:-2], content, tag) else: return etree.tostring(etree.Element(tag, attrib), method=self.method) def xml_translate(callback, value): """ Translate an XML value (string), using `callback` for translating text appearing in `value`. """ if not value: return value trans = XMLTranslator(callback, 'xml') try: root = etree.fromstring(encode(value)) trans.process(root) return trans.get_done() except etree.ParseError: # fallback for translated terms: use an HTML parser and wrap the term wrapped = "<div>%s</div>" % encode(value) root = etree.fromstring(wrapped, etree.HTMLParser(encoding='utf-8')) trans.process(root[0][0]) # html > body > div return trans.get_done()[5:-6] # remove tags <div> and </div> def html_translate(callback, value): """ Translate an HTML value (string), using `callback` for translating text appearing in `value`. """ if not value: return value parser = etree.HTMLParser(encoding='utf-8') trans = XMLTranslator(callback, 'html', parser) wrapped = "<div>%s</div>" % encode(value) root = etree.fromstring(wrapped, parser) trans.process(root[0][0]) # html > body > div return trans.get_done()[5:-6] # remove tags <div> and </div> # # Warning: better use self.pool.get('ir.translation')._get_source if you can # def translate(cr, name, source_type, lang, source=None): if source and name: cr.execute('select value from ir_translation where lang=%s and type=%s and name=%s and src=%s and md5(src)=md5(%s)', (lang, source_type, str(name), source, source)) elif name: cr.execute('select value from ir_translation where lang=%s and type=%s and name=%s', (lang, source_type, str(name))) elif source: cr.execute('select value from ir_translation where lang=%s and type=%s and src=%s and md5(src)=md5(%s)', (lang, source_type, source, source)) res_trans = cr.fetchone() res = res_trans and res_trans[0] or False return res class GettextAlias(object): def _get_db(self): # find current DB based on thread/worker db name (see netsvc) db_name = getattr(threading.currentThread(), 'dbname', None) if db_name: return sql_db.db_connect(db_name) def _get_cr(self, frame, allow_create=True): # try, in order: cr, cursor, self.env.cr, self.cr, # request.env.cr if 'cr' in frame.f_locals: return frame.f_locals['cr'], False if 'cursor' in frame.f_locals: return frame.f_locals['cursor'], False s = frame.f_locals.get('self') if hasattr(s, 'env'): return s.env.cr, False if hasattr(s, 'cr'): return s.cr, False try: from openerp.http import request return request.env.cr, False except RuntimeError: pass if allow_create: # create a new cursor db = self._get_db() if db is not None: return db.cursor(), True return None, False def _get_uid(self, frame): # try, in order: uid, user, self.env.uid if 'uid' in frame.f_locals: return frame.f_locals['uid'] if 'user' in frame.f_locals: return int(frame.f_locals['user']) # user may be a record s = frame.f_locals.get('self') return s.env.uid def _get_lang(self, frame): # try, in order: context.get('lang'), kwargs['context'].get('lang'), # self.env.lang, self.localcontext.get('lang'), request.env.lang lang = None if frame.f_locals.get('context'): lang = frame.f_locals['context'].get('lang') if not lang: kwargs = frame.f_locals.get('kwargs', {}) if kwargs.get('context'): lang = kwargs['context'].get('lang') if not lang: s = frame.f_locals.get('self') if hasattr(s, 'env'): lang = s.env.lang if not lang: if hasattr(s, 'localcontext'): lang = s.localcontext.get('lang') if not lang: try: from openerp.http import request lang = request.env.lang except RuntimeError: pass if not lang: # Last resort: attempt to guess the language of the user # Pitfall: some operations are performed in sudo mode, and we # don't know the originial uid, so the language may # be wrong when the admin language differs. pool = getattr(s, 'pool', None) (cr, dummy) = self._get_cr(frame, allow_create=False) uid = self._get_uid(frame) if pool and cr and uid: lang = pool['res.users'].context_get(cr, uid)['lang'] return lang def __call__(self, source): res = source cr = None is_new_cr = False try: frame = inspect.currentframe() if frame is None: return source frame = frame.f_back if not frame: return source lang = self._get_lang(frame) if lang: cr, is_new_cr = self._get_cr(frame) if cr: # Try to use ir.translation to benefit from global cache if possible registry = openerp.registry(cr.dbname) res = registry['ir.translation']._get_source(cr, SUPERUSER_ID, None, ('code','sql_constraint'), lang, source) else: _logger.debug('no context cursor detected, skipping translation for "%r"', source) else: _logger.debug('no translation language detected, skipping translation for "%r" ', source) except Exception: _logger.debug('translation went wrong for "%r", skipped', source) # if so, double-check the root/base translations filenames finally: if cr and is_new_cr: cr.close() return res _ = GettextAlias() def quote(s): """Returns quoted PO term string, with special PO characters escaped""" assert r"\n" not in s, "Translation terms may not include escaped newlines ('\\n'), please use only literal newlines! (in '%s')" % s return '"%s"' % s.replace('\\','\\\\') \ .replace('"','\\"') \ .replace('\n', '\\n"\n"') re_escaped_char = re.compile(r"(\\.)") re_escaped_replacements = {'n': '\n', } def _sub_replacement(match_obj): return re_escaped_replacements.get(match_obj.group(1)[1], match_obj.group(1)[1]) def unquote(str): """Returns unquoted PO term string, with special PO characters unescaped""" return re_escaped_char.sub(_sub_replacement, str[1:-1]) # class to handle po files class TinyPoFile(object): def __init__(self, buffer): self.buffer = buffer def warn(self, msg, *args): _logger.warning(msg, *args) def __iter__(self): self.buffer.seek(0) self.lines = self._get_lines() self.lines_count = len(self.lines) self.first = True self.extra_lines= [] return self def _get_lines(self): lines = self.buffer.readlines() # remove the BOM (Byte Order Mark): if len(lines): lines[0] = unicode(lines[0], 'utf8').lstrip(unicode( codecs.BOM_UTF8, "utf8")) lines.append('') # ensure that the file ends with at least an empty line return lines def cur_line(self): return self.lines_count - len(self.lines) def next(self): trans_type = name = res_id = source = trad = None if self.extra_lines: trans_type, name, res_id, source, trad, comments = self.extra_lines.pop(0) if not res_id: res_id = '0' else: comments = [] targets = [] line = None fuzzy = False while not line: if 0 == len(self.lines): raise StopIteration() line = self.lines.pop(0).strip() while line.startswith('#'): if line.startswith('#~ '): break if line.startswith('#.'): line = line[2:].strip() if not line.startswith('module:'): comments.append(line) elif line.startswith('#:'): # Process the `reference` comments. Each line can specify # multiple targets (e.g. model, view, code, selection, # ...). For each target, we will return an additional # entry. for lpart in line[2:].strip().split(' '): trans_info = lpart.strip().split(':',2) if trans_info and len(trans_info) == 2: # looks like the translation trans_type is missing, which is not # unexpected because it is not a GetText standard. Default: 'code' trans_info[:0] = ['code'] if trans_info and len(trans_info) == 3: # this is a ref line holding the destination info (model, field, record) targets.append(trans_info) elif line.startswith('#,') and (line[2:].strip() == 'fuzzy'): fuzzy = True line = self.lines.pop(0).strip() if not self.lines: raise StopIteration() while not line: # allow empty lines between comments and msgid line = self.lines.pop(0).strip() if line.startswith('#~ '): while line.startswith('#~ ') or not line.strip(): if 0 == len(self.lines): raise StopIteration() line = self.lines.pop(0) # This has been a deprecated entry, don't return anything return self.next() if not line.startswith('msgid'): raise Exception("malformed file: bad line: %s" % line) source = unquote(line[6:]) line = self.lines.pop(0).strip() if not source and self.first: self.first = False # if the source is "" and it's the first msgid, it's the special # msgstr with the informations about the traduction and the # traductor; we skip it self.extra_lines = [] while line: line = self.lines.pop(0).strip() return self.next() while not line.startswith('msgstr'): if not line: raise Exception('malformed file at %d'% self.cur_line()) source += unquote(line) line = self.lines.pop(0).strip() trad = unquote(line[7:]) line = self.lines.pop(0).strip() while line: trad += unquote(line) line = self.lines.pop(0).strip() if targets and not fuzzy: # Use the first target for the current entry (returned at the # end of this next() call), and keep the others to generate # additional entries (returned the next next() calls). trans_type, name, res_id = targets.pop(0) for t, n, r in targets: if t == trans_type == 'code': continue self.extra_lines.append((t, n, r, source, trad, comments)) if name is None: if not fuzzy: self.warn('Missing "#:" formated comment at line %d for the following source:\n\t%s', self.cur_line(), source[:30]) return self.next() return trans_type, name, res_id, source, trad, '\n'.join(comments) def write_infos(self, modules): import openerp.release as release self.buffer.write("# Translation of %(project)s.\n" \ "# This file contains the translation of the following modules:\n" \ "%(modules)s" \ "#\n" \ "msgid \"\"\n" \ "msgstr \"\"\n" \ '''"Project-Id-Version: %(project)s %(version)s\\n"\n''' \ '''"Report-Msgid-Bugs-To: \\n"\n''' \ '''"POT-Creation-Date: %(now)s\\n"\n''' \ '''"PO-Revision-Date: %(now)s\\n"\n''' \ '''"Last-Translator: <>\\n"\n''' \ '''"Language-Team: \\n"\n''' \ '''"MIME-Version: 1.0\\n"\n''' \ '''"Content-Type: text/plain; charset=UTF-8\\n"\n''' \ '''"Content-Transfer-Encoding: \\n"\n''' \ '''"Plural-Forms: \\n"\n''' \ "\n" % { 'project': release.description, 'version': release.version, 'modules': reduce(lambda s, m: s + "#\t* %s\n" % m, modules, ""), 'now': datetime.utcnow().strftime('%Y-%m-%d %H:%M')+"+0000", } ) def write(self, modules, tnrs, source, trad, comments=None): plurial = len(modules) > 1 and 's' or '' self.buffer.write("#. module%s: %s\n" % (plurial, ', '.join(modules))) if comments: self.buffer.write(''.join(('#. %s\n' % c for c in comments))) code = False for typy, name, res_id in tnrs: self.buffer.write("#: %s:%s:%s\n" % (typy, name, res_id)) if typy == 'code': code = True if code: # only strings in python code are python formated self.buffer.write("#, python-format\n") if not isinstance(trad, unicode): trad = unicode(trad, 'utf8') if not isinstance(source, unicode): source = unicode(source, 'utf8') msg = "msgid %s\n" \ "msgstr %s\n\n" \ % (quote(source), quote(trad)) self.buffer.write(msg.encode('utf8')) # Methods to export the translation file def trans_export(lang, modules, buffer, format, cr): def _process(format, modules, rows, buffer, lang): if format == 'csv': writer = csv.writer(buffer, 'UNIX') # write header first writer.writerow(("module","type","name","res_id","src","value","comments")) for module, type, name, res_id, src, trad, comments in rows: comments = '\n'.join(comments) writer.writerow((module, type, name, res_id, src, trad, comments)) elif format == 'po': writer = TinyPoFile(buffer) writer.write_infos(modules) # we now group the translations by source. That means one translation per source. grouped_rows = {} for module, type, name, res_id, src, trad, comments in rows: row = grouped_rows.setdefault(src, {}) row.setdefault('modules', set()).add(module) if not row.get('translation') and trad != src: row['translation'] = trad row.setdefault('tnrs', []).append((type, name, res_id)) row.setdefault('comments', set()).update(comments) for src, row in sorted(grouped_rows.items()): if not lang: # translation template, so no translation value row['translation'] = '' elif not row.get('translation'): row['translation'] = src writer.write(row['modules'], row['tnrs'], src, row['translation'], row['comments']) elif format == 'tgz': rows_by_module = {} for row in rows: module = row[0] rows_by_module.setdefault(module, []).append(row) tmpdir = tempfile.mkdtemp() for mod, modrows in rows_by_module.items(): tmpmoddir = join(tmpdir, mod, 'i18n') os.makedirs(tmpmoddir) pofilename = (lang if lang else mod) + ".po" + ('t' if not lang else '') buf = file(join(tmpmoddir, pofilename), 'w') _process('po', [mod], modrows, buf, lang) buf.close() tar = tarfile.open(fileobj=buffer, mode='w|gz') tar.add(tmpdir, '') tar.close() else: raise Exception(_('Unrecognized extension: must be one of ' '.csv, .po, or .tgz (received .%s).') % format) translations = trans_generate(lang, modules, cr) modules = set(t[0] for t in translations) _process(format, modules, translations, buffer, lang) del translations def trans_parse_rml(de): res = [] for n in de: for m in n: if isinstance(m, SKIPPED_ELEMENT_TYPES) or not m.text: continue string_list = [s.replace('\n', ' ').strip() for s in re.split('\[\[.+?\]\]', m.text)] for s in string_list: if s: res.append(s.encode("utf8")) res.extend(trans_parse_rml(n)) return res def _push(callback, term, source_line): """ Sanity check before pushing translation terms """ term = (term or "").strip().encode('utf8') # Avoid non-char tokens like ':' '...' '.00' etc. if len(term) > 8 or any(x.isalpha() for x in term): callback(term, source_line) # tests whether an object is in a list of modules def in_modules(object_name, modules): if 'all' in modules: return True module_dict = { 'ir': 'base', 'res': 'base', 'workflow': 'base', } module = object_name.split('.')[0] module = module_dict.get(module, module) return module in modules def _extract_translatable_qweb_terms(element, callback): """ Helper method to walk an etree document representing a QWeb template, and call ``callback(term)`` for each translatable term that is found in the document. :param etree._Element element: root of etree document to extract terms from :param Callable callback: a callable in the form ``f(term, source_line)``, that will be called for each extracted term. """ # not using elementTree.iterparse because we need to skip sub-trees in case # the ancestor element had a reason to be skipped for el in element: if isinstance(el, SKIPPED_ELEMENT_TYPES): continue if (el.tag.lower() not in SKIPPED_ELEMENTS and "t-js" not in el.attrib and not ("t-jquery" in el.attrib and "t-operation" not in el.attrib) and el.get("t-translation", '').strip() != "off"): _push(callback, el.text, el.sourceline) for att in ('title', 'alt', 'label', 'placeholder'): if att in el.attrib: _push(callback, el.attrib[att], el.sourceline) _extract_translatable_qweb_terms(el, callback) _push(callback, el.tail, el.sourceline) def babel_extract_qweb(fileobj, keywords, comment_tags, options): """Babel message extractor for qweb template files. :param fileobj: the file-like object the messages should be extracted from :param keywords: a list of keywords (i.e. function names) that should be recognized as translation functions :param comment_tags: a list of translator tags to search for and include in the results :param options: a dictionary of additional options (optional) :return: an iterator over ``(lineno, funcname, message, comments)`` tuples :rtype: Iterable """ result = [] def handle_text(text, lineno): result.append((lineno, None, text, [])) tree = etree.parse(fileobj) _extract_translatable_qweb_terms(tree.getroot(), handle_text) return result def trans_generate(lang, modules, cr): dbname = cr.dbname registry = openerp.registry(dbname) trans_obj = registry['ir.translation'] model_data_obj = registry['ir.model.data'] uid = 1 query = 'SELECT name, model, res_id, module' \ ' FROM ir_model_data' query_models = """SELECT m.id, m.model, imd.module FROM ir_model AS m, ir_model_data AS imd WHERE m.id = imd.res_id AND imd.model = 'ir.model' """ if 'all_installed' in modules: query += ' WHERE module IN ( SELECT name FROM ir_module_module WHERE state = \'installed\') ' query_models += " AND imd.module in ( SELECT name FROM ir_module_module WHERE state = 'installed') " query_param = None if 'all' not in modules: query += ' WHERE module IN %s' query_models += ' AND imd.module in %s' query_param = (tuple(modules),) else: query += ' WHERE module != %s' query_models += ' AND imd.module != %s' query_param = ('__export__',) query += ' ORDER BY module, model, name' query_models += ' ORDER BY module, model' cr.execute(query, query_param) _to_translate = set() def push_translation(module, type, name, id, source, comments=None): # empty and one-letter terms are ignored, they probably are not meant to be # translated, and would be very hard to translate anyway. sanitized_term = (source or '').strip() try: # verify the minimal size without eventual xml tags # wrap to make sure html content like '<a>b</a><c>d</c>' is accepted by lxml wrapped = "<div>%s</div>" % sanitized_term node = etree.fromstring(wrapped) sanitized_term = etree.tostring(node, encoding='UTF-8', method='text') except etree.ParseError: pass # remove non-alphanumeric chars sanitized_term = re.sub(r'\W+', '', sanitized_term) if not sanitized_term or len(sanitized_term) <= 1: return tnx = (module, source, name, id, type, tuple(comments or ())) _to_translate.add(tnx) def push(mod, type, name, res_id, term): term = (term or '').strip() if len(term) > 2 or term in ENGLISH_SMALL_WORDS: push_translation(mod, type, name, res_id, term) def get_root_view(xml_id): view = model_data_obj.xmlid_to_object(cr, uid, xml_id) if view: while view.mode != 'primary': view = view.inherit_id xml_id = view.get_external_id(cr, uid).get(view.id, xml_id) return xml_id for (xml_name,model,res_id,module) in cr.fetchall(): module = encode(module) model = encode(model) xml_name = "%s.%s" % (module, encode(xml_name)) if model not in registry: _logger.error("Unable to find object %r", model) continue Model = registry[model] if not Model._translate: # explicitly disabled continue obj = Model.browse(cr, uid, res_id) if not obj.exists(): _logger.warning("Unable to find object %r with id %d", model, res_id) continue if model=='ir.model.fields': try: field_name = encode(obj.name) except AttributeError, exc: _logger.error("name error in %s: %s", xml_name, str(exc)) continue field_model = registry.get(obj.model) if (field_model is None or not field_model._translate or field_name not in field_model._fields): continue field_def = field_model._fields[field_name] if hasattr(field_def, 'selection') and isinstance(field_def.selection, (list, tuple)): name = "%s,%s" % (encode(obj.model), field_name) for dummy, val in field_def.selection: push_translation(module, 'selection', name, 0, encode(val)) elif model=='ir.actions.report.xml': name = encode(obj.report_name) fname = "" if obj.report_rml: fname = obj.report_rml parse_func = trans_parse_rml report_type = "report" elif obj.report_xsl: continue if fname and obj.report_type in ('pdf', 'xsl'): try: report_file = misc.file_open(fname) try: d = etree.parse(report_file) for t in parse_func(d.iter()): push_translation(module, report_type, name, 0, t) finally: report_file.close() except (IOError, etree.XMLSyntaxError): _logger.exception("couldn't export translation for report %s %s %s", name, report_type, fname) for field_name, field_def in obj._fields.iteritems(): if getattr(field_def, 'translate', None): name = model + "," + field_name try: value = obj[field_name] or '' except Exception: continue for term in set(field_def.get_trans_terms(value)): push_translation(module, 'model', name, xml_name, encode(term)) # End of data for ir.model.data query results cr.execute(query_models, query_param) def push_constraint_msg(module, term_type, model, msg): if not hasattr(msg, '__call__'): push_translation(encode(module), term_type, encode(model), 0, encode(msg)) def push_local_constraints(module, model, cons_type='sql_constraints'): """Climb up the class hierarchy and ignore inherited constraints from other modules""" term_type = 'sql_constraint' if cons_type == 'sql_constraints' else 'constraint' msg_pos = 2 if cons_type == 'sql_constraints' else 1 for cls in model.__class__.__mro__: if getattr(cls, '_module', None) != module: continue constraints = getattr(cls, '_local_' + cons_type, []) for constraint in constraints: push_constraint_msg(module, term_type, model._name, constraint[msg_pos]) for (_, model, module) in cr.fetchall(): if model not in registry: _logger.error("Unable to find object %r", model) continue model_obj = registry[model] if model_obj._constraints: push_local_constraints(module, model_obj, 'constraints') if model_obj._sql_constraints: push_local_constraints(module, model_obj, 'sql_constraints') installed_modules = map( lambda m: m['name'], registry['ir.module.module'].search_read(cr, uid, [('state', '=', 'installed')], fields=['name'])) path_list = [(path, True) for path in openerp.modules.module.ad_paths] # Also scan these non-addon paths for bin_path in ['osv', 'report', 'modules', 'service', 'tools']: path_list.append((os.path.join(config.config['root_path'], bin_path), True)) # non-recursive scan for individual files in root directory but without # scanning subdirectories that may contain addons path_list.append((config.config['root_path'], False)) _logger.debug("Scanning modules at paths: %s", path_list) def get_module_from_path(path): for (mp, rec) in path_list: if rec and path.startswith(mp) and os.path.dirname(path) != mp: path = path[len(mp)+1:] return path.split(os.path.sep)[0] return 'base' # files that are not in a module are considered as being in 'base' module def verified_module_filepaths(fname, path, root): fabsolutepath = join(root, fname) frelativepath = fabsolutepath[len(path):] display_path = "addons%s" % frelativepath module = get_module_from_path(fabsolutepath) if ('all' in modules or module in modules) and module in installed_modules: if os.path.sep != '/': display_path = display_path.replace(os.path.sep, '/') return module, fabsolutepath, frelativepath, display_path return None, None, None, None def babel_extract_terms(fname, path, root, extract_method="python", trans_type='code', extra_comments=None, extract_keywords={'_': None}): module, fabsolutepath, _, display_path = verified_module_filepaths(fname, path, root) extra_comments = extra_comments or [] if not module: return src_file = open(fabsolutepath, 'r') try: for extracted in extract.extract(extract_method, src_file, keywords=extract_keywords): # Babel 0.9.6 yields lineno, message, comments # Babel 1.3 yields lineno, message, comments, context lineno, message, comments = extracted[:3] push_translation(module, trans_type, display_path, lineno, encode(message), comments + extra_comments) except Exception: _logger.exception("Failed to extract terms from %s", fabsolutepath) finally: src_file.close() for (path, recursive) in path_list: _logger.debug("Scanning files of modules at %s", path) for root, dummy, files in osutil.walksymlinks(path): for fname in fnmatch.filter(files, '*.py'): babel_extract_terms(fname, path, root) # mako provides a babel extractor: http://docs.makotemplates.org/en/latest/usage.html#babel for fname in fnmatch.filter(files, '*.mako'): babel_extract_terms(fname, path, root, 'mako', trans_type='report') # Javascript source files in the static/src/js directory, rest is ignored (libs) if fnmatch.fnmatch(root, '*/static/src/js*'): for fname in fnmatch.filter(files, '*.js'): babel_extract_terms(fname, path, root, 'javascript', extra_comments=[WEB_TRANSLATION_COMMENT], extract_keywords={'_t': None, '_lt': None}) # QWeb template files if fnmatch.fnmatch(root, '*/static/src/xml*'): for fname in fnmatch.filter(files, '*.xml'): babel_extract_terms(fname, path, root, 'openerp.tools.translate:babel_extract_qweb', extra_comments=[WEB_TRANSLATION_COMMENT]) if not recursive: # due to topdown, first iteration is in first level break out = [] # translate strings marked as to be translated for module, source, name, id, type, comments in sorted(_to_translate): trans = '' if not lang else trans_obj._get_source(cr, uid, name, type, lang, source) out.append((module, type, name, id, source, encode(trans) or '', comments)) return out def trans_load(cr, filename, lang, verbose=True, module_name=None, context=None): try: fileobj = misc.file_open(filename) _logger.info("loading %s", filename) fileformat = os.path.splitext(filename)[-1][1:].lower() result = trans_load_data(cr, fileobj, fileformat, lang, verbose=verbose, module_name=module_name, context=context) fileobj.close() return result except IOError: if verbose: _logger.error("couldn't read translation file %s", filename) return None def trans_load_data(cr, fileobj, fileformat, lang, lang_name=None, verbose=True, module_name=None, context=None): """Populates the ir_translation table.""" if verbose: _logger.info('loading translation file for language %s', lang) if context is None: context = {} db_name = cr.dbname registry = openerp.registry(db_name) lang_obj = registry.get('res.lang') trans_obj = registry.get('ir.translation') iso_lang = misc.get_iso_codes(lang) try: ids = lang_obj.search(cr, SUPERUSER_ID, [('code','=', lang)]) if not ids: # lets create the language with locale information lang_obj.load_lang(cr, SUPERUSER_ID, lang=lang, lang_name=lang_name) # Parse also the POT: it will possibly provide additional targets. # (Because the POT comments are correct on Launchpad but not the # PO comments due to a Launchpad limitation. See LP bug 933496.) pot_reader = [] # now, the serious things: we read the language file fileobj.seek(0) if fileformat == 'csv': reader = csv.reader(fileobj, quotechar='"', delimiter=',') # read the first line of the file (it contains columns titles) for row in reader: fields = row break elif fileformat == 'po': reader = TinyPoFile(fileobj) fields = ['type', 'name', 'res_id', 'src', 'value', 'comments'] # Make a reader for the POT file and be somewhat defensive for the # stable branch. if fileobj.name.endswith('.po'): try: # Normally the path looks like /path/to/xxx/i18n/lang.po # and we try to find the corresponding # /path/to/xxx/i18n/xxx.pot file. # (Sometimes we have 'i18n_extra' instead of just 'i18n') addons_module_i18n, _ignored = os.path.split(fileobj.name) addons_module, i18n_dir = os.path.split(addons_module_i18n) addons, module = os.path.split(addons_module) pot_handle = misc.file_open(os.path.join( addons, module, i18n_dir, module + '.pot')) pot_reader = TinyPoFile(pot_handle) except: pass else: _logger.info('Bad file format: %s', fileformat) raise Exception(_('Bad file format: %s') % fileformat) # Read the POT references, and keep them indexed by source string. class Target(object): def __init__(self): self.value = None self.targets = set() # set of (type, name, res_id) self.comments = None pot_targets = defaultdict(Target) for type, name, res_id, src, _ignored, comments in pot_reader: if type is not None: target = pot_targets[src] target.targets.add((type, name, res_id)) target.comments = comments # read the rest of the file irt_cursor = trans_obj._get_import_cursor(cr, SUPERUSER_ID, context=context) def process_row(row): """Process a single PO (or POT) entry.""" # dictionary which holds values for this line of the csv file # {'lang': ..., 'type': ..., 'name': ..., 'res_id': ..., # 'src': ..., 'value': ..., 'module':...} dic = dict.fromkeys(('type', 'name', 'res_id', 'src', 'value', 'comments', 'imd_model', 'imd_name', 'module')) dic['lang'] = lang dic.update(zip(fields, row)) <|fim▁hole|> target.value = dic['value'] target.targets.discard((dic['type'], dic['name'], dic['res_id'])) # This would skip terms that fail to specify a res_id res_id = dic['res_id'] if not res_id: return if isinstance(res_id, (int, long)) or \ (isinstance(res_id, basestring) and res_id.isdigit()): dic['res_id'] = int(res_id) if module_name: dic['module'] = module_name else: # res_id is an xml id dic['res_id'] = None dic['imd_model'] = dic['name'].split(',')[0] if '.' in res_id: dic['module'], dic['imd_name'] = res_id.split('.', 1) else: dic['module'], dic['imd_name'] = module_name, res_id irt_cursor.push(dic) # First process the entries from the PO file (doing so also fills/removes # the entries from the POT file). for row in reader: process_row(row) # Then process the entries implied by the POT file (which is more # correct w.r.t. the targets) if some of them remain. pot_rows = [] for src, target in pot_targets.iteritems(): if target.value: for type, name, res_id in target.targets: pot_rows.append((type, name, res_id, src, target.value, target.comments)) pot_targets.clear() for row in pot_rows: process_row(row) irt_cursor.finish() trans_obj.clear_caches() if verbose: _logger.info("translation file loaded succesfully") except IOError: filename = '[lang: %s][format: %s]' % (iso_lang or 'new', fileformat) _logger.exception("couldn't read translation file %s", filename) def get_locales(lang=None): if lang is None: lang = locale.getdefaultlocale()[0] if os.name == 'nt': lang = _LOCALE2WIN32.get(lang, lang) def process(enc): ln = locale._build_localename((lang, enc)) yield ln nln = locale.normalize(ln) if nln != ln: yield nln for x in process('utf8'): yield x prefenc = locale.getpreferredencoding() if prefenc: for x in process(prefenc): yield x prefenc = { 'latin1': 'latin9', 'iso-8859-1': 'iso8859-15', 'cp1252': '1252', }.get(prefenc.lower()) if prefenc: for x in process(prefenc): yield x yield lang def resetlocale(): # locale.resetlocale is bugged with some locales. for ln in get_locales(): try: return locale.setlocale(locale.LC_ALL, ln) except locale.Error: continue def load_language(cr, lang): """Loads a translation terms for a language. Used mainly to automate language loading at db initialization. :param lang: language ISO code with optional _underscore_ and l10n flavor (ex: 'fr', 'fr_BE', but not 'fr-BE') :type lang: str """ registry = openerp.registry(cr.dbname) language_installer = registry['base.language.install'] oid = language_installer.create(cr, SUPERUSER_ID, {'lang': lang}) language_installer.lang_install(cr, SUPERUSER_ID, [oid], context=None)<|fim▁end|>
# discard the target from the POT targets. src = dic['src'] if src in pot_targets: target = pot_targets[src]
<|file_name|>namegame.py<|end_file_name|><|fim▁begin|>"""Namegame, where you try to remember a team number starting with the last number of the previous played team""" import asyncio import gzip import pickle import traceback from collections import OrderedDict from functools import wraps import discord import tbapi from discord.ext.commands import has_permissions from fuzzywuzzy import fuzz from dozer.bot import DOZER_LOGGER from ._utils import * from .. import db SUPPORTED_MODES = ["frc", "ftc"] def keep_alive(func): """Keeps the wrapped async function alive; functions must have self and ctx as args""" @wraps(func) async def wrapper(self, ctx, *args, **kwargs): """Wraps namegame""" while True: try: return await func(self, ctx, *args, **kwargs) except Exception as e: # CancelledErrors are normal part of operation, ignore them if isinstance(e, asyncio.CancelledError): return # panic to the console, and to chat DOZER_LOGGER.error(traceback.format_exc()) await ctx.send(f"```Error in game loop:\n{e.__class__.__name__}: {e}```") return wrapper def game_is_running(func): """Check if there's an active game in a channel""" @wraps(func) async def wrapper(self, ctx, *args, **kwargs): """Wraps the checker""" if ctx.channel.id not in self.games: await ctx.send(f"There's not a game going on! Start one with `{ctx.prefix}ng startround`") return return await func(self, ctx, *args, **kwargs) return wrapper class NameGameSession(): """NameGame session object""" def __init__(self, mode): self.running = True self.pings_enabled = False self.players = OrderedDict() self.removed_players = [] self.picked = [] self.mode = mode self.time = 60 self.vote_time = -1 self.number = 0 self.current_player = None self.last_name = "" self.last_team = 0 self.state_lock = None self.turn_msg = None self.turn_embed = None self.turn_task = None self.turn_count = 0 self.pass_tally = 0 self.fail_tally = 0 self.vote_correct = False self.vote_player = None self.vote_msg = None self.vote_embed = None self.vote_task = None def create_embed(self, title="", description="", color=discord.Color.blurple(), extra_fields=[], start=False): """Creates an embed.""" v = "Starting " if start else "Current " embed = discord.Embed() embed.title = title embed.description = description embed.color = color embed.add_field(name="Players", value=", ".join([p.display_name for p in self.players.keys()]) or "n/a") embed.add_field(name=v + "Player", value=self.current_player) embed.add_field(name=v + "Number", value=self.number or "Wildcard") embed.add_field(name="Time Left", value=self.time) for name, value in extra_fields: embed.add_field(name=name, value=value) return embed def check_name(self, ctx, team, name): """Checks the name of the team""" tba_parser = ctx.cog.tba_parser ftc_teams = ctx.cog.ftc_teams actual_name = "" if self.mode == "frc": # check for existence team_data = tba_parser.get_team(team) try: getattr(team_data, "Errors") except tbapi.InvalidKeyError: """There is no error, so do nothing""" else: return -1 actual_name = team_data.nickname elif self.mode == "ftc": if team not in ftc_teams: return -1 actual_name = ftc_teams[team] self.last_name = actual_name self.last_team = team return fuzz.ratio(actual_name.lower(), name.lower()) def next_turn(self): """Processes the next turn transition""" self.turn_count += 1 self.pass_tally = 0 self.fail_tally = 0 self.time = 60 players = list(self.players.keys()) # set the current player to the next handle in the list self.current_player = players[(players.index(self.current_player) + 1) % len(players)] # self._idx = (self._idx + 1) % len(self.players) def strike(self, player): """Gives players strikes""" self.players[player] += 1 if self.players[player] >= 3 or len(self.players) == 1: self.removed_players.append(player) self.players.pop(player) return True return False def check_win(self): """Checks if someone won the game""" return len(self.players) == 1 and self.turn_count > 6 def get_picked(self): """Gets the picked teams""" return ", ".join(map(str, sorted(self.picked))) or "No Picked Teams" class NameGame(Cog): """Namegame commands""" def __init__(self, bot): super().__init__(bot) with gzip.open("ftc_teams.pickle.gz") as f: raw_teams = pickle.load(f) self.ftc_teams = {team: data['seasons'][0]['name'] for (team, data) in raw_teams.items()} self.games = {} tba_config = bot.config['tba'] self.tba_parser = tbapi.TBAParser(tba_config['key'], cache=False) @group(invoke_without_command=True) async def ng(self, ctx): """Show info about and participate in a robotics team namegame. Run the help command on each of the subcommands for more detailed help. List of subcommands: ng info ng startround ng addplayer ng pick ng drop ng skip ng gameinfo """ await self.info.callback(self, ctx) ng.example_usage = """ `{prefix}ng` - show a description on how the robotics team namegame works. """ @ng.command() @bot_has_permissions(embed_links=True) async def info(self, ctx): """Show a description of the robotics team name game and how to play.""" game_embed = discord.Embed() game_embed.color = discord.Color.magenta() game_embed.title = "How to play" game_embed.description = "This is a very simple little game where players will name a team number and name that " \ "starts with the last digit of the last named team. Some more specific rules are below:" game_embed.add_field(name="No Double Picking", value="Only pick teams once.") game_embed.add_field(name="Three Strikes, You're Out!", value="You are only allowed three strikes, which are given by picking out of turn, " "getting the team name wrong, picking a non existant team, being voted that your " "pick is incorrect, not picking in time, or picking a already picked team.") game_embed.add_field(name="No Cheatsy Doodles", value="No looking up teams on TBA, TOA, VexDB, or other methods, that's just unfair.") game_embed.add_field(name="Times up!", value="You have 60 seconds to make a pick, or you get skipped and get a strike.") game_embed.add_field(name="Shaking Things Up", value="Any team number that ends in a 0 mean that the next player has a wildcard, " "and can pick any legal team.") game_embed.add_field(name="Pesky Commands", value=(f"To start a game, type `{ctx.prefix}ng startround` and " f"mention the players you want to play with. " f"You can add people with `{ctx.prefix}ng addplayer <user_pings>`. " f"When it's your turn, type `{ctx.prefix}ng pick <team> " f"<teamname>` to execute your pick. " f"If you need to skip, typing `{ctx.prefix}ng skip` gives you" f" a strike and skips your turn." f"You can always do `{ctx.prefix}ng gameinfo` to get the " f"current game status. " f"If you ever need to quit, running `{ctx.prefix}ng drop` " f"removes you from the game. " f"For more detailed command help, run `{ctx.prefix}help ng.`")) game_embed.add_field(name="Different Game Modes", value=f"You can play the name game with FTC teams too! To start a game playing with " f"FTC teams, run `{ctx.prefix}ng startround ftc`") await ctx.send(embed=game_embed) info.example_usage = """ `{prefix}ng help` - show a description on how the robotics team namegame works """ @ng.group(invoke_without_command=True) async def config(self, ctx): """Configuration for namegame""" await ctx.send(f"""`{ctx.prefix}ng config` reference: `{ctx.prefix}ng config defaultmode [mode]` - set tbe default game mode used when startround is used with no arguments `{ctx.prefix}ng config setchannel [channel_mention]` - set the channel that games are allowed to be run in<|fim▁hole|> `{ctx.prefix}ng config clearsetchannel` - clear the set channel for games""") @config.command() @has_permissions(manage_guild=True) async def defaultmode(self, ctx, mode: str = None): """Configuration of the default game mode (FRC, FTC, etc.)""" query = await NameGameConfig.get_by(guild_id=ctx.guild.id) config = query[0] if len(query) == 1 else None if mode is None: mode = SUPPORTED_MODES[0] if config is None else config.mode await ctx.send(f"The current default game mode for this server is `{mode}`") else: if mode not in SUPPORTED_MODES: await ctx.send( f"Game mode `{mode}` not supported! Please pick a mode that is one of: `{', '.join(SUPPORTED_MODES)}`") return if config is None: config = NameGameConfig(guild_id=ctx.guild.id, channel_id=None, mode=mode, pings_enabled=False) await config.update_or_add() else: config.mode = mode await config.update_or_add() await ctx.send(f"Default game mode updated to `{mode}`") @config.command() @has_permissions(manage_guild=True) async def setchannel(self, ctx, channel: discord.TextChannel = None): """Sets the namegame channel""" query = await NameGameConfig.get_by(guild_id=ctx.guild.id) config = query[0] if len(query) == 1 else None if channel is None: if config is None or config.channel_id is None: await ctx.send( f"There is no currently set namegame channel.\nTo set a channel, run `{ctx.prefix}ng config " f"setchannel [channel_mention]`") else: await ctx.send( f"The currently set namegame channel is {ctx.guild.get_channel(config.channel_id).mention}.\n" f"To clear this, run `{ctx.prefix}ng config clearsetchannel`") else: if config is None: config = NameGameConfig(guild_id=ctx.guild.id, channel_id=channel.id, mode=SUPPORTED_MODES[0], pings_enabled=False) else: config.channel_id = channel.id await config.update_or_add() await ctx.send(f"Namegame channel set to {channel.mention}!") @config.command() @has_permissions(manage_guild=True) async def clearsetchannel(self, ctx): """Clears the set namegame channel""" query = await NameGameConfig.get_by(guild_id=ctx.guild.id) config = query[0] if len(query) == 1 else None if config is not None: # update_or_add ignores attributes set to None. To set the column to None, we delete the record and insert # a new one with channel set to None. new_namegame_config = NameGameConfig(channel_id=None, guild_id=ctx.guild.id, pings_enabled=config.pings_enabled, mode=config.mode) await NameGameConfig.delete(guild_id=ctx.guild.id) await new_namegame_config.update_or_add() await ctx.send("Namegame channel cleared!") @config.command() @has_permissions(manage_guild=True) async def setpings(self, ctx, enabled: bool): """Sets whether or not pings are enabled""" query = await NameGameConfig.get_by(guild_id=ctx.guild.id) config = query[0] if len(query) == 1 else None if config is None: config = NameGameConfig(guild_id=ctx.guild.id, channel_id=None, mode=SUPPORTED_MODES[0], pings_enabled=int(enabled)) else: config.pings_enabled = int(enabled) await config.update_or_add() await ctx.send(f"Pings enabled set to `{enabled}`!") @config.command() @has_permissions(manage_guild=True) async def leaderboardedit(self, ctx, mode: str, user: discord.User, wins: int): """Edits the leaderboard""" if mode not in SUPPORTED_MODES: await ctx.send( f"Game mode `{mode}` not supported! Please pick a mode that is one of: `{', '.join(SUPPORTED_MODES)}`") return query = await NameGameLeaderboard.get_by(user_id=user.id, game_mode=mode) if not query: await ctx.send("User not on leaderboard!") return record = query[0] record.wins = wins await record.update_or_add() await ctx.send(f"{user.display_name}'s wins now set to: **{wins}**") @config.command() @has_permissions(manage_guild=True) async def leaderboardclear(self, ctx, mode: str): """Clears the leaderboard""" if mode not in SUPPORTED_MODES: await ctx.send( f"Game mode `{mode}` not supported! Please pick a mode that is one of: `{', '.join(SUPPORTED_MODES)}`") return await NameGameLeaderboard.delete(game_mode=mode) await ctx.send(f"Cleared leaderboard for mode {mode}") # TODO: configurable time limits, ping on event, etc # MORE TODO: """ fix %ng help (done) fix %ng startround (done) fix the wrong team dialouge (????) add pings i hate bots make %ng addplayer be rhetorical question (done) figure out these stupid turn issues """ @ng.command() @game_is_running async def unheck(self, ctx): """ Emergency removal of a haywire session. """ game = self.games[ctx.channel.id] game.running = False try: game.vote_task.cancel() except Exception: pass try: game.turn_task.cancel() except Exception: pass self.games.pop(game) @ng.command() async def modes(self, ctx): """Returns a list of supported modes""" await ctx.send(f"Supported game modes: `{', '.join(SUPPORTED_MODES)}`") @ng.command() async def startround(self, ctx, mode: str = None): """ Starts a namegame session. One can select the robotics program by specifying one of "FRC" or "FTC". """ if mode is None or mode.lower() not in SUPPORTED_MODES: config = await NameGameConfig.get_by(guild_id=ctx.guild.id) mode = SUPPORTED_MODES[0] if len(config) == 0 else config[0].mode await ctx.send( f"Unspecified or invalid game mode, assuming game mode `{mode}`. For a full list of game modes, run " f"`{ctx.prefix}ng modes`") pings_enabled = False config_query = await NameGameConfig.get_by(guild_id=ctx.guild.id) if len(config_query) == 0: config = None else: config = config_query[0] if config is not None and config.channel_id is not None and config.channel_id != ctx.channel.id: await ctx.send("Games cannot be started in this channel!") return pings_enabled = (config is not None and config.pings_enabled) if ctx.channel.id in self.games: await ctx.send("A game is currently going on! Wait till the players finish up to start again.") return game = NameGameSession(mode.lower()) game.state_lock = asyncio.Lock(loop=self.bot.loop) game.pings_enabled = pings_enabled game.players[ctx.author] = 0 game.current_player = ctx.author for player in ctx.message.mentions: if player == ctx.author: continue if player.bot: await ctx.send(f"You can't invite bot users like {player.mention}!") continue game.players[player] = 0 await self.send_turn_embed(ctx, game, title=f"{mode.upper()} Name Game", description="A game has been started! The info about the game is as follows:", color=discord.Color.green()) await self.notify(ctx, game, f"{game.current_player.mention}, start us off!") # await ctx.send(f"{game.current_player.mention}, start us off!") self.games[ctx.channel.id] = game game.turn_task = self.bot.loop.create_task(self.game_turn_countdown(ctx, game)) startround.example_usage = """ `{prefix}ng startround frc` - start an FRC namegame session. """ @ng.command() @game_is_running async def addplayer(self, ctx): """Add players to the current game. Only works if the user is currently playing.""" if ctx.channel.id not in self.games: await ctx.send(f"There's not a game going on! Start one with `{ctx.prefix}ng startround`") return game = self.games[ctx.channel.id] async with game.state_lock: added = False players = ctx.message.mentions or [ctx.author] for player in ctx.message.mentions: if player.bot: await ctx.send(f"You can't invite bot users like {player.mention}!") continue if player in game.removed_players: await ctx.send(f"{player.mention} is already out of the game and can't be added back in.") elif player in game.players: await ctx.send(f"{player.mention} is already in the game!") game.players[player] = 0 added = True if not added: return await ctx.send(embed=game.create_embed( title="Players have been added to the game.", description="See below for an updated player list.", color=discord.Color.blurple() )) addplayer.example_usage = """ `{prefix}ng addplayer @user1, @user2` - add user1 and user2 to the game. """ @ng.command() @game_is_running async def pick(self, ctx, team: int, *, name): """Attempt to pick a team in a game.""" game = self.games[ctx.channel.id] async with game.state_lock: if ctx.author != game.current_player: if ctx.author in game.players: await ctx.send( "It's not your turn! You've been given a strike for this behaviour! Don't let it happen again...") await self.strike(ctx, game, ctx.author) else: await ctx.send( f"Let the people playing play! If you want to join, ask one of the people currently playing to " f"run `{ctx.prefix}ng addplayer {ctx.author.display_name}`") return if game.time < 0: await ctx.send("Vote on the current team before picking the next!") return if game.number != 0 and str(game.number) != str(team)[0]: await self.skip_player(ctx, game, ctx.author, "Your team doesn't start with the correct digit! Strike given, moving onto the next player!") return if team in game.picked: await self.skip_player(ctx, game, ctx.author, "That team has already been picked! You have been skipped and given a strike.") return ratio = game.check_name(ctx, team, name) if ratio == -1: # nonexistant team await self.skip_player(ctx, game, ctx.author, f"Team {team} doesn't exist! Strike given, moving onto the next player!") return if ratio > 60: game.picked.append(team) game.number = game.last_team % 10 game.next_turn() game.vote_correct = True game.vote_time = 20 game.vote_player = ctx.author await self.send_turn_embed(ctx, game, title="Team correct!", description=f"Team {team} ({game.last_name}) was {ratio}% correct! Moving " f"onto the next player as follows. Click the red X to override " f"this decision.", color=discord.Color.green(), extra_fields=[("Voting Time", game.vote_time)]) await game.turn_msg.add_reaction('❌') await self.notify(ctx, game, f"{game.current_player.mention}, you're up! Current number: {game.number}") game.vote_msg = game.turn_msg game.vote_embed = game.turn_embed # EXTREMELY INCOMPLETE LOL # (not anymore) else: game.time = -1 game.vote_time = 60 game.vote_player = ctx.author game.vote_correct = False vote_embed = discord.Embed() vote_embed.color = discord.Color.gold() vote_embed.title = "A vote is needed!" vote_embed.description = "A player has made a choice with less than 50% similarity. The details of the " \ "pick are below. Click on the two emoji to vote if this is correct or not. A" \ " 50% majority of players is required to accept it, otherwise the player will " \ "get a strike." vote_embed.add_field(name="Player", value=game.current_player.mention) vote_embed.add_field(name="Team", value=team) vote_embed.add_field(name="Said Name", value=name) vote_embed.add_field(name="Actual Name", value=game.last_name) vote_embed.add_field(name="Similarity", value=f"{ratio}%") vote_embed.add_field(name="Voting Time", value=game.vote_time) game.vote_embed = vote_embed game.vote_msg = await ctx.send(embed=vote_embed) await game.vote_msg.add_reaction('✅') await game.vote_msg.add_reaction('❌') game.vote_task = self.bot.loop.create_task(self.game_vote_countdown(ctx, game)) pick.example_usage = """ `{prefix}ng pick 254 poofy cheeses` - attempt to guess team 254 with a specified name of "poofy cheeses". """ @ng.command() @game_is_running async def drop(self, ctx): """Drops a player from the current game by eliminating them. Once dropped, they can no longer rejoin.""" game = self.games[ctx.channel.id] async with game.state_lock: if ctx.author not in game.players: await ctx.send("You can't leave a game you're not in!") return game.players[ctx.author] = 2 if ctx.author == game.current_player: await self.skip_player(ctx, game, ctx.author) else: await self.strike(ctx, game, ctx.author) if game.running: await self.display_info(ctx, game) drop.example_usage = """ `{prefix}ng drop` - remove the initiator of the command from the current game """ @ng.command() @game_is_running async def skip(self, ctx): """Skips the current player if the player wishes to forfeit their turn.""" game = self.games[ctx.channel.id] async with game.state_lock: if ctx.author != game.current_player: await ctx.send("It's not your turn! Only the current player can skip their turn!") else: await self.skip_player(ctx, game, ctx.author) skip.example_usage = """ `{prefix}ng skip` - skip the current player's turn """ @ng.command() @game_is_running async def gameinfo(self, ctx): """Display info about the currently running game.""" game = self.games[ctx.channel.id] await self.display_info(ctx, game) gameinfo.example_usage = """ `{prefix}ng gameinfo` - display info about the currently running game. """ @ng.command() async def leaderboard(self, ctx, mode: str = None): """Display top numbers of wins for the specified game mode""" if mode is None: config = await NameGameConfig.get_by(guild_id=ctx.guild.id) mode = SUPPORTED_MODES[0] if len(config) == 0 else config[0].mode if mode not in SUPPORTED_MODES: await ctx.send( f"Game mode `{mode}` not supported! Please pick a mode that is one of: `{', '.join(SUPPORTED_MODES)}`") return leaderboard = sorted(await NameGameLeaderboard.get_by(game_mode=mode), key=lambda i: i.wins, reverse=True)[:10] embed = discord.Embed(color=discord.Color.gold(), title=f"{mode.upper()} Name Game Leaderboard") for idx, entry in enumerate(leaderboard, 1): embed.add_field(name=f"#{idx}: {ctx.bot.get_user(entry.user_id).display_name}", value=entry.wins) await ctx.send(embed=embed) leaderboard.example_usage = """ `{prefix}ng leaderboard ftc` - display the namegame winning leaderboards for FTC. """ async def strike(self, ctx, game, player): """Gives a player a strike.""" if game.strike(player): await ctx.send(f"Player {player.mention} is ELIMINATED!") if len(game.players) == 0 or game.turn_count <= 6: await ctx.send("Game disbanded, no winner called!") game.running = False if game.check_win(): # winning condition winner = list(game.players.keys())[0] query = await NameGameLeaderboard.get_by(user_id=winner.id, mode=game.mode) if query: record = query[0] record.wins += 1 else: record = NameGameLeaderboard(user_id=winner.id, wins=1, game_mode=game.mode) await record.update_or_add() win_embed = discord.Embed() win_embed.color = discord.Color.gold() win_embed.title = "We have a winner!" win_embed.add_field(name="Winning Player", value=winner) win_embed.add_field(name="Wins Total", value=record.wins) win_embed.add_field(name="Teams Picked", value=game.get_picked()) await ctx.send(embed=win_embed) game.running = False if not game.running: self.games.pop(ctx.channel.id) async def display_info(self, ctx, game): """Displays info about the current game""" info_embed = discord.Embed(title="Current Game Info", color=discord.Color.blue()) info_embed.add_field(name="Game Type", value=game.mode.upper()) info_embed.add_field( name="Strikes", value="\n".join([f"{player.display_name}: {strikes}" for player, strikes in game.players.items()]) ) info_embed.add_field(name="Current Player", value=game.current_player) info_embed.add_field(name="Current Number", value=game.number or "Wildcard") info_embed.add_field(name="Time Left", value=game.time) info_embed.add_field(name="Teams Picked", value=game.get_picked()) await ctx.send(embed=info_embed) async def skip_player(self, ctx, game, player, msg=None): """Skips a player""" if msg is not None: await ctx.send(msg) game.vote_time = -1 game.next_turn() await self.send_turn_embed(ctx, game, title=f"Player {player.display_name} was skipped and now has {game.players[player]+1} strike(s)!", color=discord.Color.red()) if player != game.current_player: await self.notify(ctx, game, f"{game.current_player.mention}, you're up! Current number: {game.number}") await self.strike(ctx, game, player) # send an embed that starts a new turn async def send_turn_embed(self, ctx, game, **kwargs): """Sends an embed that starts a new turn""" game.turn_embed = game.create_embed(**kwargs) game.turn_msg = await ctx.send(embed=game.turn_embed) async def notify(self, ctx, game, msg): """Notifies people in the channel when it's their turn.""" if game.pings_enabled: await ctx.send(msg) @Cog.listener() async def on_reaction_add(self, reaction, user): """When reactions are added, trigger the voting handler""" if reaction.message.channel.id not in self.games: return game = self.games[reaction.message.channel.id] async with game.state_lock: if game.vote_msg is None or game.vote_time <= 0: return await self._on_reaction(game, reaction, user, 1) # also handle voting logic ctx = await self.bot.get_context(reaction.message) if game.vote_correct: if game.fail_tally > .5 * len(game.players): await ctx.send(f"The decision was overruled! Player {game.vote_player.mention} is given a strike!") await self.strike(ctx, game, game.vote_player) game.vote_time = -1 else: if game.pass_tally >= .5 * len(game.players): game.picked.append(game.last_team) game.number = game.last_team % 10 game.next_turn() await self.send_turn_embed(ctx, game, title="Team correct!", description=f"Team {game.last_team} ({game.last_name}) was correct! " f"Moving onto the next player as follows.", color=discord.Color.green()) await self.notify(ctx, game, f"{game.current_player.mention}, you're up! Current number: {game.number}") game.vote_time = -1 elif game.fail_tally >= .5 * len(game.players): await ctx.send( f"Team {game.last_team} was guessed wrong! Strike given to the responsible player and player is skipped.") await self.skip_player(ctx, game, game.current_player) game.vote_time = -1 @Cog.listener() async def on_reaction_remove(self, reaction, user): """When a reaction is removed, do vote handling""" if reaction.message.channel.id not in self.games: return game = self.games[reaction.message.channel.id] async with game.state_lock: if game.vote_msg is None or game.vote_time <= 0: return await self._on_reaction(game, reaction, user, -1) async def _on_reaction(self, game, reaction, user, inc): """Handles pass/fail reactions""" if reaction.message.id == game.vote_msg.id and user in game.players: if reaction.emoji == '❌': game.fail_tally += inc if reaction.emoji == '✅': game.pass_tally += inc return game @keep_alive async def game_turn_countdown(self, ctx, game): """Counts down the time remaining left in the turn""" await asyncio.sleep(1) async with game.state_lock: if not game.running: return if game.time > 0: game.time -= 1 game.turn_embed.set_field_at(3, name="Time Left", value=game.time) if game.vote_time > 0 and game.vote_correct: game.vote_time -= 1 game.turn_embed.set_field_at(4, name="Voting Time", value=game.vote_time) if game.time % 5 == 0: await game.turn_msg.edit(embed=game.turn_embed) if game.time == 0: await self.skip_player(ctx, game, game.current_player) game.turn_task = self.bot.loop.create_task(self.game_turn_countdown(ctx, game)) @keep_alive async def game_vote_countdown(self, ctx, game): """Counts down the time remaining left to vote""" await asyncio.sleep(1) async with game.state_lock: if not (game.running and not game.vote_correct and game.vote_embed and game.vote_time > 0): return game.vote_time -= 1 game.vote_embed.set_field_at(5, name="Voting Time", value=game.vote_time) if game.vote_time % 5 == 0: await game.vote_msg.edit(embed=game.vote_embed) if game.vote_time == 0: await ctx.send( "The vote did not reach 50% in favor or in failure, so the responsible player is given a strike and skipped.") await self.skip_player(ctx, game, game.current_player) game.vote_task = self.bot.loop.create_task(self.game_vote_countdown(ctx, game)) class NameGameConfig(db.DatabaseTable): """Configuration storage object""" __tablename__ = 'namegame_config' __uniques__ = 'guild_id' @classmethod async def initial_create(cls): """Create the table in the database""" async with db.Pool.acquire() as conn: await conn.execute(f""" CREATE TABLE {cls.__tablename__} ( guild_id bigint PRIMARY KEY NOT NULL, channel_id bigint null, mode varchar NOT NULL, pings_enabled bigint NOT NULL )""") def __init__(self, guild_id, mode, pings_enabled, channel_id=None): super().__init__() self.channel_id = channel_id self.mode = mode self.guild_id = guild_id self.pings_enabled = pings_enabled @classmethod async def get_by(cls, **kwargs): results = await super().get_by(**kwargs) result_list = [] for result in results: obj = NameGameConfig(guild_id=result.get("guild_id"), mode=result.get("mode"), pings_enabled=result.get("pings_enabled"), channel_id=result.get("channel_id")) result_list.append(obj) return result_list class NameGameLeaderboard(db.DatabaseTable): """Leaderboard storage object""" __tablename__ = 'namegame_leaderboard' __uniques__ = 'user_id' @classmethod async def initial_create(cls): """Create the table in the database""" async with db.Pool.acquire() as conn: await conn.execute(f""" CREATE TABLE {cls.__tablename__} ( user_id bigint NOT NULL, wins bigint NOT NULL, game_mode varchar NOT NULL, PRIMARY KEY (user_id, game_mode) )""") def __init__(self, user_id, game_mode, wins): super().__init__() self.game_mode = game_mode self.user_id = user_id self.wins = wins @classmethod async def get_by(cls, **kwargs): results = await super().get_by(**kwargs) result_list = [] for result in results: obj = NameGameLeaderboard(user_id=result.get("user_id"), game_mode=result.get("game_mode"), wins=result.get("wins")) result_list.append(obj) return result_list def setup(bot): """Adds the namegame cog to the bot""" bot.add_cog(NameGame(bot))<|fim▁end|>
<|file_name|>cli.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import argparse import bz2 import gzip import os.path import sys from csvkit import CSVKitReader from csvkit.exceptions import ColumnIdentifierError, RequiredHeaderError def lazy_opener(fn): def wrapped(self, *args, **kwargs): self._lazy_open() fn(*args, **kwargs) return wrapped class LazyFile(object): """ A proxy for a File object that delays opening it until a read method is called. Currently this implements only the minimum methods to be useful, but it could easily be expanded. """ def __init__(self, init, *args, **kwargs): self.init = init self.f = None self._is_lazy_opened = False self._lazy_args = args self._lazy_kwargs = kwargs def __getattr__(self, name): if not self._is_lazy_opened: self.f = self.init(*self._lazy_args, **self._lazy_kwargs) self._is_lazy_opened = True return getattr(self.f, name) def __iter__(self): return self def close(self): self.f.close() self.f = None self._is_lazy_opened = False def next(self): if not self._is_lazy_opened: self.f = self.init(*self._lazy_args, **self._lazy_kwargs) self._is_lazy_opened = True return self.f.next() class CSVFileType(object): """ An argument factory like argparse.FileType with compression support. """ def __init__(self, mode='rb'): """ Initialize the factory. """ self._mode = mode def __call__(self, path): """ Build a file-like object from the specified path. """ if path == '-': if 'r' in self._mode: return sys.stdin elif 'w' in self._mode: return sys.stdout else: raise ValueError('Invalid path "-" with mode {0}'.format(self._mode)) else: (_, extension) = os.path.splitext(path) if extension == '.gz': return LazyFile(gzip.open, path, self._mode) if extension == '.bz2': return LazyFile(bz2.BZ2File, path, self._mode) else: return LazyFile(open, path, self._mode) class CSVKitUtility(object): description = '' epilog = '' override_flags = '' def __init__(self, args=None, output_file=None): """ Perform argument processing and other setup for a CSVKitUtility. """ self._init_common_parser() self.add_arguments() self.args = self.argparser.parse_args(args) self.reader_kwargs = self._extract_csv_reader_kwargs() self.writer_kwargs = self._extract_csv_writer_kwargs() self._install_exception_handler() if output_file is None: self.output_file = sys.stdout else: self.output_file = output_file # Ensure SIGPIPE doesn't throw an exception # Prevents [Errno 32] Broken pipe errors, e.g. when piping to 'head' # To test from the shell: # python -c "for i in range(5000): print 'a,b,c'" | csvlook | head # Without this fix you will see at the end: # [Errno 32] Broken pipe # With this fix, there should be no error # For details on Python and SIGPIPE, see http://bugs.python.org/issue1652 try: import signal signal.signal(signal.SIGPIPE, signal.SIG_DFL) except (ImportError, AttributeError): #Do nothing on platforms that don't have signals or don't have SIGPIPE pass def add_arguments(self): """ Called upon initialization once the parser for common arguments has been constructed. Should be overriden by individual utilities. """ raise NotImplementedError('add_arguments must be provided by each subclass of CSVKitUtility.') def main(self): """ Main loop of the utility. Should be overriden by individual utilities and explicitly called by the executing script. """ raise NotImplementedError(' must be provided by each subclass of CSVKitUtility.') def _init_common_parser(self): """ Prepare a base argparse argument parser so that flags are consistent across different shell command tools.<|fim▁hole|> self.argparser = argparse.ArgumentParser(description=self.description, epilog=self.epilog) # Input if 'f' not in self.override_flags: self.argparser.add_argument('file', metavar="FILE", nargs='?', type=CSVFileType(), default=sys.stdin, help='The CSV file to operate on. If omitted, will accept input on STDIN.') if 'd' not in self.override_flags: self.argparser.add_argument('-d', '--delimiter', dest='delimiter', help='Delimiting character of the input CSV file.') if 't' not in self.override_flags: self.argparser.add_argument('-t', '--tabs', dest='tabs', action='store_true', help='Specifies that the input CSV file is delimited with tabs. Overrides "-d".') if 'q' not in self.override_flags: self.argparser.add_argument('-q', '--quotechar', dest='quotechar', help='Character used to quote strings in the input CSV file.') if 'u' not in self.override_flags: self.argparser.add_argument('-u', '--quoting', dest='quoting', type=int, choices=[0,1,2,3], help='Quoting style used in the input CSV file. 0 = Quote Minimal, 1 = Quote All, 2 = Quote Non-numeric, 3 = Quote None.') if 'b' not in self.override_flags: self.argparser.add_argument('-b', '--doublequote', dest='doublequote', action='store_true', help='Whether or not double quotes are doubled in the input CSV file.') if 'p' not in self.override_flags: self.argparser.add_argument('-p', '--escapechar', dest='escapechar', help='Character used to escape the delimiter if --quoting 3 ("Quote None") is specified and to escape the QUOTECHAR if --doublequote is not specified.') if 'z' not in self.override_flags: self.argparser.add_argument('-z', '--maxfieldsize', dest='maxfieldsize', type=int, help='Maximum length of a single field in the input CSV file.') if 'e' not in self.override_flags: self.argparser.add_argument('-e', '--encoding', dest='encoding', default='utf-8', help='Specify the encoding the input CSV file.') if 'S' not in self.override_flags: self.argparser.add_argument('-S', '--skipinitialspace', dest='skipinitialspace', default=False, action='store_true', help='Ignore whitespace immediately following the delimiter.') if 'H' not in self.override_flags: self.argparser.add_argument('-H', '--no-header-row', dest='no_header_row', action='store_true', help='Specifies that the input CSV file has no header row. Will create default headers.') if 'v' not in self.override_flags: self.argparser.add_argument('-v', '--verbose', dest='verbose', action='store_true', help='Print detailed tracebacks when errors occur.') # Output if 'l' not in self.override_flags: self.argparser.add_argument('-l', '--linenumbers', dest='line_numbers', action='store_true', help='Insert a column of line numbers at the front of the output. Useful when piping to grep or as a simple primary key.') # Input/Output if 'zero' not in self.override_flags: self.argparser.add_argument('--zero', dest='zero_based', action='store_true', help='When interpreting or displaying column numbers, use zero-based numbering instead of the default 1-based numbering.') def _extract_csv_reader_kwargs(self): """ Extracts those from the command-line arguments those would should be passed through to the input CSV reader(s). """ kwargs = {} if self.args.encoding: kwargs['encoding'] = self.args.encoding if self.args.tabs: kwargs['delimiter'] = '\t' elif self.args.delimiter: kwargs['delimiter'] = self.args.delimiter if self.args.quotechar: kwargs['quotechar'] = self.args.quotechar if self.args.quoting: kwargs['quoting'] = self.args.quoting if self.args.doublequote: kwargs['doublequote'] = self.args.doublequote if self.args.escapechar: kwargs['escapechar'] = self.args.escapechar if self.args.maxfieldsize: kwargs['maxfieldsize'] = self.args.maxfieldsize if self.args.skipinitialspace: kwargs['skipinitialspace'] = self.args.skipinitialspace return kwargs def _extract_csv_writer_kwargs(self): """ Extracts those from the command-line arguments those would should be passed through to the output CSV writer. """ kwargs = {} if 'l' not in self.override_flags and self.args.line_numbers: kwargs['line_numbers'] = True return kwargs def _install_exception_handler(self): """ Installs a replacement for sys.excepthook, which handles pretty-printing uncaught exceptions. """ def handler(t, value, traceback): if self.args.verbose: sys.__excepthook__(t, value, traceback) else: # Special case handling for Unicode errors, which behave very strangely # when cast with unicode() if t == UnicodeDecodeError: sys.stderr.write('Your file is not "%s" encoded. Please specify the correct encoding with the -e flag. Use the -v flag to see the complete error.\n' % self.args.encoding) else: sys.stderr.write('%s\n' % unicode(value).encode('utf-8')) sys.excepthook = handler def print_column_names(self): """ Pretty-prints the names and indices of all columns to a file-like object (usually sys.stdout). """ if self.args.no_header_row: raise RequiredHeaderError, 'You cannot use --no-header-row with the -n or --names options.' f = self.args.file output = self.output_file try: zero_based=self.args.zero_based except: zero_based=False rows = CSVKitReader(f, **self.reader_kwargs) column_names = rows.next() for i, c in enumerate(column_names): if not zero_based: i += 1 output.write('%3i: %s\n' % (i, c)) def match_column_identifier(column_names, c, zero_based=False): """ Determine what column a single column id (name or index) matches in a series of column names. Note that integer values are *always* treated as positional identifiers. If you happen to have column names which are also integers, you must specify them using a positional index. """ if isinstance(c, basestring) and not c.isdigit() and c in column_names: return column_names.index(c) else: try: c = int(c) if not zero_based: c -= 1 # Fail out if neither a column name nor an integer except: raise ColumnIdentifierError('Column identifier "%s" is neither an integer, nor a existing column\'s name.' % c) # Fail out if index is 0-based if c < 0: raise ColumnIdentifierError('Column 0 is not valid; columns are 1-based.') # Fail out if index is out of range if c >= len(column_names): raise ColumnIdentifierError('Index %i is beyond the last named column, "%s" at index %i.' % (c, column_names[-1], len(column_names) - 1)) return c def parse_column_identifiers(ids, column_names, zero_based=False, excluded_columns=None): """ Parse a comma-separated list of column indices AND/OR names into a list of integer indices. Ranges of integers can be specified with two integers separated by a '-' or ':' character. Ranges of non-integers (e.g. column names) are not supported. Note: Column indices are 1-based. """ columns = [] # If not specified, start with all columns if not ids: columns = range(len(column_names)) if columns and not excluded_columns: return columns if not columns: for c in ids.split(','): c = c.strip() try: columns.append(match_column_identifier(column_names, c, zero_based)) except ColumnIdentifierError: if ':' in c: a,b = c.split(':',1) elif '-' in c: a,b = c.split('-',1) else: raise try: if a: a = int(a) else: a = 1 if b: b = int(b) + 1 else: b = len(column_names) except ValueError: raise ColumnIdentifierError("Invalid range %s. Ranges must be two integers separated by a - or : character.") for x in range(a,b): columns.append(match_column_identifier(column_names, x, zero_based)) excludes = [] if excluded_columns: for c in excluded_columns.split(','): c = c.strip() try: excludes.append(match_column_identifier(column_names, c, zero_based)) except ColumnIdentifierError: if ':' in c: a,b = c.split(':',1) elif '-' in c: a,b = c.split('-',1) else: raise try: if a: a = int(a) else: a = 1 if b: b = int(b) + 1 else: b = len(column_names) except ValueError: raise ColumnIdentifierError("Invalid range %s. Ranges must be two integers separated by a - or : character.") for x in range(a,b): excludes.append(match_column_identifier(column_names, x, zero_based)) return [c for c in columns if c not in excludes]<|fim▁end|>
If you want to constrain which common args are present, you can pass a string for 'omitflags'. Any argument whose single-letter form is contained in 'omitflags' will be left out of the configured parser. Use 'f' for file. """
<|file_name|>js.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/. */ //! Smart pointers for the JS-managed DOM objects. //! //! The DOM is made up of DOM objects whose lifetime is entirely controlled by //! the whims of the SpiderMonkey garbage collector. The types in this module //! are designed to ensure that any interactions with said Rust types only //! occur on values that will remain alive the entire time. //! //! Here is a brief overview of the important types: //! //! - `JSRef<T>`: a freely-copyable reference to a rooted DOM object. //! - `Root<T>`: a stack-based reference to a rooted DOM object. //! - `JS<T>`: a reference to a DOM object that can automatically be traced by //! the GC when encountered as a field of a Rust structure. //! - `Temporary<T>`: a reference to a DOM object that will remain rooted for //! the duration of its lifetime. //! //! The rule of thumb is as follows: //! //! - All methods return `Temporary<T>`, to ensure the value remains alive //! until it is stored somewhere that is reachable by the GC. //! - All functions take `JSRef<T>` arguments, to ensure that they will remain //! uncollected for the duration of their usage. //! - All DOM structs contain `JS<T>` fields and derive the `JSTraceable` //! trait, to ensure that they are transitively marked as reachable by the GC //! if the enclosing value is reachable. //! - All methods for type `T` are implemented for `JSRef<T>`, to ensure that //! the self value will not be collected for the duration of the method call. //! //! Both `Temporary<T>` and `JS<T>` do not allow access to their inner value //! without explicitly creating a stack-based root via the `root` method //! through the `Rootable<T>` trait. This returns a `Root<T>`, which causes the //! JS-owned value to be uncollectable for the duration of the `Root` object's //! lifetime. A `JSRef<T>` can be obtained from a `Root<T>` by calling the `r` //! method. These `JSRef<T>` values are not allowed to outlive their //! originating `Root<T>`, to ensure that all interactions with the enclosed //! value only occur when said value is uncollectable, and will cause static //! lifetime errors if misused. //! //! Other miscellaneous helper traits: //! //! - `OptionalRootable` and `OptionalOptionalRootable`: make rooting `Option` //! values easy via a `root` method //! - `ResultRootable`: make rooting successful `Result` values easy //! - `TemporaryPushable`: allows mutating vectors of `JS<T>` with new elements //! of `JSRef`/`Temporary` //! - `RootedReference`: makes obtaining an `Option<JSRef<T>>` from an //! `Option<Root<T>>` easy use dom::bindings::trace::JSTraceable; use dom::bindings::trace::RootedVec; use dom::bindings::utils::{Reflector, Reflectable}; use dom::node::Node; use js::jsapi::JSObject; use js::jsval::JSVal; use layout_interface::TrustedNodeAddress; use script_task::STACK_ROOTS; use core::nonzero::NonZero; use libc; use std::cell::{Cell, UnsafeCell}; use std::default::Default; use std::intrinsics::return_address; use std::marker::PhantomData; use std::ops::Deref; /// An unrooted, JS-owned value. Must not be held across a GC. /// /// This is used in particular to wrap pointers extracted from a reflector. #[must_root] pub struct Unrooted<T> { ptr: NonZero<*const T> } impl<T: Reflectable> Unrooted<T> { /// Create a new JS-owned value wrapped from a raw Rust pointer. pub unsafe fn from_raw(raw: *const T) -> Unrooted<T> { assert!(!raw.is_null()); Unrooted { ptr: NonZero::new(raw) } } /// Create a new unrooted value from a `JS<T>`. #[allow(unrooted_must_root)] pub fn from_js(ptr: JS<T>) -> Unrooted<T> { Unrooted { ptr: ptr.ptr } } /// Create a new unrooted value from a `Temporary<T>`. #[allow(unrooted_must_root)] pub fn from_temporary(ptr: Temporary<T>) -> Unrooted<T> { Unrooted::from_js(ptr.inner) } /// Get the `Reflector` for this pointer. pub fn reflector<'a>(&'a self) -> &'a Reflector { unsafe { (**self.ptr).reflector() } } /// Returns an unsafe pointer to the interior of this object. pub unsafe fn unsafe_get(&self) -> *const T { *self.ptr } } impl<T: Reflectable> Rootable<T> for Unrooted<T> { /// Create a stack-bounded root for this value. fn root(&self) -> Root<T> { STACK_ROOTS.with(|ref collection| { let RootCollectionPtr(collection) = collection.get().unwrap(); unsafe { Root::new(&*collection, self.ptr) } }) } } impl<T> Copy for Unrooted<T> {} impl<T> Clone for Unrooted<T> { fn clone(&self) -> Unrooted<T> { *self } } /// A type that represents a JS-owned value that is rooted for the lifetime of /// this value. Importantly, it requires explicit rooting in order to interact /// with the inner value. Can be assigned into JS-owned member fields (i.e. /// `JS<T>` types) safely via the `JS<T>::assign` method or /// `OptionalSettable::assign` (for `Option<JS<T>>` fields). #[allow(unrooted_must_root)] pub struct Temporary<T> { inner: JS<T>, /// On-stack JS pointer to assuage conservative stack scanner _js_ptr: *mut JSObject, } impl<T> Clone for Temporary<T> { fn clone(&self) -> Temporary<T> { Temporary { inner: self.inner, _js_ptr: self._js_ptr, } } } impl<T> PartialEq for Temporary<T> { fn eq(&self, other: &Temporary<T>) -> bool { self.inner == other.inner } } impl<T: Reflectable> Temporary<T> { /// Create a new `Temporary` value from an unrooted value. #[allow(unrooted_must_root)] pub fn from_unrooted(unrooted: Unrooted<T>) -> Temporary<T> { Temporary { inner: JS { ptr: unrooted.ptr }, _js_ptr: unrooted.reflector().get_jsobject(), } } /// Create a new `Temporary` value from a rooted value. #[allow(unrooted_must_root)] pub fn from_rooted<U: Assignable<T>>(root: U) -> Temporary<T> { let inner = JS::from_rooted(root); Temporary { inner: inner, _js_ptr: inner.reflector().get_jsobject(), } } } impl<T: Reflectable> Rootable<T> for Temporary<T> { /// Create a stack-bounded root for this value. fn root(&self) -> Root<T> { self.inner.root() } } /// A traced reference to a DOM object. Must only be used as a field in other /// DOM objects. #[must_root] pub struct JS<T> { ptr: NonZero<*const T> } impl<T> JS<T> { /// Returns `LayoutJS<T>` containing the same pointer. pub unsafe fn to_layout(self) -> LayoutJS<T> { LayoutJS { ptr: self.ptr.clone() } } } /// An unrooted reference to a DOM object for use in layout. `Layout*Helpers` /// traits must be implemented on this. pub struct LayoutJS<T> { ptr: NonZero<*const T> } impl<T: Reflectable> LayoutJS<T> { /// Get the reflector. pub unsafe fn get_jsobject(&self) -> *mut JSObject { (**self.ptr).reflector().get_jsobject() } } impl<T> Copy for JS<T> {} impl<T> Copy for LayoutJS<T> {} impl<T> PartialEq for JS<T> { #[allow(unrooted_must_root)] fn eq(&self, other: &JS<T>) -> bool { self.ptr == other.ptr } } impl<T> PartialEq for LayoutJS<T> { #[allow(unrooted_must_root)] fn eq(&self, other: &LayoutJS<T>) -> bool { self.ptr == other.ptr } } impl <T> Clone for JS<T> { #[inline] fn clone(&self) -> JS<T> { JS { ptr: self.ptr.clone() } }<|fim▁hole|> impl <T> Clone for LayoutJS<T> { #[inline] fn clone(&self) -> LayoutJS<T> { LayoutJS { ptr: self.ptr.clone() } } } impl LayoutJS<Node> { /// Create a new JS-owned value wrapped from an address known to be a /// `Node` pointer. pub unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> LayoutJS<Node> { let TrustedNodeAddress(addr) = inner; LayoutJS { ptr: NonZero::new(addr as *const Node) } } } impl<T: Reflectable> Rootable<T> for JS<T> { /// Root this JS-owned value to prevent its collection as garbage. fn root(&self) -> Root<T> { STACK_ROOTS.with(|ref collection| { let RootCollectionPtr(collection) = collection.get().unwrap(); unsafe { Root::new(&*collection, self.ptr) } }) } } impl<U: Reflectable> JS<U> { /// Create a `JS<T>` from any JS-managed pointer. pub fn from_rooted<T: Assignable<U>>(root: T) -> JS<U> { unsafe { root.get_js() } } } //XXXjdm This is disappointing. This only gets called from trace hooks, in theory, // so it's safe to assume that self is rooted and thereby safe to access. impl<T: Reflectable> Reflectable for JS<T> { fn reflector<'a>(&'a self) -> &'a Reflector { unsafe { (**self.ptr).reflector() } } } /// A trait to be implemented for JS-managed types that can be stored in /// mutable member fields. /// /// Do not implement this trait yourself. pub trait HeapGCValue: JSTraceable { } impl HeapGCValue for JSVal { } impl<T: Reflectable> HeapGCValue for JS<T> { } /// A holder that provides interior mutability for GC-managed values such as /// `JSVal` and `JS<T>`. /// /// Must be used in place of traditional interior mutability to ensure proper /// GC barriers are enforced. #[must_root] #[jstraceable] pub struct MutHeap<T: HeapGCValue+Copy> { val: Cell<T>, } impl<T: HeapGCValue+Copy> MutHeap<T> { /// Create a new `MutHeap`. pub fn new(initial: T) -> MutHeap<T> { MutHeap { val: Cell::new(initial), } } /// Set this `MutHeap` to the given value, calling write barriers as /// appropriate. pub fn set(&self, val: T) { self.val.set(val) } /// Set the value in this `MutHeap`, calling read barriers as appropriate. pub fn get(&self) -> T { self.val.get() } } /// A mutable holder for GC-managed values such as `JSval` and `JS<T>`, with /// nullability represented by an enclosing Option wrapper. Must be used in /// place of traditional internal mutability to ensure that the proper GC /// barriers are enforced. #[must_root] #[jstraceable] pub struct MutNullableHeap<T: HeapGCValue+Copy> { ptr: Cell<Option<T>> } impl<T: HeapGCValue+Copy> MutNullableHeap<T> { /// Create a new `MutNullableHeap`. pub fn new(initial: Option<T>) -> MutNullableHeap<T> { MutNullableHeap { ptr: Cell::new(initial) } } /// Set this `MutNullableHeap` to the given value, calling write barriers /// as appropriate. pub fn set(&self, val: Option<T>) { self.ptr.set(val); } /// Retrieve a copy of the current optional inner value. pub fn get(&self) -> Option<T> { self.ptr.get() } } impl<T: Reflectable> MutNullableHeap<JS<T>> { /// Retrieve a copy of the current inner value. If it is `None`, it is /// initialized with the result of `cb` first. pub fn or_init<F>(&self, cb: F) -> Temporary<T> where F: FnOnce() -> Temporary<T> { match self.get() { Some(inner) => Temporary::from_rooted(inner), None => { let inner = cb(); self.set(Some(JS::from_rooted(inner.clone()))); inner }, } } /// Retrieve a copy of the inner optional `JS<T>` as `LayoutJS<T>`. /// For use by layout, which can't use safe types like Temporary. pub unsafe fn get_inner_as_layout(&self) -> Option<LayoutJS<T>> { self.ptr.get().map(|js| js.to_layout()) } } impl<T: HeapGCValue+Copy> Default for MutNullableHeap<T> { fn default() -> MutNullableHeap<T> { MutNullableHeap { ptr: Cell::new(None) } } } impl<T: Reflectable> JS<T> { /// Store an unrooted value in this field. This is safe under the /// assumption that JS<T> values are only used as fields in DOM types that /// are reachable in the GC graph, so this unrooted value becomes /// transitively rooted for the lifetime of its new owner. pub fn assign(&mut self, val: Temporary<T>) { *self = val.inner.clone(); } } impl<T: Reflectable> LayoutJS<T> { /// Returns an unsafe pointer to the interior of this JS object. This is /// the only method that be safely accessed from layout. (The fact that /// this is unsafe is what necessitates the layout wrappers.) pub unsafe fn unsafe_get(&self) -> *const T { *self.ptr } } /// Get an `Option<JSRef<T>>` out of an `Option<Root<T>>` pub trait RootedReference<T> { /// Obtain a safe optional reference to the wrapped JS owned-value that /// cannot outlive the lifetime of this root. fn r<'a>(&'a self) -> Option<JSRef<'a, T>>; } impl<T: Reflectable> RootedReference<T> for Option<Root<T>> { fn r<'a>(&'a self) -> Option<JSRef<'a, T>> { self.as_ref().map(|root| root.r()) } } /// Get an `Option<Option<JSRef<T>>>` out of an `Option<Option<Root<T>>>` pub trait OptionalRootedReference<T> { /// Obtain a safe optional optional reference to the wrapped JS owned-value /// that cannot outlive the lifetime of this root. fn r<'a>(&'a self) -> Option<Option<JSRef<'a, T>>>; } impl<T: Reflectable> OptionalRootedReference<T> for Option<Option<Root<T>>> { fn r<'a>(&'a self) -> Option<Option<JSRef<'a, T>>> { self.as_ref().map(|inner| inner.r()) } } /// Trait that allows extracting a `JS<T>` value from a variety of /// rooting-related containers, which in general is an unsafe operation since /// they can outlive the rooted lifetime of the original value. pub trait Assignable<T> { /// Extract an unrooted `JS<T>`. unsafe fn get_js(&self) -> JS<T>; } impl<T> Assignable<T> for JS<T> { unsafe fn get_js(&self) -> JS<T> { self.clone() } } impl<'a, T: Reflectable> Assignable<T> for JSRef<'a, T> { unsafe fn get_js(&self) -> JS<T> { JS { ptr: self.ptr } } } impl<T: Reflectable> Assignable<T> for Temporary<T> { unsafe fn get_js(&self) -> JS<T> { self.inner.clone() } } /// Root a rootable `Option` type (used for `Option<Temporary<T>>`) pub trait OptionalRootable<T> { /// Root the inner value, if it exists. fn root(&self) -> Option<Root<T>>; } impl<T: Reflectable, U: Rootable<T>> OptionalRootable<T> for Option<U> { fn root(&self) -> Option<Root<T>> { self.as_ref().map(|inner| inner.root()) } } /// Root a rootable `Option<Option>` type (used for `Option<Option<JS<T>>>`) pub trait OptionalOptionalRootable<T> { /// Root the inner value, if it exists. fn root(&self) -> Option<Option<Root<T>>>; } impl<T: Reflectable, U: OptionalRootable<T>> OptionalOptionalRootable<T> for Option<U> { fn root(&self) -> Option<Option<Root<T>>> { self.as_ref().map(|inner| inner.root()) } } /// Root a rootable `Result` type (any of `Temporary<T>` or `JS<T>`) pub trait ResultRootable<T,U> { /// Root the inner value, if it exists. fn root(self) -> Result<Root<T>, U>; } impl<T: Reflectable, U, V: Rootable<T>> ResultRootable<T, U> for Result<V, U> { fn root(self) -> Result<Root<T>, U> { self.map(|inner| inner.root()) } } /// Root a rootable type. pub trait Rootable<T> { /// Root the value. fn root(&self) -> Root<T>; } /// Provides a facility to push unrooted values onto lists of rooted values. /// This is safe under the assumption that said lists are reachable via the GC /// graph, and therefore the new values are transitively rooted for the /// lifetime of their new owner. pub trait TemporaryPushable<T> { /// Push a new value onto this container. fn push_unrooted(&mut self, val: &T); /// Insert a new value into this container. fn insert_unrooted(&mut self, index: usize, val: &T); } impl<T: Assignable<U>, U: Reflectable> TemporaryPushable<T> for Vec<JS<U>> { fn push_unrooted(&mut self, val: &T) { self.push(unsafe { val.get_js() }); } fn insert_unrooted(&mut self, index: usize, val: &T) { self.insert(index, unsafe { val.get_js() }); } } /// An opaque, LIFO rooting mechanism. This tracks roots and ensures that they /// are destructed in a LIFO order. /// /// See also [*Exact Stack Rooting - Storing a GCPointer on the CStack*] /// (https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Internals/GC/Exact_Stack_Rooting). #[no_move] pub struct RootCollection { roots: UnsafeCell<RootedVec<*mut JSObject>>, } /// A pointer to a RootCollection, for use in global variables. pub struct RootCollectionPtr(pub *const RootCollection); impl Copy for RootCollectionPtr {} impl Clone for RootCollectionPtr { fn clone(&self) -> RootCollectionPtr { *self } } impl RootCollection { /// Create an empty collection of roots pub fn new() -> RootCollection { let addr = unsafe { return_address() as *const libc::c_void }; RootCollection { roots: UnsafeCell::new(RootedVec::new_with_destination_address(addr)), } } /// Track a stack-based root as a pointer to ensure LIFO root ordering. fn root<'b>(&self, untracked_js_ptr: *mut JSObject) { unsafe { let roots = self.roots.get(); (*roots).push(untracked_js_ptr); debug!(" rooting {:?}", untracked_js_ptr); } } /// Stop tracking a stack-based root, asserting if LIFO root ordering has /// been violated fn unroot<'b, T: Reflectable>(&self, rooted: &Root<T>) { unsafe { let roots = self.roots.get(); let unrooted = (*roots).pop().unwrap(); debug!("unrooted {:?} (expecting {:?}", unrooted, rooted.js_ptr); assert!(unrooted == rooted.js_ptr); } } } /// A rooted reference to a DOM object. /// /// The JS value is pinned for the duration of this object's lifetime; roots /// are additive, so this object's destruction will not invalidate other roots /// for the same JS value. `Root`s cannot outlive the associated /// `RootCollection` object. Attempts to transfer ownership of a `Root` via /// moving will trigger dynamic unrooting failures due to incorrect ordering. #[no_move] pub struct Root<T: Reflectable> { /// List that ensures correct dynamic root ordering root_list: &'static RootCollection, /// Reference to rooted value that must not outlive this container ptr: NonZero<*const T>, /// On-stack JS pointer to assuage conservative stack scanner js_ptr: *mut JSObject, } impl<T: Reflectable> Root<T> { /// Create a new stack-bounded root for the provided JS-owned value. /// It cannot not outlive its associated `RootCollection`, and it contains /// a `JSRef` which cannot outlive this new `Root`. #[inline] fn new(roots: &'static RootCollection, unrooted: NonZero<*const T>) -> Root<T> { let js_ptr = unsafe { (**unrooted).reflector().get_jsobject() }; roots.root(js_ptr); Root { root_list: roots, ptr: unrooted, js_ptr: js_ptr, } } /// Obtain a safe reference to the wrapped JS owned-value that cannot /// outlive the lifetime of this root. pub fn r<'b>(&'b self) -> JSRef<'b, T> { JSRef { ptr: self.ptr, chain: PhantomData, } } /// Obtain an unsafe reference to the wrapped JS owned-value that can /// outlive the lifetime of this root. /// /// DO NOT CALL. pub fn get_unsound_ref_forever<'b>(&self) -> JSRef<'b, T> { JSRef { ptr: self.ptr, chain: PhantomData, } } } impl<T: Reflectable> Drop for Root<T> { fn drop(&mut self) { self.root_list.unroot(self); } } impl<'a, T: Reflectable> Deref for JSRef<'a, T> { type Target = T; fn deref<'b>(&'b self) -> &'b T { unsafe { &**self.ptr } } } /// A reference to a DOM object that is guaranteed to be alive. This is freely /// copyable. pub struct JSRef<'a, T> { ptr: NonZero<*const T>, chain: PhantomData<&'a ()>, } impl<'a, T> Copy for JSRef<'a, T> {} impl<'a, T> Clone for JSRef<'a, T> { fn clone(&self) -> JSRef<'a, T> { JSRef { ptr: self.ptr.clone(), chain: self.chain, } } } impl<'a, 'b, T> PartialEq<JSRef<'b, T>> for JSRef<'a, T> { fn eq(&self, other: &JSRef<T>) -> bool { self.ptr == other.ptr } } impl<'a, T: Reflectable> JSRef<'a, T> { /// Returns the inner pointer directly. pub fn extended_deref(self) -> &'a T { unsafe { &**self.ptr } } } impl<'a, T: Reflectable> Reflectable for JSRef<'a, T> { fn reflector<'b>(&'b self) -> &'b Reflector { (**self).reflector() } }<|fim▁end|>
}
<|file_name|>bind_polyfill.js<|end_file_name|><|fim▁begin|>Function.prototype.bind = Function.prototype.bind || function (target) { var self = this; return function (args) { if (!(args instanceof Array)) { args = [args]; } self.apply(target, args); <|fim▁hole|>};<|fim▁end|>
};
<|file_name|>fake_features.go<|end_file_name|><|fim▁begin|>// Code generated by client-gen. DO NOT EDIT. package fake import ( config_v1 "github.com/openshift/api/config/v1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" testing "k8s.io/client-go/testing" ) // FakeFeatures implements FeaturesInterface type FakeFeatures struct { Fake *FakeConfigV1 } var featuresResource = schema.GroupVersionResource{Group: "config.openshift.io", Version: "v1", Resource: "features"} var featuresKind = schema.GroupVersionKind{Group: "config.openshift.io", Version: "v1", Kind: "Features"} // Get takes name of the features, and returns the corresponding features object, and an error if there is any. func (c *FakeFeatures) Get(name string, options v1.GetOptions) (result *config_v1.Features, err error) { obj, err := c.Fake. Invokes(testing.NewRootGetAction(featuresResource, name), &config_v1.Features{}) if obj == nil { return nil, err } return obj.(*config_v1.Features), err } // List takes label and field selectors, and returns the list of Features that match those selectors. func (c *FakeFeatures) List(opts v1.ListOptions) (result *config_v1.FeaturesList, err error) { obj, err := c.Fake. Invokes(testing.NewRootListAction(featuresResource, featuresKind, opts), &config_v1.FeaturesList{}) if obj == nil { return nil, err } label, _, _ := testing.ExtractFromListOptions(opts) if label == nil { label = labels.Everything() } list := &config_v1.FeaturesList{ListMeta: obj.(*config_v1.FeaturesList).ListMeta} for _, item := range obj.(*config_v1.FeaturesList).Items { if label.Matches(labels.Set(item.Labels)) { list.Items = append(list.Items, item) } } return list, err } // Watch returns a watch.Interface that watches the requested features. func (c *FakeFeatures) Watch(opts v1.ListOptions) (watch.Interface, error) { return c.Fake. InvokesWatch(testing.NewRootWatchAction(featuresResource, opts)) } // Create takes the representation of a features and creates it. Returns the server's representation of the features, and an error, if there is any.<|fim▁hole|> return nil, err } return obj.(*config_v1.Features), err } // Update takes the representation of a features and updates it. Returns the server's representation of the features, and an error, if there is any. func (c *FakeFeatures) Update(features *config_v1.Features) (result *config_v1.Features, err error) { obj, err := c.Fake. Invokes(testing.NewRootUpdateAction(featuresResource, features), &config_v1.Features{}) if obj == nil { return nil, err } return obj.(*config_v1.Features), err } // UpdateStatus was generated because the type contains a Status member. // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). func (c *FakeFeatures) UpdateStatus(features *config_v1.Features) (*config_v1.Features, error) { obj, err := c.Fake. Invokes(testing.NewRootUpdateSubresourceAction(featuresResource, "status", features), &config_v1.Features{}) if obj == nil { return nil, err } return obj.(*config_v1.Features), err } // Delete takes name of the features and deletes it. Returns an error if one occurs. func (c *FakeFeatures) Delete(name string, options *v1.DeleteOptions) error { _, err := c.Fake. Invokes(testing.NewRootDeleteAction(featuresResource, name), &config_v1.Features{}) return err } // DeleteCollection deletes a collection of objects. func (c *FakeFeatures) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { action := testing.NewRootDeleteCollectionAction(featuresResource, listOptions) _, err := c.Fake.Invokes(action, &config_v1.FeaturesList{}) return err } // Patch applies the patch and returns the patched features. func (c *FakeFeatures) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *config_v1.Features, err error) { obj, err := c.Fake. Invokes(testing.NewRootPatchSubresourceAction(featuresResource, name, data, subresources...), &config_v1.Features{}) if obj == nil { return nil, err } return obj.(*config_v1.Features), err }<|fim▁end|>
func (c *FakeFeatures) Create(features *config_v1.Features) (result *config_v1.Features, err error) { obj, err := c.Fake. Invokes(testing.NewRootCreateAction(featuresResource, features), &config_v1.Features{}) if obj == nil {
<|file_name|>magma_s_init.cpp<|end_file_name|><|fim▁begin|>/* -- MAGMA (version 1.5.0-beta3) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date July 2014 @generated from magma_z_init.cpp normal z -> s, Fri Jul 18 17:34:30 2014 @author Hartwig Anzt<|fim▁hole|> #include <fstream> #include <stdlib.h> #include <string> #include <sstream> #include <iostream> #include <ostream> #include <assert.h> #include <stdio.h> #include "../include/magmasparse_s.h" #include "../../include/magma.h" #include "../include/mmio.h" using namespace std; /** Purpose ------- Initialize a magma_s_vector. Arguments --------- @param x magma_s_vector vector to initialize @param mem_loc magma_location_t memory for vector @param num_rows magma_int_t desired length of vector @param values float entries in vector @ingroup magmasparse_saux ********************************************************************/ magma_int_t magma_s_vinit( magma_s_vector *x, magma_location_t mem_loc, magma_int_t num_rows, float values ){ x->memory_location = Magma_CPU; x->num_rows = num_rows; x->nnz = num_rows; if( mem_loc == Magma_CPU ){ x->memory_location = Magma_CPU; magma_smalloc_cpu( &x->val, num_rows ); if ( x->val == NULL ) return MAGMA_ERR_HOST_ALLOC; for( magma_int_t i=0; i<num_rows; i++) x->val[i] = values; return MAGMA_SUCCESS; } else if( mem_loc == Magma_DEV ){ x->memory_location = Magma_DEV; float *tmp; magma_smalloc_cpu( &tmp, num_rows ); if ( tmp == NULL ) return MAGMA_ERR_HOST_ALLOC; for( magma_int_t i=0; i<num_rows; i++) tmp[i] = values; if (MAGMA_SUCCESS != magma_smalloc( &x->val, x->num_rows)) return MAGMA_ERR_DEVICE_ALLOC; // data transfer magma_ssetvector( x->num_rows, tmp, 1, x->val, 1 ); magma_free_cpu(tmp); return MAGMA_SUCCESS; } return MAGMA_SUCCESS; }<|fim▁end|>
*/
<|file_name|>shard.go<|end_file_name|><|fim▁begin|>// Copyright (c) 2018 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. //<|fim▁hole|>// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package filter import ( "github.com/m3db/m3/src/aggregator/sharding" "github.com/m3db/m3/src/msg/producer" ) type shardSetFilter struct { shardSet sharding.ShardSet } // NewShardSetFilter creates a filter based on ShardSet. func NewShardSetFilter(shardSet sharding.ShardSet) producer.FilterFunc { f := shardSetFilter{shardSet: shardSet} return f.Filter } func (f shardSetFilter) Filter(m producer.Message) bool { _, ok := f.shardSet[m.Shard()] return ok }<|fim▁end|>
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
<|file_name|>SearchBar.styles.ts<|end_file_name|><|fim▁begin|>/* * @author Stéphane LaFlèche <[email protected]> * @copyright 2009-2021 Vanilla Forums Inc. * @license GPL-2.0-only */ import { globalVariables } from "@library/styles/globalStyleVars"; import { useThemeCache } from "@library/styles/themeCache"; import { formElementsVariables } from "@library/forms/formElementStyles"; import { ColorsUtils } from "@library/styles/ColorsUtils"; import { absolutePosition, borderRadii, defaultTransition, flexHelper, getVerticalPaddingForTextInput, importantUnit, singleBorder, userSelect, } from "@library/styles/styleHelpers"; import { styleUnit } from "@library/styles/styleUnit"; import { Mixins } from "@library/styles/Mixins"; import { calc, important, percent, px, translateX } from "csx"; import { titleBarVariables } from "@library/headers/TitleBar.variables"; import { buttonGlobalVariables } from "@library/forms/Button.variables"; import { buttonResetMixin } from "@library/forms/buttonMixins"; import { oneColumnVariables } from "@library/layout/Section.variables"; import { shadowHelper } from "@library/styles/shadowHelpers"; import { inputBlockClasses } from "@library/forms/InputBlockStyles"; import { css, CSSObject } from "@emotion/css"; import { inputVariables } from "@library/forms/inputStyles"; import { suggestedTextStyleHelper } from "@library/features/search/suggestedTextStyles"; import { searchResultsVariables } from "@library/features/search/searchResultsStyles"; import { paddingOffsetBasedOnBorderRadius } from "@library/forms/paddingOffsetFromBorderRadius"; import { selectBoxClasses } from "@library/forms/select/selectBoxStyles"; import { SearchBarPresets } from "@library/banner/SearchBarPresets"; import { IBorderRadiusValue } from "@library/styles/cssUtilsTypes"; import { searchBarVariables } from "./SearchBar.variables"; import { metasVariables } from "@library/metas/Metas.variables"; export interface ISearchBarOverwrites { borderRadius?: IBorderRadiusValue; compact?: boolean; preset?: SearchBarPresets; } export const searchBarClasses = useThemeCache((overwrites?: ISearchBarOverwrites) => { const shadow = shadowHelper(); const classesInputBlock = inputBlockClasses(); const vars = searchBarVariables(); const { compact = vars.options.compact, borderRadius = vars.border.radius, preset = vars.options.preset } = overwrites || {}; const globalVars = globalVariables(); const metasVars = metasVariables(); const layoutVars = oneColumnVariables(); const inputVars = inputVariables(); const titleBarVars = titleBarVariables(); const formElementVars = formElementsVariables(); const mediaQueries = layoutVars.mediaQueries(); const borderStyle = overwrites && overwrites.preset ? overwrites.preset : vars.options.preset; const isOuterBordered = borderStyle === SearchBarPresets.BORDER; const isInsetBordered = borderStyle === SearchBarPresets.NO_BORDER; const borderColor = isInsetBordered ? vars.input.bg : vars.border.color; const independentRoot = css({ display: "block", height: percent(100), }); const verticalPadding = getVerticalPaddingForTextInput( vars.sizing.height, inputVars.font.size as number, formElementVars.border.width * 2, ); const calculatedHeight = vars.sizing.height - verticalPadding * 2 - formElementVars.border.width * 2; const borderVars = vars.border || globalVars.border; const paddingOffset = paddingOffsetBasedOnBorderRadius({ radius: borderRadius, extraPadding: vars.search.fullBorderRadius.extraHorizontalPadding, height: vars.sizing.height, side: "right", }); const root = css({ cursor: "pointer", ...{ ".searchBar__placeholder": { color: ColorsUtils.colorOut(vars.placeholder.color), margin: "auto", height: styleUnit(calculatedHeight), lineHeight: styleUnit(calculatedHeight), overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis", top: 0, transform: "none", cursor: "text", // Needed otherwise you can't use copy/paste in the context menu. // @see https://github.com/JedWatson/react-select/issues/612 // @see https://github.com/vanilla/support/issues/3252 pointerEvents: "none", }, ".suggestedTextInput-valueContainer": { ...{ [`.${classesInputBlock.inputText}`]: { height: "auto", }, "& > *": { width: percent(100), }, }, }, ".wrap__control": { width: percent(100), }, ".searchBar__control": { border: 0, backgroundColor: ColorsUtils.colorOut(globalVars.elementaryColors.transparent), width: percent(100), flexBasis: percent(100), ...{ "&.searchBar__control--is-focused": { boxShadow: "none", }, }, }, ".searchBar__value-container": { position: "static", overflow: "auto", cursor: "text", display: "flex", justifyContent: "center", alignItems: "center", lineHeight: styleUnit(globalVars.lineHeights.base * globalVars.fonts.size.medium), fontSize: styleUnit(inputVars.font.size), height: styleUnit(calculatedHeight), "& > div": { width: percent(100), }, }, ".searchBar__indicators": { display: "none", }, ".searchBar__input": { width: percent(100), }, ".searchBar__input input": { margin: 0, height: "auto", minHeight: 0, width: important(`100%`), borderRadius: important(0), lineHeight: styleUnit(globalVars.lineHeights.base * globalVars.fonts.size.medium), }, }, }); const submitButton = css({ ...Mixins.button(compact ? vars.compactSubmitButton : vars.submitButton), margin: "-1px", "&:hover, &:focus": { zIndex: 2, }, paddingRight: importantUnit(buttonGlobalVariables().padding.horizontal + paddingOffset.right), ...mediaQueries.oneColumnDown({ minWidth: 0, }), }); // The styles have been split here so they can be exported to the compatibility styles. const searchResultsStyles = { title: { ...Mixins.font({ ...globalVars.fontSizeAndWeightVars("large", "semiBold"), lineHeight: globalVars.lineHeights.condensed, }), }, meta: { ...Mixins.font(metasVars.font), }, excerpt: { marginTop: styleUnit(searchResultsVariables().excerpt.margin), ...Mixins.font({ ...globalVars.fontSizeAndWeightVars("medium"), color: vars.results.fg, lineHeight: globalVars.lineHeights.excerpt, }), }, }; const results = css({ position: "absolute", width: percent(100), backgroundColor: ColorsUtils.colorOut(vars.results.bg), color: ColorsUtils.colorOut(vars.results.fg), ...borderRadii({ all: Math.min(parseInt(borderRadius.toString()), 6), }), ...{ "&:empty": { display: important("none"), }, ".suggestedTextInput__placeholder": { color: ColorsUtils.colorOut(formElementVars.placeholder.color), }, ".suggestedTextInput-noOptions": { padding: px(12), }, ".suggestedTextInput-head": { ...flexHelper().middleLeft(), justifyContent: "space-between", }, ".suggestedTextInput-option": { ...suggestedTextStyleHelper().option, margin: 0, }, ".suggestedTextInput-menuItems": { margin: 0, padding: 0, }, ".suggestedTextInput-item": { listStyle: "none", ...{ "& + .suggestedTextInput-item": { borderTop: `solid 1px ${globalVars.border.color.toString()}`, }, }, }, ".suggestedTextInput-title": { ...searchResultsStyles.title, }, ".suggestedTextInput-title .suggestedTextInput-searchingFor": { fontWeight: globalVars.fonts.weights.normal, }, }, }); const resultsAsModal = css({ position: "absolute", top: styleUnit(vars.sizing.height), left: 0, overflow: "hidden", boxSizing: "border-box", ...shadow.dropDown(), zIndex: 2, }); const clear = css({ position: "relative", display: "flex", boxSizing: "border-box", height: styleUnit(vars.sizing.height), width: styleUnit(vars.sizing.height), color: ColorsUtils.colorOut(globalVars.mixBgAndFg(0.78)), transform: translateX(`${styleUnit(4)}`), ...{ "&, &.buttonIcon": { border: "none", boxShadow: "none", }, "&:hover": { color: ColorsUtils.colorOut(vars.stateColors.hover), }, "&:focus": { color: ColorsUtils.colorOut(vars.stateColors.focus), }, }, }); const mainConditionalStyles = isInsetBordered ? { padding: `0 ${styleUnit(borderVars.width)}`, } : {}; const main = css({ flexGrow: 1, position: "relative", borderRadius: 0, ...mainConditionalStyles, ...{ "&&.withoutButton.withoutScope": { ...borderRadii({ right: borderRadius, left: borderRadius, }), }, "&&.withButton.withScope": { ...borderRadii({ left: borderRadius, }), }, "&&.withoutButton.withScope": { ...borderRadii({ right: borderRadius, }), }, "&&.withButton.withoutScope": { ...borderRadii({ left: borderRadius, right: 0, }), }, "&.isFocused": { zIndex: isOuterBordered ? 3 : 1, }, "&.isHovered": { zIndex: isOuterBordered ? 3 : undefined, }, }, }); const valueContainerConditionalStyles = isInsetBordered ? { position: "absolute", top: 0, left: 0, height: calc(`100% - 2px`), minHeight: calc(`100% - 2px`), width: calc(`100% - 2px`), margin: styleUnit(1), } : { height: percent(100), }; const valueContainer = css({ ...{ "&&&": { ...valueContainerConditionalStyles, display: "flex", alignItems: "center", backgroundColor: ColorsUtils.colorOut(vars.input.bg), color: ColorsUtils.colorOut(vars.input.fg), cursor: "text", flexWrap: "nowrap", justifyContent: "flex-start", borderRadius: 0, zIndex: isInsetBordered ? 2 : undefined, ...defaultTransition("border-color"), ...Mixins.border({ color: borderColor, }), ...borderRadii({ all: borderRadius, }), }, "&&&:not(.isFocused)": { borderColor: ColorsUtils.colorOut(isInsetBordered ? vars.input.bg : vars.border.color), }, "&&&:not(.isFocused).isHovered": { borderColor: ColorsUtils.colorOut(vars.stateColors.hover), }, [`&&&&.isFocused .${main}`]: { borderColor: ColorsUtils.colorOut(vars.stateColors.hover), }, // -- Text Input Radius -- // Both sides round "&&.inputText.withoutButton.withoutScope": { paddingLeft: styleUnit(vars.searchIcon.gap), ...borderRadii({ all: borderRadius, }), }, // Right side flat "&&.inputText.withButton.withoutScope": { paddingLeft: styleUnit(vars.searchIcon.gap), paddingRight: styleUnit(vars.searchIcon.gap), ...borderRadii({ left: borderRadius, right: 0, }), }, [`&&.inputText.withButton.withoutScope .${clear}`]: { ...absolutePosition.topRight(), bottom: 0, ...Mixins.margin({ vertical: "auto", }), transform: translateX(styleUnit(vars.border.width * 2)), }, // Both sides flat "&&.inputText.withButton.withScope": { ...borderRadii({ left: 0, }), }, // Left side flat "&&.inputText.withoutButton.withScope:not(.compactScope)": { paddingRight: styleUnit(vars.searchIcon.gap), }, "&&.inputText.withoutButton.withScope": { ...borderRadii({ right: borderRadius, left: 0, }), }, }, } as CSSObject); // Has a search button attached. const compoundValueContainer = css({ ...{ "&&": { borderTopRightRadius: important(0), borderBottomRightRadius: important(0), }, }, }); const actionButton = css({ marginLeft: -borderVars.width, }); const label = css({ display: "flex", alignItems: "center", justifyContent: "flex-start", }); const scopeSeparatorStyle = isOuterBordered ? { display: "none", } : { ...absolutePosition.topRight(), bottom: 0, margin: "auto 0", height: percent(90), width: styleUnit(borderVars.width), borderRight: singleBorder({ color: borderVars.color, }), }; const scopeSeparator = css(scopeSeparatorStyle); const content = css({ display: "flex", alignItems: "stretch", justifyContent: "flex-start", position: "relative", backgroundColor: ColorsUtils.colorOut(vars.input.bg), width: percent(100), height: percent(100), ...{ "&&.withoutButton.withoutScope": { ...borderRadii({ all: borderRadius, }), }, "&&.withButton.withScope": {}, "&&.withoutButton.withScope": { ...borderRadii({ all: borderRadius, }), }, "&&.withButton.withoutScope": { ...borderRadii({ left: borderRadius, right: 0, }), }, [`&.hasFocus .${scopeSeparator}`]: { display: "none", }, [`&.hasFocus .${valueContainer}`]: { borderColor: ColorsUtils.colorOut(vars.stateColors.focus), }, }, }); // special selector const heading = css({ ...{ "&&": { marginBottom: styleUnit(vars.heading.margin), }, }, }); const icon = css({}); const iconContainer = (alignRight?: boolean) => { const { compact = false } = overwrites || {}; const horizontalPosition = styleUnit(compact ? vars.scope.compact.padding : vars.scope.padding); const conditionalStyle = alignRight ? { right: horizontalPosition, } : { left: horizontalPosition, }; return css({ ...buttonResetMixin(), position: "absolute", top: 0, bottom: 0, ...conditionalStyle, height: percent(100), display: "flex", alignItems: "center", justifyContent: "center", zIndex: 5, outline: 0, color: ColorsUtils.colorOut(vars.searchIcon.fg), ...{ [`.${icon}`]: { width: styleUnit(vars.searchIcon.width), height: styleUnit(vars.searchIcon.height), }, [`&&& + .searchBar-valueContainer`]: { paddingLeft: styleUnit(vars.searchIcon.gap), }, "&:hover": { color: ColorsUtils.colorOut(vars.stateColors.hover), }, "&:focus": { color: ColorsUtils.colorOut(vars.stateColors.focus), }, }, }); }; const iconContainerBigInput = css({ ...{ "&&": { height: styleUnit(vars.sizing.height), }, }, }); const menu = css({ display: "flex", alignItems: "flex-start", justifyContent: "flex-start", ...{ "&.hasFocus .searchBar-valueContainer": { borderColor: ColorsUtils.colorOut(vars.stateColors.focus), }, "&&": { position: "relative", }, ".searchBar__menu-list": { maxHeight: calc(`100vh - ${styleUnit(titleBarVars.sizing.height)}`), width: percent(100), }, ".searchBar__input": { color: ColorsUtils.colorOut(globalVars.mainColors.fg), width: percent(100), display: important("block"), ...{ input: { width: important(percent(100).toString()), lineHeight: globalVars.lineHeights.base, }, }, }, ".suggestedTextInput-menu": { borderRadius: styleUnit(globalVars.border.radius), marginTop: styleUnit(-formElementVars.border.width), marginBottom: styleUnit(-formElementVars.border.width), }, "&:empty": { display: "none", }, }, }); const { selectBoxDropdown, buttonIcon } = selectBoxClasses(); const scopeSelect = css({ display: "flex", width: calc("100%"), height: calc("100%"), justifyContent: "center", alignItems: "stretch", ...{ [`.${selectBoxDropdown}`]: { position: "relative", padding: isInsetBordered ? styleUnit(vars.border.width) : undefined, width: percent(100), height: percent(100), }, }, }); const scopeToggleConditionalStyles: CSSObject = isInsetBordered ? { position: "absolute", top: 0, left: 0, height: calc(`100% - 2px`), width: calc(`100% - 2px`), margin: styleUnit(vars.noBorder.offset), } : { width: percent(100), height: percent(100), }; const scopeToggle = css({ display: "flex", justifyContent: "stretch", alignItems: "center", lineHeight: "2em", flexWrap: "nowrap", ...scopeToggleConditionalStyles, ...Mixins.border({ color: borderColor, }), ...userSelect(), backgroundColor: ColorsUtils.colorOut(globalVars.mainColors.bg), ...Mixins.padding({ horizontal: compact ? vars.scope.compact.padding : vars.scope.padding, }), outline: 0, ...borderRadii({ left: borderRadius, right: 0, }), ...{ [`.${buttonIcon}`]: { width: styleUnit(vars.scopeIcon.width), flexBasis: styleUnit(vars.scopeIcon.width), height: styleUnit(vars.scopeIcon.width * vars.scopeIcon.ratio), margin: "0 0 0 auto", color: ColorsUtils.colorOut(vars.input.fg), }, "&:focus, &:hover, &:active, &.focus-visible": { zIndex: 3, }, "&:hover": { borderColor: ColorsUtils.colorOut(vars.stateColors.hover), }, "&:active": { borderColor: ColorsUtils.colorOut(vars.stateColors.active), }, "&:focus, &.focus-visible": { borderColor: ColorsUtils.colorOut(vars.stateColors.focus), }, // Nested above doesn't work [`&:focus .${scopeSeparator}, &:hover .${scopeSeparator}, &:active .${scopeSeparator}, &.focus-visible .${scopeSeparator}`]: { display: "none", }, }, }); const scopeLabelWrap = css({ display: "flex", textOverflow: "ellipsis", whiteSpace: "nowrap", overflow: "hidden", lineHeight: 2, color: ColorsUtils.colorOut(vars.input.fg), }); const scope = css({ position: "relative", minHeight: styleUnit(vars.sizing.height), width: styleUnit(compact ? vars.scope.compact.width : vars.scope.width), flexBasis: styleUnit(compact ? vars.scope.compact.width : vars.scope.width), display: "flex", alignItems: "stretch", justifyContent: "flex-start", backgroundColor: ColorsUtils.colorOut(globalVars.mainColors.bg), paddingRight: isInsetBordered ? styleUnit(vars.border.width) : undefined, transform: isOuterBordered ? translateX(styleUnit(vars.border.width)) : undefined, zIndex: isOuterBordered ? 2 : undefined, ...borderRadii({ left: borderRadius, right: 0, }), ...{ [` &.isOpen .${scopeSeparator}, &.isActive .${scopeSeparator} `]: { display: "none", }, [`.${scopeToggle}`]: { ...borderRadii({ left: borderRadius,<|fim▁hole|> }), }, [`&.isCompact .${scopeToggle}`]: { paddingLeft: styleUnit(12), paddingRight: styleUnit(12), }, [`& + .${main}`]: { maxWidth: calc(`100% - ${styleUnit(compact ? vars.scope.compact.width : vars.scope.width)}`), flexBasis: calc(`100% - ${styleUnit(compact ? vars.scope.compact.width : vars.scope.width)}`), }, }, }); const wrap = css({ display: "flex", height: percent(100), width: percent(100), }); const form = css({ display: "flex", width: percent(100), flexWrap: "nowrap", alignItems: "center", }); const closeButton = css({ marginLeft: styleUnit(6), borderRadius: "6px", }); const compactIcon = css({ ...{ "&&": { width: styleUnit(vars.searchIcon.width), height: styleUnit(vars.searchIcon.height), }, }, }); const standardContainer = css({ display: "block", position: "relative", height: styleUnit(vars.sizing.height), marginBottom: styleUnit(globalVars.gutter.size), }); const firstItemBorderTop = css({ borderTop: `solid 1px ${globalVars.border.color.toString()}`, }); return { root, submitButton, independentRoot, compoundValueContainer, valueContainer, actionButton, label, clear, form, content, heading, iconContainer, iconContainerBigInput, icon, results, resultsAsModal, menu, searchResultsStyles, // for compatibility scope, scopeToggle, scopeSeparator, scopeSelect, scopeLabelWrap, closeButton, wrap, main, compactIcon, standardContainer, firstItemBorderTop, }; });<|fim▁end|>
right: 0,
<|file_name|>key_loader.py<|end_file_name|><|fim▁begin|>def load_keys(filepath): """ Loads the Twitter API keys into a dict.<|fim▁hole|> """ try: keys_file = open(filepath, 'rb') keys = {} for line in keys_file: key, value = line.split('=') keys[key.strip()] = value.strip() except IOError: message = ('File {} cannot be opened.' ' Check that it exists and is binary.') print message.format(filepath) raise except: print "Error opening or unpickling file." raise return keys<|fim▁end|>
:param filepath: file path to config file with Twitter API keys. :return: keys_dict :raise: IOError
<|file_name|>sink.spec.js<|end_file_name|><|fim▁begin|>'use strict'; /* jshint ignore:start */ /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ /* jshint ignore:end */ var Holodeck = require('../../../holodeck'); /* jshint ignore:line */ var Request = require( '../../../../../lib/http/request'); /* jshint ignore:line */ var Response = require( '../../../../../lib/http/response'); /* jshint ignore:line */ var RestException = require( '../../../../../lib/base/RestException'); /* jshint ignore:line */ var Twilio = require('../../../../../lib'); /* jshint ignore:line */ var serialize = require( '../../../../../lib/base/serialize'); /* jshint ignore:line */ var client; var holodeck; describe('Sink', function() { beforeEach(function() { holodeck = new Holodeck(); client = new Twilio('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'AUTHTOKEN', { httpClient: holodeck }); }); it('should generate valid fetch request', function(done) { holodeck.mock(new Response(500, {})); var promise = client.events.v1.sinks('DGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch(); promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(RestException.prototype.constructor); done(); }).done(); var sid = 'DGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; var url = `https://events.twilio.com/v1/Sinks/${sid}`; holodeck.assertHasRequest(new Request({ method: 'GET', url: url })); } ); it('should generate valid fetch response', function(done) { var body = { 'status': 'initialized', 'sink_configuration': { 'arn': 'arn:aws:kinesis:us-east-1:111111111:stream/test', 'role_arn': 'arn:aws:iam::111111111:role/Role', 'external_id': '1234567890' }, 'description': 'A Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'date_created': '2015-07-30T20:00:00Z', 'sink_type': 'kinesis', 'date_updated': '2015-07-30T20:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Validate' } }; holodeck.mock(new Response(200, body)); var promise = client.events.v1.sinks('DGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch(); promise.then(function(response) { expect(response).toBeDefined(); done(); }, function() { throw new Error('failed'); }).done(); } ); it('should generate valid create request', function(done) { holodeck.mock(new Response(500, {})); var opts = {'description': 'description', 'sinkConfiguration': {}, 'sinkType': 'kinesis'}; var promise = client.events.v1.sinks.create(opts); promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(RestException.prototype.constructor); done(); }).done(); var url = 'https://events.twilio.com/v1/Sinks'; var values = { 'Description': 'description', 'SinkConfiguration': serialize.object({}), 'SinkType': 'kinesis', }; holodeck.assertHasRequest(new Request({ method: 'POST', url: url, data: values })); } ); it('should generate valid create response', function(done) { var body = { 'status': 'initialized', 'sink_configuration': { 'arn': 'arn:aws:kinesis:us-east-1:111111111:stream/test', 'role_arn': 'arn:aws:iam::111111111:role/Role', 'external_id': '1234567890' }, 'description': 'My Kinesis Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'date_created': '2015-07-30T20:00:00Z', 'sink_type': 'kinesis', 'date_updated': '2015-07-30T20:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Validate' } }; holodeck.mock(new Response(201, body)); var opts = {'description': 'description', 'sinkConfiguration': {}, 'sinkType': 'kinesis'}; var promise = client.events.v1.sinks.create(opts); promise.then(function(response) { expect(response).toBeDefined(); done(); }, function() { throw new Error('failed'); }).done(); } ); it('should generate valid create_segment response', function(done) { var body = { 'status': 'initialized', 'sink_configuration': { 'write_key': 'MY_WRITEKEY' }, 'description': 'My segment Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'date_created': '2015-07-30T20:00:00Z', 'sink_type': 'segment', 'date_updated': '2015-07-30T20:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Validate' } }; holodeck.mock(new Response(201, body)); var opts = {'description': 'description', 'sinkConfiguration': {}, 'sinkType': 'kinesis'}; var promise = client.events.v1.sinks.create(opts); promise.then(function(response) { expect(response).toBeDefined(); done(); }, function() { throw new Error('failed'); }).done(); } ); it('should generate valid remove request', function(done) { holodeck.mock(new Response(500, {})); var promise = client.events.v1.sinks('DGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').remove(); promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(RestException.prototype.constructor); done(); }).done(); var sid = 'DGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; var url = `https://events.twilio.com/v1/Sinks/${sid}`; holodeck.assertHasRequest(new Request({ method: 'DELETE', url: url })); } ); it('should generate valid delete response', function(done) { var body = null; holodeck.mock(new Response(204, body)); var promise = client.events.v1.sinks('DGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').remove(); promise.then(function(response) { expect(response).toBe(true); done(); }, function() { throw new Error('failed'); }).done(); } ); it('should treat the first each arg as a callback', function(done) { var body = { 'sinks': [ { 'status': 'initialized', 'sink_configuration': { 'arn': 'arn:aws:kinesis:us-east-1:111111111:stream/test', 'role_arn': 'arn:aws:iam::111111111:role/Role', 'external_id': '1234567890' }, 'description': 'A Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'date_created': '2015-07-30T19:00:00Z', 'sink_type': 'kinesis', 'date_updated': '2015-07-30T19:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Validate' } }, { 'status': 'initialized', 'sink_configuration': { 'arn': 'arn:aws:kinesis:us-east-1:222222222:stream/test', 'role_arn': 'arn:aws:iam::111111111:role/Role', 'external_id': '1234567890' }, 'description': 'ANOTHER Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab', 'date_created': '2015-07-30T20:00:00Z', 'sink_type': 'kinesis', 'date_updated': '2015-07-30T20:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Validate' } }, { 'status': 'active', 'sink_configuration': { 'destination': 'http://example.org/webhook', 'method': 'POST', 'batch_events': true }, 'description': 'A webhook Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac', 'date_created': '2015-07-30T21:00:00Z', 'sink_type': 'webhook', 'date_updated': '2015-07-30T21:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Validate' } } ], 'meta': { 'page': 0, 'page_size': 20, 'first_page_url': 'https://events.twilio.com/v1/Sinks?PageSize=20&Page=0', 'previous_page_url': null, 'url': 'https://events.twilio.com/v1/Sinks?PageSize=20&Page=0', 'next_page_url': null, 'key': 'sinks' } }; holodeck.mock(new Response(200, body)); client.events.v1.sinks.each(() => done()); } ); it('should treat the second arg as a callback', function(done) { var body = { 'sinks': [ { 'status': 'initialized', 'sink_configuration': { 'arn': 'arn:aws:kinesis:us-east-1:111111111:stream/test', 'role_arn': 'arn:aws:iam::111111111:role/Role', 'external_id': '1234567890' }, 'description': 'A Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'date_created': '2015-07-30T19:00:00Z', 'sink_type': 'kinesis', 'date_updated': '2015-07-30T19:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Validate' } }, { 'status': 'initialized', 'sink_configuration': { 'arn': 'arn:aws:kinesis:us-east-1:222222222:stream/test', 'role_arn': 'arn:aws:iam::111111111:role/Role', 'external_id': '1234567890' }, 'description': 'ANOTHER Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab', 'date_created': '2015-07-30T20:00:00Z', 'sink_type': 'kinesis', 'date_updated': '2015-07-30T20:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Validate' } }, { 'status': 'active', 'sink_configuration': { 'destination': 'http://example.org/webhook', 'method': 'POST', 'batch_events': true }, 'description': 'A webhook Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac', 'date_created': '2015-07-30T21:00:00Z', 'sink_type': 'webhook', 'date_updated': '2015-07-30T21:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Validate' } } ], 'meta': { 'page': 0, 'page_size': 20, 'first_page_url': 'https://events.twilio.com/v1/Sinks?PageSize=20&Page=0', 'previous_page_url': null, 'url': 'https://events.twilio.com/v1/Sinks?PageSize=20&Page=0', 'next_page_url': null, 'key': 'sinks' } }; holodeck.mock(new Response(200, body)); client.events.v1.sinks.each({pageSize: 20}, () => done()); holodeck.assertHasRequest(new Request({ method: 'GET', url: 'https://events.twilio.com/v1/Sinks', params: {PageSize: 20}, })); } ); it('should find the callback in the opts object', function(done) { var body = { 'sinks': [ { 'status': 'initialized', 'sink_configuration': { 'arn': 'arn:aws:kinesis:us-east-1:111111111:stream/test', 'role_arn': 'arn:aws:iam::111111111:role/Role', 'external_id': '1234567890' }, 'description': 'A Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'date_created': '2015-07-30T19:00:00Z', 'sink_type': 'kinesis', 'date_updated': '2015-07-30T19:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Validate' } }, { 'status': 'initialized', 'sink_configuration': { 'arn': 'arn:aws:kinesis:us-east-1:222222222:stream/test', 'role_arn': 'arn:aws:iam::111111111:role/Role', 'external_id': '1234567890' }, 'description': 'ANOTHER Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab', 'date_created': '2015-07-30T20:00:00Z', 'sink_type': 'kinesis', 'date_updated': '2015-07-30T20:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Validate' } }, { 'status': 'active', 'sink_configuration': { 'destination': 'http://example.org/webhook', 'method': 'POST', 'batch_events': true }, 'description': 'A webhook Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac', 'date_created': '2015-07-30T21:00:00Z', 'sink_type': 'webhook', 'date_updated': '2015-07-30T21:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Validate' } } ], 'meta': { 'page': 0, 'page_size': 20, 'first_page_url': 'https://events.twilio.com/v1/Sinks?PageSize=20&Page=0', 'previous_page_url': null, 'url': 'https://events.twilio.com/v1/Sinks?PageSize=20&Page=0', 'next_page_url': null, 'key': 'sinks' } }; holodeck.mock(new Response(200, body)); client.events.v1.sinks.each({callback: () => done()}, () => fail('wrong callback!')); } ); it('should generate valid list request', function(done) { holodeck.mock(new Response(500, {})); var promise = client.events.v1.sinks.list(); promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(RestException.prototype.constructor); done(); }).done(); var url = 'https://events.twilio.com/v1/Sinks'; holodeck.assertHasRequest(new Request({ method: 'GET', url: url })); } ); it('should generate valid read_empty response', function(done) { var body = { 'sinks': [], 'meta': { 'page': 0, 'page_size': 10, 'first_page_url': 'https://events.twilio.com/v1/Sinks?PageSize=10&Page=0', 'previous_page_url': null, 'url': 'https://events.twilio.com/v1/Sinks?PageSize=10&Page=0', 'next_page_url': null, 'key': 'sinks' } }; holodeck.mock(new Response(200, body)); var promise = client.events.v1.sinks.list(); promise.then(function(response) { expect(response).toBeDefined(); done(); }, function() { throw new Error('failed'); }).done(); } ); it('should generate valid read_results response', function(done) { var body = { 'sinks': [ { 'status': 'initialized', 'sink_configuration': { 'arn': 'arn:aws:kinesis:us-east-1:111111111:stream/test', 'role_arn': 'arn:aws:iam::111111111:role/Role', 'external_id': '1234567890' }, 'description': 'A Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'date_created': '2015-07-30T19:00:00Z', 'sink_type': 'kinesis', 'date_updated': '2015-07-30T19:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Validate' } }, { 'status': 'initialized', 'sink_configuration': { 'arn': 'arn:aws:kinesis:us-east-1:222222222:stream/test', 'role_arn': 'arn:aws:iam::111111111:role/Role', 'external_id': '1234567890' }, 'description': 'ANOTHER Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab', 'date_created': '2015-07-30T20:00:00Z', 'sink_type': 'kinesis', 'date_updated': '2015-07-30T20:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Validate' } }, { 'status': 'active', 'sink_configuration': { 'destination': 'http://example.org/webhook', 'method': 'POST', 'batch_events': true }, 'description': 'A webhook Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac', 'date_created': '2015-07-30T21:00:00Z', 'sink_type': 'webhook', 'date_updated': '2015-07-30T21:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Validate' } } ], 'meta': { 'page': 0, 'page_size': 20, 'first_page_url': 'https://events.twilio.com/v1/Sinks?PageSize=20&Page=0', 'previous_page_url': null, 'url': 'https://events.twilio.com/v1/Sinks?PageSize=20&Page=0', 'next_page_url': null, 'key': 'sinks' } }; holodeck.mock(new Response(200, body)); var promise = client.events.v1.sinks.list(); promise.then(function(response) { expect(response).toBeDefined(); done(); }, function() { throw new Error('failed'); }).done(); } ); it('should generate valid read_results_in_use response', function(done) { var body = { 'sinks': [ { 'status': 'initialized', 'sink_configuration': { 'arn': 'arn:aws:kinesis:us-east-1:111111111:stream/test', 'role_arn': 'arn:aws:iam::111111111:role/Role', 'external_id': '1234567890' }, 'description': 'A Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'date_created': '2015-07-30T19:00:00Z', 'sink_type': 'kinesis', 'date_updated': '2015-07-30T19:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Validate' } }, { 'status': 'initialized', 'sink_configuration': { 'arn': 'arn:aws:kinesis:us-east-1:222222222:stream/test', 'role_arn': 'arn:aws:iam::111111111:role/Role', 'external_id': '1234567890' }, 'description': 'ANOTHER Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab', 'date_created': '2015-07-30T20:00:00Z', 'sink_type': 'kinesis', 'date_updated': '2015-07-30T20:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Validate' } }, { 'status': 'active', 'sink_configuration': { 'destination': 'http://example.org/webhook', 'method': 'POST', 'batch_events': true }, 'description': 'A webhook Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac', 'date_created': '2015-07-30T21:00:00Z', 'sink_type': 'webhook', 'date_updated': '2015-07-30T21:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Validate' } } ], 'meta': { 'page': 0, 'page_size': 20, 'first_page_url': 'https://events.twilio.com/v1/Sinks?InUse=True&PageSize=20&Page=0',<|fim▁hole|> } }; holodeck.mock(new Response(200, body)); var promise = client.events.v1.sinks.list(); promise.then(function(response) { expect(response).toBeDefined(); done(); }, function() { throw new Error('failed'); }).done(); } ); it('should generate valid read_results_status response', function(done) { var body = { 'sinks': [ { 'status': 'active', 'sink_configuration': { 'destination': 'http://example.org/webhook', 'method': 'POST', 'batch_events': true }, 'description': 'A webhook Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac', 'date_created': '2015-07-30T21:00:00Z', 'sink_type': 'webhook', 'date_updated': '2015-07-30T21:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Validate' } } ], 'meta': { 'page': 0, 'page_size': 20, 'first_page_url': 'https://events.twilio.com/v1/Sinks?Status=active&PageSize=20&Page=0', 'previous_page_url': null, 'url': 'https://events.twilio.com/v1/Sinks?Status=active&PageSize=20&Page=0', 'next_page_url': null, 'key': 'sinks' } }; holodeck.mock(new Response(200, body)); var promise = client.events.v1.sinks.list(); promise.then(function(response) { expect(response).toBeDefined(); done(); }, function() { throw new Error('failed'); }).done(); } ); it('should generate valid update request', function(done) { holodeck.mock(new Response(500, {})); var opts = {'description': 'description'}; var promise = client.events.v1.sinks('DGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').update(opts); promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(RestException.prototype.constructor); done(); }).done(); var sid = 'DGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; var url = `https://events.twilio.com/v1/Sinks/${sid}`; var values = {'Description': 'description', }; holodeck.assertHasRequest(new Request({ method: 'POST', url: url, data: values })); } ); it('should generate valid update response', function(done) { var body = { 'status': 'initialized', 'sink_configuration': { 'arn': 'arn:aws:kinesis:us-east-1:111111111:stream/test', 'role_arn': 'arn:aws:iam::111111111:role/Role', 'external_id': '1234567890' }, 'description': 'My Kinesis Sink', 'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'date_created': '2015-07-30T20:00:00Z', 'sink_type': 'kinesis', 'date_updated': '2015-07-30T20:00:00Z', 'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'links': { 'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Test', 'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Validate' } }; holodeck.mock(new Response(200, body)); var opts = {'description': 'description'}; var promise = client.events.v1.sinks('DGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').update(opts); promise.then(function(response) { expect(response).toBeDefined(); done(); }, function() { throw new Error('failed'); }).done(); } ); });<|fim▁end|>
'previous_page_url': null, 'url': 'https://events.twilio.com/v1/Sinks?InUse=True&PageSize=20&Page=0', 'next_page_url': null, 'key': 'sinks'
<|file_name|>test_chgrp.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright (C) 2012 University of Dundee & Open Microscopy Environment. All Rights Reserved. Copyright 2013 Glencoe Software, Inc. All rights reserved. Use is subject to license terms supplied in LICENSE.txt pytest fixtures used as defined in conftest.py: - gatewaywrapper """ import omero from omero.rtypes import rstring from omero.cmd import State, ERR, OK from omero.callbacks import CmdCallbackI PRIVATE = 'rw----' READONLY = 'rwr---' COLLAB = 'rwrw--' def doChange(gateway, obj_type, obj_ids, group_id, container_id=None, test_should_pass=True, return_complete=True): """ Performs the change-group action, waits on completion and checks that the result is not an error. """ prx = gateway.chgrpObjects(obj_type, obj_ids, group_id, container_id) if not return_complete: return prx cb = CmdCallbackI(gateway.c, prx) try: for i in range(10): cb.loop(20, 500) if prx.getResponse() is not None: break assert prx.getResponse() is not None prx.getStatus() rsp = prx.getResponse() if test_should_pass: assert not isinstance(rsp, ERR), \ "Found ERR when test_should_pass==true: %s (%s) params=%s" \ % (rsp.category, rsp.name, rsp.parameters) assert State.FAILURE not in prx.getStatus().flags else: assert not isinstance(rsp, OK), \ "Found OK when test_should_pass==false: %s" % rsp assert State.FAILURE in prx.getStatus().flags return rsp finally: cb.close(True) def testImageChgrp(gatewaywrapper): """ Create a new group with the User as member. Test move the Image to new group. """ gatewaywrapper.loginAsAuthor() image = gatewaywrapper.createTestImage() ctx = gatewaywrapper.gateway.getAdminService().getEventContext() uuid = ctx.sessionUuid gatewaywrapper.loginAsAdmin() gid = gatewaywrapper.gateway.createGroup( "chgrp-test-%s" % uuid, member_Ids=[ctx.userId], perms=COLLAB) gatewaywrapper.loginAsAuthor() assert gatewaywrapper.gateway.getObject("Image", image.id) is not None # Do the Chgrp doChange(gatewaywrapper.gateway, "Image", [image.getId()], gid) # Image should no-longer be available in current group assert gatewaywrapper.gateway.getObject("Image", image.id) is None, \ "Image should not be available in original group" # Switch to new group - confirm that image is there. gatewaywrapper.gateway.setGroupForSession(gid) img = gatewaywrapper.gateway.getObject("Image", image.id) assert img is not None, "Image should be available in new group" assert img.getDetails().getGroup().id == gid, \ "Image group.id should match new group" <|fim▁hole|> def testDatasetChgrp(gatewaywrapper): """ Create a new group with the User as member. Test move the Dataset/Image to new group. """ gatewaywrapper.loginAsAuthor() dataset = gatewaywrapper.createPDTree(dataset="testDatasetChgrp") image = gatewaywrapper.createTestImage(dataset=dataset) ctx = gatewaywrapper.gateway.getAdminService().getEventContext() uuid = ctx.sessionUuid gatewaywrapper.loginAsAdmin() gid = gatewaywrapper.gateway.createGroup( "chgrp-test-%s" % uuid, member_Ids=[ctx.userId], perms=PRIVATE) gatewaywrapper.loginAsAuthor() assert gatewaywrapper.gateway.getObject("Image", image.id) is not None # Do the Chgrp doChange(gatewaywrapper.gateway, "Dataset", [dataset.id], gid) # Dataset should no-longer be available in current group assert gatewaywrapper.gateway.getObject("Dataset", dataset.id) is None, \ "Dataset should not be available in original group" # Switch to new group - confirm that Dataset, Image is there. gatewaywrapper.gateway.setGroupForSession(gid) ds = gatewaywrapper.gateway.getObject("Dataset", dataset.id) assert ds is not None, "Dataset should be available in new group" img = gatewaywrapper.gateway.getObject("Image", image.id) assert img is not None, "Image should be available in new group" assert img.getDetails().getGroup().id == gid, \ "Image group.id should match new group" def testPDIChgrp(gatewaywrapper): """ Create a new group with the User as member. Test move the Project/Dataset/Image to new group. """ gatewaywrapper.loginAsAuthor() link = gatewaywrapper.createPDTree(project="testPDIChgrp", dataset="testPDIChgrp") dataset = link.getChild() # DatasetWrapper # omero.model.ProjectI - link.getParent() overwritten - returns None project = link.parent image = gatewaywrapper.createTestImage(dataset=dataset) grp = project.details.group ctx = gatewaywrapper.gateway.getAdminService().getEventContext() uuid = ctx.sessionUuid gatewaywrapper.loginAsAdmin() gid = gatewaywrapper.gateway.createGroup( "chgrp-test-%s" % uuid, member_Ids=[ctx.userId], perms=COLLAB) gatewaywrapper.loginAsAuthor() assert gatewaywrapper.gateway.getObject("Image", image.id) is not None try: # Do the Chgrp doChange(gatewaywrapper.gateway, "Project", [project.id.val], gid) # Image should no-longer be available in current group assert gatewaywrapper.gateway.getObject("Image", image.id) is None, \ "Image should not be available in original group" # Switch to new group - confirm that Project, Dataset, Image is there. gatewaywrapper.gateway.setGroupForSession(gid) prj = gatewaywrapper.gateway.getObject("Project", project.id.val) assert prj is not None, "Project should be available in new group" ds = gatewaywrapper.gateway.getObject("Dataset", dataset.id) assert ds is not None, "Dataset should be available in new group" img = gatewaywrapper.gateway.getObject("Image", image.id) assert img is not None, "Image should be available in new group" assert img.getDetails().getGroup().id == gid, \ "Image group.id should match new group" finally: # Change it all back gatewaywrapper.loginAsAuthor() # Do the Chgrp doChange(gatewaywrapper.gateway, "Project", [project.id.val], grp.id.val) # Image should again be available in current group assert gatewaywrapper.gateway.getObject("Image", image.id) \ is not None, "Image should be available in original group" def testTwoDatasetsChgrpToProject(gatewaywrapper): """ Create a new group with the User as member. Image has 2 Dataset Parents. Test move one Dataset to new group. Image does not move. Move 2nd Dataset - Image moves. """ gatewaywrapper.loginAsAuthor() dataset = gatewaywrapper.createPDTree( dataset="testTwoDatasetsChgrpToProject") image = gatewaywrapper.createTestImage(dataset=dataset) orig_gid = dataset.details.group.id.val new_ds = gatewaywrapper.createPDTree( dataset="testTwoDatasetsChgrp-parent2") update = gatewaywrapper.gateway.getUpdateService() link = omero.model.DatasetImageLinkI() link.setParent(omero.model.DatasetI(new_ds.id, False)) link.setChild(omero.model.ImageI(image.id, False)) update.saveObject(link) ctx = gatewaywrapper.gateway.getAdminService().getEventContext() uuid = ctx.sessionUuid gatewaywrapper.loginAsAdmin() gid = gatewaywrapper.gateway.createGroup("chgrp-test-%s" % uuid, member_Ids=[ctx.userId]) gatewaywrapper.loginAsAuthor() assert gatewaywrapper.gateway.getObject("Dataset", dataset.id) is not None # create Project in destination group gatewaywrapper.gateway.setGroupForSession(gid) p = omero.model.ProjectI() p.name = rstring("testTwoDatasetsChgrpToProject") p = gatewaywrapper.gateway.getUpdateService().saveAndReturnObject(p) assert p.details.group.id.val == gid, \ "Project should be created in target group" gatewaywrapper.gateway.setGroupForSession(orig_gid) # switch back # Do the Chgrp with one of the parents doChange(gatewaywrapper.gateway, "Dataset", [new_ds.id], gid) # Dataset should no-longer be available in current group assert gatewaywrapper.gateway.getObject("Dataset", new_ds.id) is None, \ "Dataset should not be available in original group" assert gatewaywrapper.gateway.getObject("Dataset", dataset.getId()) \ is not None, "Other Dataset should still be in original group" # But Image should img = gatewaywrapper.gateway.getObject("Image", image.id) assert img is not None, \ "Image should still be available in original group" # Do the Chgrp with the OTHER parent # switch BEFORE doChange to allow Project link Save gatewaywrapper.gateway.setGroupForSession(gid) doChange(gatewaywrapper.gateway, "Dataset", [dataset.id], gid, container_id=p.id.val) # Confirm that Dataset AND Image is now in new group ctx = gatewaywrapper.gateway.getAdminService().getEventContext() ds = gatewaywrapper.gateway.getObject("Dataset", dataset.id) projects = list(ds.listParents()) assert len(projects) == 1, \ "Dataset should have one parent Project in new group" assert projects[0].getId() == p.id.val, \ "Check Dataset parent is Project created above" assert ds is not None, "Dataset should now be available in new group" assert ds.getDetails().getGroup().id == gid, \ "Dataset group.id should match new group" img = gatewaywrapper.gateway.getObject("Image", image.id) assert img is not None, "Image should now be available in new group" assert img.getDetails().getGroup().id == gid, \ "Image group.id should match new group" def testMultiDatasetDoAll(gatewaywrapper): """ Need to enable chgrp independently of EventContext group being the destination group. Other tests that do not set omero.group require this for DoAll Save to work. """ gatewaywrapper.loginAsAuthor() ctx = gatewaywrapper.gateway.getAdminService().getEventContext() uuid = ctx.sessionUuid update = gatewaywrapper.gateway.getUpdateService() new_ds = omero.model.DatasetI() new_ds.name = rstring("testMultiDatasetDoAll") new_ds = update.saveAndReturnObject(new_ds) new_ds2 = omero.model.DatasetI() new_ds2.name = rstring("testMultiDatasetDoAll2") new_ds2 = update.saveAndReturnObject(new_ds2) # new group gatewaywrapper.loginAsAdmin() gid = gatewaywrapper.gateway.createGroup( "testMultiDatasetDoAll-%s" % uuid, member_Ids=[ctx.userId]) gatewaywrapper.loginAsAuthor() # create Project in new group gatewaywrapper.gateway.SERVICE_OPTS.setOmeroGroup(gid) p = omero.model.ProjectI() p.name = rstring("testMultiChgrp") p = gatewaywrapper.gateway.getUpdateService().saveAndReturnObject( p, gatewaywrapper.gateway.SERVICE_OPTS) assert p.details.group.id.val == gid, \ "Project should be created in target group" # Test that this works whichever group you're in gatewaywrapper.gateway.SERVICE_OPTS.setOmeroGroup(ctx.groupId) dsIds = [new_ds.id.val, new_ds2.id.val] # Chgrp doChange(gatewaywrapper.gateway, "Dataset", dsIds, gid, container_id=p.id.val) # Check all objects in destination group # we can get objects from either group... gatewaywrapper.gateway.SERVICE_OPTS.setOmeroGroup(-1) p = gatewaywrapper.gateway.getObject("Project", p.id.val) datasets = list(p.listChildren()) assert len(datasets) == 2, "Project should have 2 new Datasets" for d in datasets: assert d.details.group.id.val == gid, "Dataset should be in new group" assert d.getId() in dsIds, "Checking Datasets by ID"<|fim▁end|>
<|file_name|>test.js<|end_file_name|><|fim▁begin|>var test = require('tst') var assert = require('assert') var noise = require('..') test('white noise', () => { assert(typeof noise.white() === 'function') }) test('pink noise', () => { assert(typeof noise.pink() === 'function') }) test('brown noise', () => {<|fim▁hole|> assert(typeof noise.pink() === 'function') })<|fim▁end|>
<|file_name|>check_prefixes.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import os import sys import subprocess sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))<|fim▁hole|> def get_registries(): registries = [] directories = os.listdir(PREFIXES_PATH) directories.append(os.path.expanduser("~/.wine")) for prefix in directories: for path in os.listdir(os.path.join(PREFIXES_PATH, prefix)): if path.endswith(".reg"): registries.append(os.path.join(PREFIXES_PATH, prefix, path)) return registries def check_registry(registry_path): with open(registry_path, 'r') as registry_file: original_content = registry_file.read() try: registry = WineRegistry(registry_path) except: sys.stderr.write("Error parsing {}\n".format(registry_path)) raise content = registry.render() if content != original_content: wrong_path = os.path.join(os.path.dirname(__file__), 'error.reg') with open(wrong_path, 'w') as wrong_reg: wrong_reg.write(content) print("Content of parsed registry doesn't match: {}".format(registry_path)) subprocess.call(["meld", registry_path, wrong_path]) sys.exit(2) registries = get_registries() for registry in registries: check_registry(registry) print("All {} registry files validated!".format(len(registries)))<|fim▁end|>
from lutris.util.wineregistry import WineRegistry PREFIXES_PATH = os.path.expanduser("~/Games/wine/prefixes")
<|file_name|>FileDoesNotExistException.java<|end_file_name|><|fim▁begin|>/* * Copyright 2017 Axway Software * * 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.axway.ats.core.filesystem.exceptions; import java.io.File; import com.axway.ats.common.filesystem.FileSystemOperationException; /** * Exception thrown when a file does not exist */ @SuppressWarnings( "serial") public class FileDoesNotExistException extends FileSystemOperationException { /** * Constructor * * @param fileName name of the file which does not exist */ public FileDoesNotExistException( String fileName ) { <|fim▁hole|> super("File '" + fileName + "' does not exist"); } /** * Constructor * * @param file the file which does not exist */ public FileDoesNotExistException( File file ) { super("File '" + file.getPath() + "' does not exist"); } }<|fim▁end|>
<|file_name|>storage.py<|end_file_name|><|fim▁begin|># Copyright 2015, 2017 IBM Corp. # # 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. from oslo_log import log as logging from pypowervm import exceptions as pvm_exc from pypowervm.tasks import scsi_mapper as pvm_smap from taskflow import task from taskflow.types import failure as task_fail from nova import exception from nova.virt.powervm import media from nova.virt.powervm import mgmt LOG = logging.getLogger(__name__) class CreateDiskForImg(task.Task): """The Task to create the disk from an image in the storage.""" def __init__(self, disk_dvr, context, instance, image_meta): """Create the Task. Provides the 'disk_dev_info' for other tasks. Comes from the disk_dvr create_disk_from_image method. :param disk_dvr: The storage driver. :param context: The context passed into the driver method. :param instance: The nova instance. :param nova.objects.ImageMeta image_meta: The metadata of the image of the instance. """ super(CreateDiskForImg, self).__init__( name='create_disk_from_img', provides='disk_dev_info') self.disk_dvr = disk_dvr self.instance = instance self.context = context self.image_meta = image_meta def execute(self): return self.disk_dvr.create_disk_from_image( self.context, self.instance, self.image_meta) def revert(self, result, flow_failures): # If there is no result, or its a direct failure, then there isn't # anything to delete. if result is None or isinstance(result, task_fail.Failure): return # Run the delete. The result is a single disk. Wrap into list # as the method works with plural disks. try: self.disk_dvr.delete_disks([result]) except pvm_exc.Error: # Don't allow revert exceptions to interrupt the revert flow. LOG.exception("Disk deletion failed during revert. Ignoring.", instance=self.instance) class AttachDisk(task.Task): """The task to attach the disk to the instance.""" def __init__(self, disk_dvr, instance, stg_ftsk): """Create the Task for the attach disk to instance method. Requires disk info through requirement of disk_dev_info (provided by crt_disk_from_img) :param disk_dvr: The disk driver. :param instance: The nova instance. :param stg_ftsk: FeedTask to defer storage connectivity operations. """ super(AttachDisk, self).__init__( name='attach_disk', requires=['disk_dev_info']) self.disk_dvr = disk_dvr self.instance = instance self.stg_ftsk = stg_ftsk def execute(self, disk_dev_info): self.disk_dvr.attach_disk(self.instance, disk_dev_info, self.stg_ftsk) def revert(self, disk_dev_info, result, flow_failures): try: self.disk_dvr.detach_disk(self.instance) except pvm_exc.Error: # Don't allow revert exceptions to interrupt the revert flow. LOG.exception("Disk detach failed during revert. Ignoring.", instance=self.instance) class DetachDisk(task.Task): """The task to detach the disk storage from the instance.""" def __init__(self, disk_dvr, instance): """Creates the Task to detach the storage adapters. Provides the stor_adpt_mappings. A list of pypowervm VSCSIMappings or VFCMappings (depending on the storage adapter). :param disk_dvr: The DiskAdapter for the VM. :param instance: The nova instance. """ super(DetachDisk, self).__init__( name='detach_disk', provides='stor_adpt_mappings') self.instance = instance self.disk_dvr = disk_dvr def execute(self): return self.disk_dvr.detach_disk(self.instance) class DeleteDisk(task.Task): """The task to delete the backing storage.""" def __init__(self, disk_dvr): """Creates the Task to delete the disk storage from the system. Requires the stor_adpt_mappings. :param disk_dvr: The DiskAdapter for the VM. """ super(DeleteDisk, self).__init__( name='delete_disk', requires=['stor_adpt_mappings']) self.disk_dvr = disk_dvr def execute(self, stor_adpt_mappings): self.disk_dvr.delete_disks(stor_adpt_mappings) class CreateAndConnectCfgDrive(task.Task): """The task to create the configuration drive.""" def __init__(self, adapter, instance, injected_files, network_info, stg_ftsk, admin_pass=None): """Create the Task that creates and connects the config drive. Requires the 'mgmt_cna' <|fim▁hole|> the ISO. :param network_info: The network_info from the nova spawn method. :param stg_ftsk: FeedTask to defer storage connectivity operations. :param admin_pass (Optional, Default None): Password to inject for the VM. """ super(CreateAndConnectCfgDrive, self).__init__( name='cfg_drive', requires=['mgmt_cna']) self.adapter = adapter self.instance = instance self.injected_files = injected_files self.network_info = network_info self.stg_ftsk = stg_ftsk self.ad_pass = admin_pass self.mb = None def execute(self, mgmt_cna): self.mb = media.ConfigDrivePowerVM(self.adapter) self.mb.create_cfg_drv_vopt(self.instance, self.injected_files, self.network_info, self.stg_ftsk, admin_pass=self.ad_pass, mgmt_cna=mgmt_cna) def revert(self, mgmt_cna, result, flow_failures): # No media builder, nothing to do if self.mb is None: return # Delete the virtual optical media. We don't care if it fails try: self.mb.dlt_vopt(self.instance, self.stg_ftsk) except pvm_exc.Error: LOG.exception('VOpt removal (as part of reversion) failed.', instance=self.instance) class DeleteVOpt(task.Task): """The task to delete the virtual optical.""" def __init__(self, adapter, instance, stg_ftsk=None): """Creates the Task to delete the instance's virtual optical media. :param adapter: The adapter for the pypowervm API :param instance: The nova instance. :param stg_ftsk: FeedTask to defer storage connectivity operations. """ super(DeleteVOpt, self).__init__(name='vopt_delete') self.adapter = adapter self.instance = instance self.stg_ftsk = stg_ftsk def execute(self): media_builder = media.ConfigDrivePowerVM(self.adapter) media_builder.dlt_vopt(self.instance, stg_ftsk=self.stg_ftsk) class InstanceDiskToMgmt(task.Task): """The task to connect an instance's disk to the management partition." This task will connect the instance's disk to the management partition and discover it. We do these two pieces together because their reversion happens in the same order. """ def __init__(self, disk_dvr, instance): """Create the Task for connecting boot disk to mgmt partition. Provides: stg_elem: The storage element wrapper (pypowervm LU, PV, etc.) that was connected. vios_wrap: The Virtual I/O Server wrapper from which the storage element was mapped. disk_path: The local path to the mapped-and-discovered device, e.g. '/dev/sde'. :param disk_dvr: The disk driver. :param instance: The nova instance whose boot disk is to be connected. """ super(InstanceDiskToMgmt, self).__init__( name='instance_disk_to_mgmt', provides=['stg_elem', 'vios_wrap', 'disk_path']) self.disk_dvr = disk_dvr self.instance = instance self.stg_elem = None self.vios_wrap = None self.disk_path = None def execute(self): """Map the instance's boot disk and discover it.""" # Search for boot disk on the NovaLink partition. if self.disk_dvr.mp_uuid in self.disk_dvr._vios_uuids: dev_name = self.disk_dvr.get_bootdisk_path( self.instance, self.disk_dvr.mp_uuid) if dev_name is not None: return None, None, dev_name self.stg_elem, self.vios_wrap = ( self.disk_dvr.connect_instance_disk_to_mgmt(self.instance)) new_maps = pvm_smap.find_maps( self.vios_wrap.scsi_mappings, client_lpar_id=self.disk_dvr.mp_uuid, stg_elem=self.stg_elem) if not new_maps: raise exception.NewMgmtMappingNotFoundException( stg_name=self.stg_elem.name, vios_name=self.vios_wrap.name) # new_maps should be length 1, but even if it's not - i.e. we somehow # matched more than one mapping of the same dev to the management # partition from the same VIOS - it is safe to use the first one. mapping = new_maps[0] # Scan the SCSI bus, discover the disk, find its canonical path. LOG.info("Discovering device and path for mapping of %(dev_name)s " "on the management partition.", {'dev_name': self.stg_elem.name}, instance=self.instance) self.disk_path = mgmt.discover_vscsi_disk(mapping) return self.stg_elem, self.vios_wrap, self.disk_path def revert(self, result, flow_failures): """Unmap the disk and then remove it from the management partition. We use this order to avoid rediscovering the device in case some other thread scans the SCSI bus between when we remove and when we unmap. """ if self.vios_wrap is None or self.stg_elem is None: # We never even got connected - nothing to do. return LOG.warning("Unmapping boot disk %(disk_name)s from the management " "partition via Virtual I/O Server %(vioname)s.", {'disk_name': self.stg_elem.name, 'vioname': self.vios_wrap.name}, instance=self.instance) self.disk_dvr.disconnect_disk_from_mgmt(self.vios_wrap.uuid, self.stg_elem.name) if self.disk_path is None: # We did not discover the disk - nothing else to do. return LOG.warning("Removing disk %(dpath)s from the management partition.", {'dpath': self.disk_path}, instance=self.instance) try: mgmt.remove_block_dev(self.disk_path) except pvm_exc.Error: # Don't allow revert exceptions to interrupt the revert flow. LOG.exception("Remove disk failed during revert. Ignoring.", instance=self.instance) class RemoveInstanceDiskFromMgmt(task.Task): """Unmap and remove an instance's boot disk from the mgmt partition.""" def __init__(self, disk_dvr, instance): """Create task to unmap and remove an instance's boot disk from mgmt. Requires (from InstanceDiskToMgmt): stg_elem: The storage element wrapper (pypowervm LU, PV, etc.) that was connected. vios_wrap: The Virtual I/O Server wrapper. (pypowervm.wrappers.virtual_io_server.VIOS) from which the storage element was mapped. disk_path: The local path to the mapped-and-discovered device, e.g. '/dev/sde'. :param disk_dvr: The disk driver. :param instance: The nova instance whose boot disk is to be connected. """ self.disk_dvr = disk_dvr self.instance = instance super(RemoveInstanceDiskFromMgmt, self).__init__( name='remove_inst_disk_from_mgmt', requires=['stg_elem', 'vios_wrap', 'disk_path']) def execute(self, stg_elem, vios_wrap, disk_path): """Unmap and remove an instance's boot disk from the mgmt partition. Input parameters ('requires') provided by InstanceDiskToMgmt task. :param stg_elem: The storage element wrapper (pypowervm LU, PV, etc.) to be disconnected. :param vios_wrap: The Virtual I/O Server wrapper from which the mapping is to be removed. :param disk_path: The local path to the disk device to be removed, e.g. '/dev/sde' """ # stg_elem is None if boot disk was not mapped to management partition. if stg_elem is None: return LOG.info("Unmapping boot disk %(disk_name)s from the management " "partition via Virtual I/O Server %(vios_name)s.", {'disk_name': stg_elem.name, 'vios_name': vios_wrap.name}, instance=self.instance) self.disk_dvr.disconnect_disk_from_mgmt(vios_wrap.uuid, stg_elem.name) LOG.info("Removing disk %(disk_path)s from the management partition.", {'disk_path': disk_path}, instance=self.instance) mgmt.remove_block_dev(disk_path)<|fim▁end|>
:param adapter: The adapter for the pypowervm API :param instance: The nova instance :param injected_files: A list of file paths that will be injected into
<|file_name|>car.py<|end_file_name|><|fim▁begin|>""" Constructs a planner that is good for being kinda like a car-boat thing! """ from __future__ import division import numpy as np import numpy.linalg as npl from params import * import lqrrt ################################################# DYNAMICS magic_rudder = 6000 def dynamics(x, u, dt): """ Returns next state given last state x, wrench u, and timestep dt. """ # Rotation matrix (orientation, converts body to world) R = np.array([ [np.cos(x[2]), -np.sin(x[2]), 0], [np.sin(x[2]), np.cos(x[2]), 0], [ 0, 0, 1] ]) # Construct drag coefficients based on our motion signs D = np.copy(D_neg) for i, v in enumerate(x[3:]): if v >= 0: D[i] = D_pos[i] # Heading controller trying to keep us car-like vw = R[:2, :2].dot(x[3:5]) ang = np.arctan2(vw[1], vw[0]) c = np.cos(x[2]) s = np.sin(x[2]) cg = np.cos(ang) sg = np.sin(ang) u[2] = magic_rudder*np.arctan2(sg*c - cg*s, cg*c + sg*s) # Actuator saturation u = B.dot(np.clip(invB.dot(u), -thrust_max, thrust_max)) # M*vdot + D*v = u and pdot = R*v xdot = np.concatenate((R.dot(x[3:]), invM*(u - D*x[3:]))) # First-order integrate xnext = x + xdot*dt # Impose not driving backwards if xnext[3] < 0: xnext[3] = abs(x[3]) # # Impose not turning in place # xnext[5] = np.clip(np.abs(xnext[3]/velmax_pos[0]), 0, 1) * xnext[5] return xnext ################################################# POLICY kp = np.diag([150, 150, 0]) kd = np.diag([150, 5, 0]) S = np.diag([1, 1, 1, 0, 0, 0])<|fim▁hole|> def lqr(x, u): """ Returns cost-to-go matrix S and policy matrix K given local state x and effort u. """ R = np.array([ [np.cos(x[2]), -np.sin(x[2]), 0], [np.sin(x[2]), np.cos(x[2]), 0], [ 0, 0, 1] ]) K = np.hstack((kp.dot(R.T), kd)) return (S, K) ################################################# HEURISTICS goal_buffer = [0.5*free_radius, 0.5*free_radius, np.inf, np.inf, np.inf, np.inf] error_tol = np.copy(goal_buffer)/10 def gen_ss(seed, goal, buff=[ss_start]*4): """ Returns a sample space given a seed state, goal state, and buffer. """ return [(min([seed[0], goal[0]]) - buff[0], max([seed[0], goal[0]]) + buff[1]), (min([seed[1], goal[1]]) - buff[2], max([seed[1], goal[1]]) + buff[3]), (-np.pi, np.pi), (0.9*velmax_pos[0], velmax_pos[0]), (-abs(velmax_neg[1]), velmax_pos[1]), (-abs(velmax_neg[2]), velmax_pos[2])] ################################################# MAIN ATTRIBUTES constraints = lqrrt.Constraints(nstates=nstates, ncontrols=ncontrols, goal_buffer=goal_buffer, is_feasible=unset) planner = lqrrt.Planner(dynamics, lqr, constraints, horizon=horizon, dt=dt, FPR=FPR, error_tol=error_tol, erf=unset, min_time=basic_duration, max_time=basic_duration, max_nodes=max_nodes, sys_time=unset, printing=False)<|fim▁end|>
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>from functools import update_wrapper, wraps from unittest import TestCase from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth.decorators import ( login_required, permission_required, user_passes_test, ) from django.http import HttpRequest, HttpResponse, HttpResponseNotAllowed from django.middleware.clickjacking import XFrameOptionsMiddleware from django.test import SimpleTestCase from django.utils.decorators import method_decorator from django.utils.functional import keep_lazy, keep_lazy_text, lazy from django.utils.safestring import mark_safe from django.views.decorators.cache import ( cache_control, cache_page, never_cache, ) from django.views.decorators.clickjacking import ( xframe_options_deny, xframe_options_exempt, xframe_options_sameorigin, ) from django.views.decorators.http import ( condition, require_GET, require_http_methods, require_POST, require_safe, ) from django.views.decorators.vary import vary_on_cookie, vary_on_headers def fully_decorated(request): """Expected __doc__""" return HttpResponse('<html><body>dummy</body></html>') fully_decorated.anything = "Expected __dict__" def compose(*functions): # compose(f, g)(*args, **kwargs) == f(g(*args, **kwargs)) functions = list(reversed(functions)) def _inner(*args, **kwargs): result = functions[0](*args, **kwargs) for f in functions[1:]: result = f(result) return result return _inner full_decorator = compose( # django.views.decorators.http require_http_methods(["GET"]), require_GET, require_POST, require_safe, condition(lambda r: None, lambda r: None), # django.views.decorators.vary vary_on_headers('Accept-language'), vary_on_cookie, # django.views.decorators.cache cache_page(60 * 15), cache_control(private=True), never_cache, # django.contrib.auth.decorators # Apply user_passes_test twice to check #9474 user_passes_test(lambda u: True), login_required, permission_required('change_world'), # django.contrib.admin.views.decorators staff_member_required, # django.utils.functional keep_lazy(HttpResponse), keep_lazy_text, lazy, # django.utils.safestring mark_safe, ) fully_decorated = full_decorator(fully_decorated) class DecoratorsTest(TestCase): def test_attributes(self): """ Built-in decorators set certain attributes of the wrapped function. """ self.assertEqual(fully_decorated.__name__, 'fully_decorated') self.assertEqual(fully_decorated.__doc__, 'Expected __doc__') self.assertEqual(fully_decorated.__dict__['anything'], 'Expected __dict__') def test_user_passes_test_composition(self): """ The user_passes_test decorator can be applied multiple times (#9474). """ def test1(user): user.decorators_applied.append('test1') return True def test2(user): user.decorators_applied.append('test2') return True def callback(request): return request.user.decorators_applied callback = user_passes_test(test1)(callback) callback = user_passes_test(test2)(callback) class DummyUser: pass class DummyRequest: pass request = DummyRequest() request.user = DummyUser() request.user.decorators_applied = [] response = callback(request) self.assertEqual(response, ['test2', 'test1']) def test_cache_page(self): def my_view(request): return "response" my_view_cached = cache_page(123)(my_view) self.assertEqual(my_view_cached(HttpRequest()), "response") my_view_cached2 = cache_page(123, key_prefix="test")(my_view) self.assertEqual(my_view_cached2(HttpRequest()), "response") def test_require_safe_accepts_only_safe_methods(self): """ Test for the require_safe decorator. A view returns either a response or an exception. Refs #15637. """ def my_view(request): return HttpResponse("OK") my_safe_view = require_safe(my_view) request = HttpRequest() request.method = 'GET' self.assertIsInstance(my_safe_view(request), HttpResponse) request.method = 'HEAD' self.assertIsInstance(my_safe_view(request), HttpResponse) request.method = 'POST' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)<|fim▁hole|> self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) # For testing method_decorator, a decorator that assumes a single argument. # We will get type arguments if there is a mismatch in the number of arguments. def simple_dec(func): def wrapper(arg): return func("test:" + arg) return wraps(func)(wrapper) simple_dec_m = method_decorator(simple_dec) # For testing method_decorator, two decorators that add an attribute to the function def myattr_dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.myattr = True return wrapper myattr_dec_m = method_decorator(myattr_dec) def myattr2_dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.myattr2 = True return wrapper myattr2_dec_m = method_decorator(myattr2_dec) class ClsDec: def __init__(self, myattr): self.myattr = myattr def __call__(self, f): def wrapped(): return f() and self.myattr return update_wrapper(wrapped, f) class MethodDecoratorTests(SimpleTestCase): """ Tests for method_decorator """ def test_preserve_signature(self): class Test: @simple_dec_m def say(self, arg): return arg self.assertEqual("test:hello", Test().say("hello")) def test_preserve_attributes(self): # Sanity check myattr_dec and myattr2_dec @myattr_dec def func(): pass self.assertIs(getattr(func, 'myattr', False), True) @myattr2_dec def func(): pass self.assertIs(getattr(func, 'myattr2', False), True) @myattr_dec @myattr2_dec def func(): pass self.assertIs(getattr(func, 'myattr', False), True) self.assertIs(getattr(func, 'myattr2', False), False) # Decorate using method_decorator() on the method. class TestPlain: @myattr_dec_m @myattr2_dec_m def method(self): "A method" pass # Decorate using method_decorator() on both the class and the method. # The decorators applied to the methods are applied before the ones # applied to the class. @method_decorator(myattr_dec_m, "method") class TestMethodAndClass: @method_decorator(myattr2_dec_m) def method(self): "A method" pass # Decorate using an iterable of function decorators. @method_decorator((myattr_dec, myattr2_dec), 'method') class TestFunctionIterable: def method(self): "A method" pass # Decorate using an iterable of method decorators. decorators = (myattr_dec_m, myattr2_dec_m) @method_decorator(decorators, "method") class TestMethodIterable: def method(self): "A method" pass tests = (TestPlain, TestMethodAndClass, TestFunctionIterable, TestMethodIterable) for Test in tests: with self.subTest(Test=Test): self.assertIs(getattr(Test().method, 'myattr', False), True) self.assertIs(getattr(Test().method, 'myattr2', False), True) self.assertIs(getattr(Test.method, 'myattr', False), True) self.assertIs(getattr(Test.method, 'myattr2', False), True) self.assertEqual(Test.method.__doc__, 'A method') self.assertEqual(Test.method.__name__, 'method') def test_new_attribute(self): """A decorator that sets a new attribute on the method.""" def decorate(func): func.x = 1 return func class MyClass: @method_decorator(decorate) def method(self): return True obj = MyClass() self.assertEqual(obj.method.x, 1) self.assertIs(obj.method(), True) def test_bad_iterable(self): decorators = {myattr_dec_m, myattr2_dec_m} msg = "'set' object is not subscriptable" with self.assertRaisesMessage(TypeError, msg): @method_decorator(decorators, "method") class TestIterable: def method(self): "A method" pass # Test for argumented decorator def test_argumented(self): class Test: @method_decorator(ClsDec(False)) def method(self): return True self.assertIs(Test().method(), False) def test_descriptors(self): def original_dec(wrapped): def _wrapped(arg): return wrapped(arg) return _wrapped method_dec = method_decorator(original_dec) class bound_wrapper: def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __call__(self, arg): return self.wrapped(arg) def __get__(self, instance, cls=None): return self class descriptor_wrapper: def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __get__(self, instance, cls=None): return bound_wrapper(self.wrapped.__get__(instance, cls)) class Test: @method_dec @descriptor_wrapper def method(self, arg): return arg self.assertEqual(Test().method(1), 1) def test_class_decoration(self): """ @method_decorator can be used to decorate a class and its methods. """ def deco(func): def _wrapper(*args, **kwargs): return True return _wrapper @method_decorator(deco, name="method") class Test: def method(self): return False self.assertTrue(Test().method()) def test_tuple_of_decorators(self): """ @method_decorator can accept a tuple of decorators. """ def add_question_mark(func): def _wrapper(*args, **kwargs): return func(*args, **kwargs) + "?" return _wrapper def add_exclamation_mark(func): def _wrapper(*args, **kwargs): return func(*args, **kwargs) + "!" return _wrapper # The order should be consistent with the usual order in which # decorators are applied, e.g. # @add_exclamation_mark # @add_question_mark # def func(): # ... decorators = (add_exclamation_mark, add_question_mark) @method_decorator(decorators, name="method") class TestFirst: def method(self): return "hello world" class TestSecond: @method_decorator(decorators) def method(self): return "hello world" self.assertEqual(TestFirst().method(), "hello world?!") self.assertEqual(TestSecond().method(), "hello world?!") def test_invalid_non_callable_attribute_decoration(self): """ @method_decorator on a non-callable attribute raises an error. """ msg = ( "Cannot decorate 'prop' as it isn't a callable attribute of " "<class 'Test'> (1)" ) with self.assertRaisesMessage(TypeError, msg): @method_decorator(lambda: None, name="prop") class Test: prop = 1 @classmethod def __module__(cls): return "tests" def test_invalid_method_name_to_decorate(self): """ @method_decorator on a nonexistent method raises an error. """ msg = ( "The keyword argument `name` must be the name of a method of the " "decorated class: <class 'Test'>. Got 'nonexistent_method' instead" ) with self.assertRaisesMessage(ValueError, msg): @method_decorator(lambda: None, name='nonexistent_method') class Test: @classmethod def __module__(cls): return "tests" class XFrameOptionsDecoratorsTests(TestCase): """ Tests for the X-Frame-Options decorators. """ def test_deny_decorator(self): """ Ensures @xframe_options_deny properly sets the X-Frame-Options header. """ @xframe_options_deny def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual(r.headers['X-Frame-Options'], 'DENY') def test_sameorigin_decorator(self): """ Ensures @xframe_options_sameorigin properly sets the X-Frame-Options header. """ @xframe_options_sameorigin def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual(r.headers['X-Frame-Options'], 'SAMEORIGIN') def test_exempt_decorator(self): """ Ensures @xframe_options_exempt properly instructs the XFrameOptionsMiddleware to NOT set the header. """ @xframe_options_exempt def a_view(request): return HttpResponse() req = HttpRequest() resp = a_view(req) self.assertIsNone(resp.get('X-Frame-Options', None)) self.assertTrue(resp.xframe_options_exempt) # Since the real purpose of the exempt decorator is to suppress # the middleware's functionality, let's make sure it actually works... r = XFrameOptionsMiddleware(a_view)(req) self.assertIsNone(r.get('X-Frame-Options', None)) class NeverCacheDecoratorTest(SimpleTestCase): def test_never_cache_decorator(self): @never_cache def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual( set(r.headers['Cache-Control'].split(', ')), {'max-age=0', 'no-cache', 'no-store', 'must-revalidate', 'private'}, ) def test_never_cache_decorator_http_request(self): class MyClass: @never_cache def a_view(self, request): return HttpResponse() msg = ( "never_cache didn't receive an HttpRequest. If you are decorating " "a classmethod, be sure to use @method_decorator." ) with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(HttpRequest()) class CacheControlDecoratorTest(SimpleTestCase): def test_cache_control_decorator_http_request(self): class MyClass: @cache_control(a='b') def a_view(self, request): return HttpResponse() msg = ( "cache_control didn't receive an HttpRequest. If you are " "decorating a classmethod, be sure to use @method_decorator." ) with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(HttpRequest())<|fim▁end|>
request.method = 'PUT' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) request.method = 'DELETE'
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>use separator::Separatable; #[test] fn negative_nine_hundred_million() { let i : i128 = -900000000; assert_eq!("-900,000,000", &i.separated_string()); } #[test] fn negative_ninety_million() { let i : i128 = -90000000; assert_eq!("-90,000,000", &i.separated_string()); } #[test] fn negative_nine_million() { let i : i128 = -9000000; assert_eq!("-9,000,000", &i.separated_string()); } #[test] fn negative_nine_hundred_thousand() { let i : i128 = -900000; assert_eq!("-900,000", &i.separated_string()); } #[test] fn negative_ninety_thousand() { let i : i128 = -90000; assert_eq!("-90,000", &i.separated_string()); } #[test] fn negative_nine_thousand() { let i : i128 = -9000; assert_eq!("-9,000", &i.separated_string()); } #[test] fn negative_nine_hundred() { let i : i128 = -900; assert_eq!("-900", &i.separated_string()); } #[test] fn negative_ninety() { let i : i128 = -90; assert_eq!("-90", &i.separated_string()); } #[test] fn negative_nine() { let i : i128 = -9; assert_eq!("-9", &i.separated_string()); } #[test] fn nine() { let i : i128 = 9; assert_eq!("9", &i.separated_string());<|fim▁hole|>#[test] fn ninety() { let i : i128 = 90; assert_eq!("90", &i.separated_string()); } #[test] fn nine_hundred() { let i : i128 = 900; assert_eq!("900", &i.separated_string()); } #[test] fn nine_thousand() { let i : i128 = 9000; assert_eq!("9,000", &i.separated_string()); } #[test] fn ninety_thousand() { let i : i128 = 90000; assert_eq!("90,000", &i.separated_string()); } #[test] fn nine_hundred_thousand() { let i : i128 = 900000; assert_eq!("900,000", &i.separated_string()); } #[test] fn nine_million() { let i : i128 = 9000000; assert_eq!("9,000,000", &i.separated_string()); } #[test] fn ninety_million() { let i : i128 = 90000000; assert_eq!("90,000,000", &i.separated_string()); } #[test] fn nine_hundred_million() { let i : i128 = 900000000; assert_eq!("900,000,000", &i.separated_string()); }<|fim▁end|>
}
<|file_name|>mscorlib_System_Runtime_Serialization_SerializationObjectManager.cpp<|end_file_name|><|fim▁begin|>#include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_SerializationObjectManager.h> #include <mscorlib/System/mscorlib_System_Type.h> #include <mscorlib/System/mscorlib_System_String.h> namespace mscorlib { namespace System { namespace Runtime { namespace Serialization { //Public Methods void SerializationObjectManager::RegisterObject(mscorlib::System::Object obj) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameters__[0] = (MonoObject*)obj; Global::InvokeMethod("mscorlib", "System.Runtime.Serialization", "SerializationObjectManager", 0, NULL, "RegisterObject", __native_object__, 1, __parameter_types__, __parameters__, NULL); } void SerializationObjectManager::RaiseOnSerializedEvent() { Global::InvokeMethod("mscorlib", "System.Runtime.Serialization", "SerializationObjectManager", 0, NULL, "RaiseOnSerializedEvent", __native_object__, 0, NULL, NULL, NULL); } <|fim▁hole|>}<|fim▁end|>
} } }
<|file_name|>test_hgnc.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 import unittest import logging from tests.test_source import SourceTestCase<|fim▁hole|> class HGNCTestCase(SourceTestCase): def setUp(self): self.source = HGNC('rdf_graph', True) self.source.test_ids = self.all_test_ids['gene'] self.source.settestonly(True) self._setDirToSource() return def tearDown(self): self.source = None return if __name__ == '__main__': unittest.main()<|fim▁end|>
from dipper.sources.HGNC import HGNC logging.basicConfig(level=logging.WARNING) logger = logging.getLogger(__name__)
<|file_name|>AccountTag.tsx<|end_file_name|><|fim▁begin|>import { IPromise } from 'angular'; import React from 'react'; import { AccountService } from './AccountService'; export interface IAccountTagProps { account: string; className?: string; } export interface IAccountTagState { isProdAccount: boolean; } export class AccountTag extends React.Component<IAccountTagProps, IAccountTagState> { private static cache: { [account: string]: boolean | IPromise<boolean>; } = {}; public state = { isProdAccount: false }; private mounted = true; public componentWillUnmount(): void { this.mounted = false; } public componentDidMount() { this.updateAccount(this.props.account); } public componentWillReceiveProps(nextProps: IAccountTagProps): void { this.updateAccount(nextProps.account); }<|fim▁hole|> private updateAccount(account: string) { const { cache } = AccountTag; if (!cache.hasOwnProperty(account)) { cache[account] = AccountService.challengeDestructiveActions(account).then(result => (cache[account] = !!result)); } const cachedVal: boolean | IPromise<boolean> = cache[account]; if (typeof cachedVal === 'boolean') { this.setState({ isProdAccount: cachedVal }); } else { cachedVal.then(isProdAccount => this.mounted && this.setState({ isProdAccount })); } } public render() { const { account, className } = this.props; const { isProdAccount } = this.state; return ( <span className={`account-tag account-tag-${isProdAccount ? 'prod' : 'notprod'} ${className || ''}`}> {account} </span> ); } }<|fim▁end|>
<|file_name|>mkdir.hpp<|end_file_name|><|fim▁begin|>// 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<|fim▁hole|>// See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_OS_WINDOWS_MKDIR_HPP__ #define __STOUT_OS_WINDOWS_MKDIR_HPP__ #include <string> #include <vector> #include <stout/error.hpp> #include <stout/nothing.hpp> #include <stout/strings.hpp> #include <stout/try.hpp> #include <stout/windows.hpp> #include <stout/os/exists.hpp> #include <stout/os/constants.hpp> #include <stout/internal/windows/longpath.hpp> namespace os { inline Try<Nothing> mkdir(const std::string& directory, bool recursive = true) { if (!recursive) { // NOTE: We check for existence because parts of certain directories // like `C:\` will return an error if passed to `CreateDirectory`, // even though the drive may already exist. if (os::exists(directory)) { return Nothing(); } std::wstring longpath = ::internal::windows::longpath(directory); if (::CreateDirectoryW(longpath.data(), nullptr) == 0) { return WindowsError("Failed to create directory: " + directory); } } else { // Remove the long path prefix, if it already exists, otherwise the // tokenizer includes the long path prefix (`\\?\`) as the first part // of the path. std::vector<std::string> tokens = strings::tokenize( strings::remove(directory, os::LONGPATH_PREFIX, strings::Mode::PREFIX), stringify(os::PATH_SEPARATOR)); std::string path; foreach (const std::string& token, tokens) { path += token + os::PATH_SEPARATOR; Try<Nothing> result = mkdir(path, false); if (result.isError()) { return result; } } } return Nothing(); } } // namespace os { #endif // __STOUT_OS_WINDOWS_MKDIR_HPP__<|fim▁end|>
// distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<|file_name|>defined.js<|end_file_name|><|fim▁begin|>function defined (constant_name) { // http://kevin.vanzonneveld.net // + original by: Waldo Malqui Silva // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + revised by: Brett Zamir (http://brett-zamir.me) // % note 1: Because this function can (albeit only temporarily) overwrite a global variable, // % note 1: it is not thread-safe (normally not a concern for JavaScript, but would be if used<|fim▁hole|> this.window[constant_name] = this.window[constant_name] ? 'changed' + this.window[constant_name].toString() : 'changed'; var returnval = this.window[constant_name] === tmp; if (!returnval) { // Reset this.window[constant_name] = tmp; } return returnval; }<|fim▁end|>
// % note 1: in a threaded environment, e.g., DOM worker threads) // * example 1: defined('IMAGINARY_CONSTANT1'); // * returns 1: false var tmp = this.window[constant_name];
<|file_name|>mdarray_test.cpp<|end_file_name|><|fim▁begin|>// // (c) Copyright 2013 DESY, Eugen Wintersberger <[email protected]> // // This file is part of pninexus. // // pninexus 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. // // pninexus 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|>// // =========================================================================== // // Created on: Oct 28, 2013 // Author: Eugen Wintersberger <[email protected]> // #ifdef __GNUG__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif #include <boost/test/unit_test.hpp> #ifdef __GNUG__ #pragma GCC diagnostic pop #endif #include <pni/arrays.hpp> #include "array_types.hpp" #include "../data_generator.hpp" #include "../compiler_version.hpp" using namespace pni; template<typename AT> struct test_mdarray_fixture { typedef AT array_type; typedef typename array_type::value_type value_type; typedef typename array_type::storage_type storage_type; typedef typename array_type::map_type map_type; typedef random_generator<value_type> generator_type; generator_type generator; shape_t shape; test_mdarray_fixture(): generator(), shape(shape_t{2,3,5}) {} }; BOOST_AUTO_TEST_SUITE(test_mdarray) typedef boost::mpl::joint_view<all_dynamic_arrays, #if GCC_VERSION > 40800 boost::mpl::joint_view< all_fixed_dim_arrays<3>, all_static_arrays<2,3,5> > #else all_fixed_dim_arrays<3> #endif > array_types; template<typename CTYPE,typename...ITYPES> static void create_index(CTYPE &index,ITYPES ...indexes) { index = CTYPE{indexes...}; } template<typename T,size_t N,typename ...ITYPES> static void create_index(std::array<T,N> &c,ITYPES ...indexes) { c = std::array<T,N>{{indexes...}}; } template< typename ITYPE, typename ATYPE > void test_multiindex_access_with_container() { typedef test_mdarray_fixture<ATYPE> fixture_type; typedef typename fixture_type::value_type value_type; fixture_type fixture; auto a = ATYPE::create(fixture.shape); ITYPE index; for(size_t i=0;i<fixture.shape[0];i++) for(size_t j=0;j<fixture.shape[1];j++) for(size_t k=0;k<fixture.shape[2];k++) { value_type v = fixture.generator(); create_index(index,i,j,k); a(index) = v; BOOST_CHECK_EQUAL(a(index),v); } } //======================================================================== // Create a mdarray instance from a view BOOST_AUTO_TEST_CASE_TEMPLATE(test_view_construction,AT,array_types) { typedef test_mdarray_fixture<AT> fixture_type; typedef typename fixture_type::value_type value_type; typedef dynamic_array<value_type> darray_type; fixture_type fixture; auto a = darray_type::create(shape_t{100,20,30}); std::generate(a.begin(),a.end(),fixture.generator); auto view = a(slice(0,2),slice(0,3),slice(0,5)); AT target(view); auto view_shape = view.template shape<shape_t>(); auto target_shape = target.template shape<shape_t>(); BOOST_CHECK_EQUAL_COLLECTIONS(view_shape.begin(),view_shape.end(), target_shape.begin(),target_shape.end()); BOOST_CHECK_EQUAL(view.size(),target.size()); BOOST_CHECK_EQUAL(view.rank(),target.rank()); BOOST_CHECK_EQUAL_COLLECTIONS(view.begin(),view.end(), target.begin(),target.end()); } //======================================================================== BOOST_AUTO_TEST_CASE(test_is_view_index) { BOOST_CHECK((is_view_index<size_t,size_t,size_t>::value==false)); BOOST_CHECK((is_view_index<slice,size_t,size_t>::value==true)); BOOST_CHECK((is_view_index<size_t,slice,size_t>::value==true)); BOOST_CHECK((is_view_index<size_t,size_t,slice>::value==true)); } //======================================================================== BOOST_AUTO_TEST_CASE_TEMPLATE(test_inquery,AT,array_types) { typedef test_mdarray_fixture<AT> fixture_type; typedef typename fixture_type::value_type value_type; fixture_type fixture; auto a = AT::create(fixture.shape); BOOST_CHECK_EQUAL(a.size(),30u); BOOST_CHECK_EQUAL(a.rank(),3u); BOOST_CHECK(AT::type_id == type_id_map<value_type>::type_id); } //======================================================================== BOOST_AUTO_TEST_CASE_TEMPLATE(test_linear_access_operator,AT,array_types) { typedef test_mdarray_fixture<AT> fixture_type; typedef typename fixture_type::value_type value_type; fixture_type fixture; auto a = AT::create(fixture.shape); const AT &ca = a; for(size_t index=0;index<a.size();++index) { value_type v = fixture.generator(); a[index] = v; BOOST_CHECK_EQUAL(a[index],v); BOOST_CHECK_EQUAL(ca[index],v); } } //======================================================================== BOOST_AUTO_TEST_CASE_TEMPLATE(test_linear_access_pointer,AT,array_types) { typedef test_mdarray_fixture<AT> fixture_type; fixture_type fixture; auto a = AT::create(fixture.shape); std::generate(a.begin(),a.end(),fixture.generator); auto ptr = a.data(); for(size_t index=0;index<a.size();++index) BOOST_CHECK_EQUAL(a[index],*(ptr++)); } //======================================================================== BOOST_AUTO_TEST_CASE_TEMPLATE(test_linear_access_at,AT,array_types) { typedef test_mdarray_fixture<AT> fixture_type; typedef typename fixture_type::value_type value_type; fixture_type fixture; auto a = AT::create(fixture.shape); const AT &ca = a; for(size_t index=0;index<a.size();++index) { value_type v = fixture.generator(); a.at(index) = v; BOOST_CHECK_EQUAL(a.at(index),v); BOOST_CHECK_EQUAL(ca.at(index),v); } BOOST_CHECK_THROW(a.at(a.size()),index_error); } //======================================================================== BOOST_AUTO_TEST_CASE_TEMPLATE(test_linear_access_iter,AT,array_types) { typedef test_mdarray_fixture<AT> fixture_type; typedef typename fixture_type::value_type value_type; fixture_type fixture; auto a = AT::create(fixture.shape); typename AT::iterator iter = a.begin(); typename AT::const_iterator citer = a.begin(); for(;iter!=a.end();++iter,++citer) { value_type v = fixture.generator(); *iter = v; BOOST_CHECK_EQUAL(*iter,v); BOOST_CHECK_EQUAL(*citer,v); } } //======================================================================== BOOST_AUTO_TEST_CASE_TEMPLATE(test_linear_access_riter,AT,array_types) { typedef test_mdarray_fixture<AT> fixture_type; typedef typename fixture_type::value_type value_type; fixture_type fixture; auto a = AT::create(fixture.shape); typename AT::reverse_iterator iter = a.rbegin(); typename AT::const_reverse_iterator citer = a.rbegin(); for(;iter!=a.rend();++iter,++citer) { value_type v = fixture.generator(); *iter = v; BOOST_CHECK_EQUAL(*iter,v); BOOST_CHECK_EQUAL(*citer,v); } } //======================================================================== BOOST_AUTO_TEST_CASE_TEMPLATE(test_multiindex_access,AT,array_types) { typedef test_mdarray_fixture<AT> fixture_type; typedef typename fixture_type::value_type value_type; fixture_type fixture; auto a = AT::create(fixture.shape); for(size_t i=0;i<fixture.shape[0];i++) for(size_t j=0;j<fixture.shape[1];j++) for(size_t k=0;k<fixture.shape[2];k++) { value_type v = fixture.generator(); a(i,j,k) = v; BOOST_CHECK_EQUAL(a(i,j,k),v); } } //======================================================================== BOOST_AUTO_TEST_CASE_TEMPLATE(test_muldiindex_access_container,AT,array_types) { test_multiindex_access_with_container<std::vector<size_t>,AT>(); test_multiindex_access_with_container<std::array<size_t,3>,AT>(); test_multiindex_access_with_container<std::list<size_t>,AT>(); test_multiindex_access_with_container<std::vector<uint64>,AT>(); test_multiindex_access_with_container<std::array<uint64,3>,AT>(); test_multiindex_access_with_container<std::list<uint64>,AT>(); } BOOST_AUTO_TEST_SUITE_END()<|fim▁end|>
// GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with pninexus. If not, see <http://www.gnu.org/licenses/>.
<|file_name|>types.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2019 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from sqlalchemy.ext.declarative import declared_attr <|fim▁hole|>from indico.core.db import db from indico.util.locators import locator_property from indico.util.string import format_repr, return_ascii class SessionType(db.Model): __tablename__ = 'session_types' @declared_attr def __table_args__(cls): return (db.Index('ix_uq_session_types_event_id_name_lower', cls.event_id, db.func.lower(cls.name), unique=True), {'schema': 'events'}) id = db.Column( db.Integer, primary_key=True ) event_id = db.Column( db.Integer, db.ForeignKey('events.events.id'), index=True, nullable=False ) name = db.Column( db.String, nullable=False ) code = db.Column( db.String, nullable=False, default='' ) is_poster = db.Column( db.Boolean, nullable=False, default=False ) event = db.relationship( 'Event', lazy=True, backref=db.backref( 'session_types', cascade='all, delete-orphan', lazy=True ) ) # relationship backrefs: # - sessions (Session.type) @return_ascii def __repr__(self): return format_repr(self, 'id', _text=self.name) @locator_property def locator(self): return dict(self.event.locator, session_type_id=self.id)<|fim▁end|>
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import include, url from django.contrib import admin from Poller import views<|fim▁hole|> url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'), url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'), url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'), ]<|fim▁end|>
urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'),
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Benchmark testing // // Test serialization and deserialzation of a MicrovmState for a default VMM: // - 1 VCPU // - 128 MB memory size // - no devices use criterion::{black_box, criterion_group, criterion_main, Criterion}; use snapshot::Snapshot; use std::path::Path; use std::thread; use std::time::Duration; use utils::tempfile::TempFile; use versionize::VersionMap; use vmm::persist::MicrovmState; use vmm::utilities::mock_resources::NOISY_KERNEL_IMAGE; use vmm::utilities::test_utils::create_vmm; use vmm::version_map::VERSION_MAP; use vmm::vmm_config::snapshot::{CreateSnapshotParams, SnapshotType}; use vmm::{persist, FC_EXIT_CODE_OK}; #[inline] pub fn bench_restore_snapshot( mut snapshot_reader: &[u8], snapshot_len: usize, vm: VersionMap, crc: bool, ) { if crc { Snapshot::load::<&[u8], MicrovmState>(&mut snapshot_reader, snapshot_len, vm).unwrap(); } else { Snapshot::unchecked_load::<&[u8], MicrovmState>(&mut snapshot_reader, vm).unwrap(); } } #[inline] pub fn bench_create_snapshot<W: std::io::Write>( mut snapshot_writer: &mut W, vm: VersionMap, crc: bool, state: &mut MicrovmState, ) { let mut snapshot = Snapshot::new(vm.clone(), vm.latest_version()); if crc { snapshot.save(&mut snapshot_writer, state).unwrap(); } else { snapshot .save_without_crc(&mut snapshot_writer, state) .unwrap(); } } fn create_microvm_state(is_diff: bool) -> MicrovmState { let snapshot_file = TempFile::new().unwrap(); let memory_file = TempFile::new().unwrap(); let (vmm, _) = create_vmm(Some(NOISY_KERNEL_IMAGE), is_diff); // Be sure that the microVM is running. thread::sleep(Duration::from_millis(200)); // Pause microVM. vmm.lock().unwrap().pause_vm().unwrap(); // Create snapshot. let snapshot_type = match is_diff { true => SnapshotType::Diff, false => SnapshotType::Full, }; let snapshot_params = CreateSnapshotParams { snapshot_type, snapshot_path: snapshot_file.as_path().to_path_buf(), mem_file_path: memory_file.as_path().to_path_buf(), version: None, }; { let mut locked_vmm = vmm.lock().unwrap(); persist::create_snapshot(&mut locked_vmm, &snapshot_params, VERSION_MAP.clone()).unwrap(); } vmm.lock().unwrap().stop(FC_EXIT_CODE_OK); // Deserialize the microVM state from `snapshot_file`. let snapshot_path = snapshot_file.as_path().to_path_buf(); let snapshot_file_metadata = std::fs::metadata(snapshot_path).unwrap(); let snapshot_len = snapshot_file_metadata.len() as usize; let microvm_state: MicrovmState = Snapshot::load( &mut snapshot_file.as_file(), snapshot_len, VERSION_MAP.clone(), ) .unwrap(); microvm_state } pub fn criterion_benchmark(c: &mut Criterion) { let version_map = VERSION_MAP.clone(); // Create the microvm state let mut state = create_microvm_state(false); // Setup benchmarking with CRC let mut snapshot_state_with_crc = vec![0u8; 1024 * 1024 * 128]; let mut slice = &mut snapshot_state_with_crc.as_mut_slice(); bench_create_snapshot(&mut slice, version_map.clone(), true, &mut state); let snapshot_len = slice.as_ptr() as usize - snapshot_state_with_crc.as_slice().as_ptr() as usize; println!("Snapshot length with CRC: {} bytes.", snapshot_len); c.bench_function("Serialize MicrovmState CRC", |b| { b.iter(|| { bench_create_snapshot( &mut snapshot_state_with_crc.as_mut_slice(), black_box(version_map.clone()), black_box(true), black_box(&mut state), ) }) }); c.bench_function("Deserialize MicrovmState CRC", |b| { b.iter(|| { bench_restore_snapshot( &mut snapshot_state_with_crc.as_mut_slice(), black_box(snapshot_len), black_box(version_map.clone()), black_box(true), ) }) }); // Setup benchmarking without CRC let mut snapshot_state_without_crc = vec![0u8; 1024 * 1024 * 128]; let mut slice = &mut snapshot_state_without_crc.as_mut_slice(); bench_create_snapshot(&mut slice, version_map.clone(), false, &mut state); let snapshot_len = slice.as_ptr() as usize - snapshot_state_without_crc.as_slice().as_ptr() as usize; println!("Snapshot length without CRC: {} bytes.", snapshot_len); c.bench_function("Serialize MicrovmState", |b| { b.iter(|| { bench_create_snapshot( black_box(&mut snapshot_state_without_crc.as_mut_slice()), black_box(version_map.clone()), black_box(false), black_box(&mut state), ) }) }); c.bench_function("Deserialize MicrovmState", |b| { b.iter(|| { bench_restore_snapshot( black_box(&mut snapshot_state_without_crc.as_mut_slice()),<|fim▁hole|> black_box(false), ) }) }); } criterion_group! { name = benches; config = Criterion::default().sample_size(200).output_directory(Path::new("../../build/vmm_benchmark")); targets = criterion_benchmark } criterion_main! { benches }<|fim▁end|>
black_box(snapshot_len), black_box(version_map.clone()),
<|file_name|>kex.rs<|end_file_name|><|fim▁begin|>use ::NailResult; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use rand::{self, Rng}; use ssh::CompressionAlgorithm::{Xz, Zlib, NoComp}; use ssh::EncryptionAlgorithm::{TripleDesCbc, BlowfishCbc, Twofish256Cbc, Twofish192Cbc, Twofish128Cbc, Aes256Cbc, Aes192Cbc, Aes128Cbc, Serpent256Cbc, Serpent192Cbc, Serpent128Cbc, Arcfour, IdeaCbc, Cast128Cbc, NoEnc}; use ssh::KeyExchangeAlgorithm::{Curve25519Sha256, ExchangeSha1, ExchangeSha256, FourteenSha1, OneSha1}; use ssh::MacAlgorithm::{HmacMd5, HmacMd5NinetySix, HmacSha1, HmacSha1NinetySix, NoMac}; use ssh::ServerHostKeyAlgorithm::{PgpSignDss, PgpSignRsa, SshDss, SshEd25519, SshRsa}; use std::default::Default; use std::io::Cursor; #[derive(Clone, Debug, PartialEq)] pub struct KeyExchangeInit { id: u32, cookie: [u8; 16], kex_algorithms: Vec<String>, server_host_key_algorithms: Vec<String>, encryption_algorithms_client_to_server: Vec<String>, encryption_algorithms_server_to_client: Vec<String>, mac_algorithms_client_to_server: Vec<String>, mac_algorithms_server_to_client: Vec<String>, compression_algorithms_client_to_server: Vec<String>, compression_algorithms_server_to_client: Vec<String>, languages_client_to_server: Vec<String>, languages_server_to_client: Vec<String>, first_kex_packet_follows: bool, reserved: u32, } impl Default for KeyExchangeInit { fn default() -> KeyExchangeInit { // Setup the cookie (16 random bytes). let mut cookie = [0; 16]; let mut rng = rand::thread_rng(); for x in &mut cookie { *x = rng.gen::<u8>(); } // Setup the default key exchange algorithms. Order is important here. let mut kex_algos = Vec::new(); kex_algos.push(Curve25519Sha256.to_string()); kex_algos.push(ExchangeSha256.to_string()); // Setup teh default server host key algorithms. Order is important. let mut shk_algos = Vec::new(); shk_algos.push(SshEd25519.to_string()); shk_algos.push(SshRsa.to_string()); // Setup the default encryption client-to-server algorithms. Order is important. let mut enc_c2s_algos = Vec::new(); enc_c2s_algos.push(Aes256Cbc.to_string()); enc_c2s_algos.push(Twofish256Cbc.to_string()); enc_c2s_algos.push(Serpent256Cbc.to_string()); enc_c2s_algos.push(Aes192Cbc.to_string()); enc_c2s_algos.push(Twofish192Cbc.to_string()); enc_c2s_algos.push(Serpent192Cbc.to_string()); enc_c2s_algos.push(Aes128Cbc.to_string()); enc_c2s_algos.push(Twofish128Cbc.to_string()); enc_c2s_algos.push(Serpent128Cbc.to_string()); enc_c2s_algos.push(Cast128Cbc.to_string()); enc_c2s_algos.push(IdeaCbc.to_string()); enc_c2s_algos.push(BlowfishCbc.to_string()); enc_c2s_algos.push(TripleDesCbc.to_string()); enc_c2s_algos.push(Arcfour.to_string()); enc_c2s_algos.push(NoEnc.to_string()); // Setup the default encryption server-to-client algorithms. let enc_s2c_algos = enc_c2s_algos.clone(); // Setup the default mac client-to-server algorithms. let mut mac_c2s_algos = Vec::new(); mac_c2s_algos.push(HmacSha1.to_string()); mac_c2s_algos.push(HmacSha1NinetySix.to_string()); mac_c2s_algos.push(HmacMd5.to_string()); mac_c2s_algos.push(HmacMd5NinetySix.to_string()); mac_c2s_algos.push(NoMac.to_string()); // Setup the default mac server-to-client algorithms. let mac_s2c_algos = mac_c2s_algos.clone(); // Setup the default compression client-to-server algorithms. let mut comp_c2s_algos = Vec::new(); comp_c2s_algos.push(Xz.to_string()); comp_c2s_algos.push(Zlib.to_string()); comp_c2s_algos.push(NoComp.to_string()); // Setup the default compression server-to-client algorithms. let comp_s2c_algos = comp_c2s_algos.clone(); KeyExchangeInit { id: 20, cookie: cookie, kex_algorithms: kex_algos, server_host_key_algorithms: shk_algos, encryption_algorithms_client_to_server: enc_c2s_algos, encryption_algorithms_server_to_client: enc_s2c_algos, mac_algorithms_client_to_server: mac_c2s_algos, mac_algorithms_server_to_client: mac_s2c_algos, compression_algorithms_client_to_server: comp_c2s_algos, compression_algorithms_server_to_client: comp_s2c_algos, languages_client_to_server: Vec::new(), languages_server_to_client: Vec::new(), first_kex_packet_follows: false, reserved: 0, } } } impl KeyExchangeInit { pub fn into_bytes(self) -> NailResult<Vec<u8>> { let mut kex_packet = Vec::new(); try!(kex_packet.write_u32::<BigEndian>(self.id)); kex_packet.extend_from_slice(&self.cookie); try!(write_name_list(&mut kex_packet, &self.kex_algorithms)); try!(write_name_list(&mut kex_packet, &self.server_host_key_algorithms)); try!(write_name_list(&mut kex_packet, &self.encryption_algorithms_client_to_server)); try!(write_name_list(&mut kex_packet, &self.encryption_algorithms_server_to_client)); try!(write_name_list(&mut kex_packet, &self.mac_algorithms_client_to_server)); try!(write_name_list(&mut kex_packet, &self.mac_algorithms_server_to_client)); try!(write_name_list(&mut kex_packet, &self.compression_algorithms_client_to_server)); try!(write_name_list(&mut kex_packet, &self.compression_algorithms_server_to_client)); try!(write_name_list(&mut kex_packet, &self.languages_client_to_server)); try!(write_name_list(&mut kex_packet, &self.languages_server_to_client)); if self.first_kex_packet_follows { kex_packet.push(0) } else { kex_packet.push(1) } try!(kex_packet.write_u32::<BigEndian>(self.reserved));<|fim▁hole|> pub fn from_bytes(bytes: Vec<u8>) -> NailResult<KeyExchangeInit> { let mut iter = bytes.into_iter(); // Get the Message Type Byte let idv = iter.by_ref().take(4).collect::<Vec<u8>>(); let mut rdr = Cursor::new(&idv); let id = try!(rdr.read_u32::<BigEndian>()); // Get the cookie let mut cookie = [0; 16]; for (b, x) in iter.by_ref().take(16).zip(cookie.iter_mut()) { *x = b; } let kex_algs = try!(read_name_list(&mut iter)); let shk_algs = try!(read_name_list(&mut iter)); let enc_c2s_algs = try!(read_name_list(&mut iter)); let enc_s2c_algs = try!(read_name_list(&mut iter)); let mac_c2s_algs = try!(read_name_list(&mut iter)); let mac_s2c_algs = try!(read_name_list(&mut iter)); let comp_s2c_algs = try!(read_name_list(&mut iter)); let comp_c2s_algs = try!(read_name_list(&mut iter)); let lang_c2s_algs = try!(read_name_list(&mut iter)); let lang_s2c_algs = try!(read_name_list(&mut iter)); let first_kex_packet_follows = if let Some(fkpf) = iter.by_ref().next() { fkpf == 0 } else { false }; let mut reserved_cursor = Cursor::new(iter.by_ref().take(4).collect::<Vec<u8>>()); let reserved = try!(reserved_cursor.read_u32::<BigEndian>()); Ok(KeyExchangeInit { id: id, cookie: cookie, kex_algorithms: kex_algs, server_host_key_algorithms: shk_algs, encryption_algorithms_client_to_server: enc_c2s_algs, encryption_algorithms_server_to_client: enc_s2c_algs, mac_algorithms_client_to_server: mac_c2s_algs, mac_algorithms_server_to_client: mac_s2c_algs, compression_algorithms_client_to_server: comp_c2s_algs, compression_algorithms_server_to_client: comp_s2c_algs, languages_client_to_server: lang_c2s_algs, languages_server_to_client: lang_s2c_algs, first_kex_packet_follows: first_kex_packet_follows, reserved: reserved, }) } pub fn kex_algorithms(&self) -> &Vec<String> { &self.kex_algorithms } } fn read_name_list<I: Iterator<Item = u8>>(iter: &mut I) -> NailResult<Vec<String>> { let mut outv = Vec::new(); let mut name_list_cursor = Cursor::new(iter.by_ref().take(4).collect::<Vec<u8>>()); let name_list_len = try!(name_list_cursor.read_u32::<BigEndian>()); outv.extend(iter.by_ref().take(name_list_len as usize)); let name_list = String::from_utf8_lossy(&outv); let names: Vec<String> = name_list.split(',').map(|x| x.to_string()).collect(); Ok(names) } #[cfg_attr(feature="clippy", allow(cast_possible_truncation))] fn write_name_list(packet: &mut Vec<u8>, name_list: &[String]) -> NailResult<()> { let joined = name_list.join(","); let len = joined.len(); try!(packet.write_u32::<BigEndian>(len as u32)); packet.extend(joined.bytes()); Ok(()) } #[cfg(test)] mod test { use std::default::Default; use super::KeyExchangeInit; #[test] fn kex_default() { let kex: KeyExchangeInit = Default::default(); assert!(kex.id == 20); assert!(kex.cookie.len() == 16); assert!(!kex.first_kex_packet_follows); assert!(kex.reserved == 0); } #[test] #[cfg_attr(feature="clippy", allow(indexing_slicing, use_debug))] fn kex_from_bytes() { let kex: KeyExchangeInit = Default::default(); if let Ok(kex_bytes) = kex.into_bytes() { assert!(&kex_bytes[0..4] == [0, 0, 0, 20]); } else { assert!(false) } } }<|fim▁end|>
Ok(kex_packet) }
<|file_name|>HeartbeatManager.java<|end_file_name|><|fim▁begin|>package ch.spacebase.openclassic.api; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; import ch.spacebase.openclassic.api.util.Constants; /** * Manages the server's web heartbeats. */ public final class HeartbeatManager { private static final long salt = new SecureRandom().nextLong(); private static final Map<String, Runnable> customBeats = new HashMap<String, Runnable>(); private static String url = ""; /** * Gets the server's current salt. * @return The server's salt. */ public static long getSalt() { return salt; } /** * Gets the server's minecraft.net url. * @return The url. */ public static String getURL() { return url; } /** * Sets the server's known minecraft.net url. * @param url The url. */ public static void setURL(String url) { HeartbeatManager.url = url; } /** * Triggers a heartbeat. */ public static void beat() { mineBeat(); womBeat(); for(String id : customBeats.keySet()) { try { customBeats.get(id).run(); } catch(Exception e) { OpenClassic.getLogger().severe("Exception while running a custom heartbeat with the ID \"" + id + "\"!"); e.printStackTrace(); } } } /** * Adds a custom heartbeat to run when {@link beat()} is called.<|fim▁hole|> * @param run Runnable to call when beating. */ public static void addBeat(String id, Runnable run) { customBeats.put(id, run); } /** * Removes a custom heartbeat. * @param id ID of the heartbeat. */ public static void removeBeat(String id) { customBeats.remove(id); } /** * Clears the custom heartbeat list. */ public static void clearBeats() { customBeats.clear(); } private static void mineBeat() { URL url = null; try { url = new URL("https://minecraft.net/heartbeat.jsp?port=" + OpenClassic.getServer().getPort() + "&max=" + OpenClassic.getServer().getMaxPlayers() + "&name=" + URLEncoder.encode(Color.stripColor(OpenClassic.getServer().getServerName()), "UTF-8") + "&public=" + OpenClassic.getServer().isPublic() + "&version=" + Constants.PROTOCOL_VERSION + "&salt=" + salt + "&users=" + OpenClassic.getServer().getPlayers().size()); } catch(MalformedURLException e) { OpenClassic.getLogger().severe("Malformed URL while attempting minecraft.net heartbeat?"); return; } catch(UnsupportedEncodingException e) { OpenClassic.getLogger().severe("UTF-8 URL encoding is unsupported on your system."); return; } HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); try { conn.setRequestMethod("GET"); } catch (ProtocolException e) { OpenClassic.getLogger().severe("Exception while performing minecraft.net heartbeat: Connection doesn't support GET...?"); return; } conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); InputStream input = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String result = reader.readLine(); reader.close(); input.close(); if(!HeartbeatManager.url.equals(result)) { HeartbeatManager.url = result; OpenClassic.getLogger().info(Color.GREEN + "The server's URL is now \"" + getURL() + "\"."); try { File file = new File(OpenClassic.getGame().getDirectory(), "server-address.txt"); if(!file.exists()) file.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(result); writer.close(); } catch(IOException e) { OpenClassic.getLogger().severe("Failed to save server address!"); e.printStackTrace(); } } } catch (IOException e) { OpenClassic.getLogger().severe("Exception while performing minecraft.net heartbeat!"); e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); } } private static void womBeat() { URL url = null; try { url = new URL("http://direct.worldofminecraft.com/hb.php?port=" + OpenClassic.getServer().getPort() + "&max=" + OpenClassic.getServer().getMaxPlayers() + "&name=" + URLEncoder.encode(Color.stripColor(OpenClassic.getServer().getServerName()), "UTF-8") + "&public=" + OpenClassic.getServer().isPublic() + "&version=" + Constants.PROTOCOL_VERSION + "&salt=" + salt + "&users=" + OpenClassic.getServer().getPlayers().size() + "&noforward=1"); } catch(MalformedURLException e) { OpenClassic.getLogger().severe("Malformed URL while attempting WOM heartbeat?"); return; } catch(UnsupportedEncodingException e) { OpenClassic.getLogger().severe("UTF-8 URL encoding is unsupported on your system."); return; } HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(false); conn.setDoInput(false); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); } catch (IOException e) { OpenClassic.getLogger().severe("Exception while performing WOM heartbeat!"); e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); } } }<|fim▁end|>
* @param id ID of the custom heartbeat.
<|file_name|>RespawnGui.java<|end_file_name|><|fim▁begin|>package io.github.phantamanta44.pwarfare.gui; import io.github.phantamanta44.pwarfare.Game; import io.github.phantamanta44.pwarfare.data.GameMap; import io.github.phantamanta44.pwarfare.data.GameMap.GameMode; import io.github.phantamanta44.pwarfare.data.GamePlayer; import io.github.phantamanta44.pwarfare.data.GamePlayer.GameTeam; import io.github.phantamanta44.pwarfare.data.GamePlayer.PlayerState; import io.github.phantamanta44.pwarfare.data.GameSquad; import io.github.phantamanta44.pwarfare.objective.ConqObjective; import io.github.phantamanta44.pwarfare.util.StackFactory; import net.md_5.bungee.api.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.ItemStack; public class RespawnGui extends GameGui { public static final String[] classNames = new String[] {"ASSAULT", "ENGINEER", "SUPPORT", "RECON"}; private GamePlayer player; private boolean canRespawn = false; private Object point; public RespawnGui(GamePlayer pl) { super("DEPLOY", 5); player = pl; generateLoadoutGui(); inv.setItem(40, StackFactory.generateStack(Material.BOOK, 1, 0, "Edit Loadout")); inv.setItem(43, StackFactory.generateStack(Material.STAINED_GLASS_PANE, 1, 8, ChatColor.AQUA + "DEPLOY")); inv.setItem(44, StackFactory.generateStack(Material.STAINED_GLASS_PANE, player.getTimeToRespawn(), 8, ChatColor.AQUA + "DEPLOY")); if (Game.INSTANCE.getCurrentMap().getGameMode() == GameMode.CONQ) setupConqGui(); } private void setupConqGui() { ConqObjective obj = (ConqObjective)Game.INSTANCE.getCurrentMap().getObjective(); ItemStack blueIs = StackFactory.generateStack(Material.STAINED_GLASS_PANE, 1, 11, ChatColor.DARK_GRAY + "Select a spawn point."); ItemStack greenIs = StackFactory.generateStack(Material.STAINED_GLASS_PANE, 1, 5, ChatColor.DARK_GRAY + "Select a spawn point."); for (int y = 0; y < 3; y++) { for (int x = 0; x < 9; x++) inv.setItem(y * 9 + x, blueIs); } for (int i = 0; i < 9; i++) inv.setItem(27 + i, greenIs); inv.setItem(10, StackFactory.generateStack(Material.STAINED_CLAY, 1, 9, "Deploy on Team Spawn")); for (int i = 0; i < 3; i++) { GameTeam flagOwner = obj.getFlagStatus(i); if (flagOwner == player.getTeam()) inv.setItem(i * 2 + 12, StackFactory.generateStack(Material.STAINED_CLAY, 1, 14, ChatColor.BLUE + "Deploy on Point " + ConqObjective.flagName[i])); else if (flagOwner == GameTeam.NONE) inv.setItem(i * 2 + 12, StackFactory.generateStack(Material.WOOL, 1, 0, "Point " + ConqObjective.flagName[i])); else inv.setItem(i * 2 + 12, StackFactory.generateStack(Material.STAINED_CLAY, 1, 1, "Point " + ConqObjective.flagName[i])); } GameSquad squad = player.getSquad(); if (squad != null) { for (int i = 0; i < 3; i++) { try { GamePlayer member = squad.members.get(i); if (member.getState() == PlayerState.INGAME) inv.setItem(27 + i, StackFactory.generateStack(Material.ARMOR_STAND, 1, 0, ChatColor.BLUE + "Deploy on " + member.getName())); else inv.setItem(27 + i, StackFactory.generateStack(Material.STEP, 1, 0, member.getPlayer().getName())); } catch (Throwable th) { } } } } private void generateLoadoutGui() { for (int i = 36; i <= 39; i++) inv.setItem(i, StackFactory.generateStack(Material.STAINED_GLASS, 1, player.getKitIndex() == (i - 36) ? 9 : 8, classNames[i - 36]));<|fim▁hole|> } @Override protected void inventoryClicked(InventoryClickEvent event) { event.setCancelled(true); if (event.getCurrentItem() != null) { ItemStack stack = event.getCurrentItem(); if (event.getSlot() >= 36 && event.getSlot() <= 39) { player.setKit(event.getSlot() - 36); generateLoadoutGui(); } else if (event.getSlot() == 40) { killGui(); new LoadoutGui(player).showGui(player.getPlayer()); } else if (event.getSlot() >= 43) { if (canRespawn && point != null) { if (point instanceof Location) player.getPlayer().teleport((Location)point); else if (point instanceof Entity) player.getPlayer().teleport((Entity)point); player.receiveKit(); player.setState(PlayerState.INGAME); } } else if (Game.INSTANCE.getCurrentMap().getGameMode() == GameMode.CONQ) onConqClick(stack, event); } } @SuppressWarnings("deprecation") private void onConqClick(ItemStack stack, InventoryClickEvent event) { GameMap map = Game.INSTANCE.getCurrentMap(); if (event.getSlot() == 10) { point = map.getSpawnPoint(player.getTeam()); setupConqGui(); inv.setItem(10, StackFactory.generateStack(Material.STAINED_GLASS, 1, 5, "Deploy on Team Spawn")); } else if (event.getSlot() == 12) { if (stack.getData().getData() == (byte)14) { point = ((ConqObjective)map.getObjective()).getCap(0).toLocation(map.getWorld()); setupConqGui(); inv.setItem(12, StackFactory.generateStack(Material.STAINED_GLASS, 1, 5, ChatColor.BLUE + "Deploy on Point A")); } } else if (event.getSlot() == 14) { if (stack.getData().getData() == (byte)14) { point = ((ConqObjective)map.getObjective()).getCap(1).toLocation(map.getWorld()); setupConqGui(); inv.setItem(14, StackFactory.generateStack(Material.STAINED_GLASS, 1, 5, ChatColor.BLUE + "Deploy on Point B")); } } else if (event.getSlot() == 16) { if (stack.getData().getData() == (byte)14) { point = ((ConqObjective)map.getObjective()).getCap(2).toLocation(map.getWorld()); setupConqGui(); inv.setItem(16, StackFactory.generateStack(Material.STAINED_GLASS, 1, 5, ChatColor.BLUE + "Deploy on Point C")); } } else if (event.getSlot() >= 27 && event.getSlot() <= 29) { int i = 27 - event.getSlot(); if (player.getSquad() != null && player.getSquad().members.size() >= i) { point = player.getSquad().members.get(i).getPlayer(); setupConqGui(); inv.setItem(event.getSlot(), StackFactory.generateStack(Material.STAINED_GLASS, 1, 5, ChatColor.BLUE + "Deploy on " + player.getSquad().members.get(i).getName())); } } } @Override public void tick(long tick) { if (player.getTimeToRespawn() <= 0) { if (canRespawn = false) { canRespawn = true; for (int i = 0; i < 2; i++) inv.setItem(43 + i, StackFactory.generateStack(Material.STAINED_GLASS_PANE, 1, 9, ChatColor.AQUA + "DEPLOY")); } } else inv.getItem(44).setAmount(player.getTimeToRespawn()); } }<|fim▁end|>
<|file_name|>loadbalancer_test.go<|end_file_name|><|fim▁begin|>// Copyright 2018 Authors of Cilium // // 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. // +build !privileged_tests package loadbalancer import ( "testing" "gopkg.in/check.v1" ) // Hook up gocheck into the "go test" runner. func Test(t *testing.T) { check.TestingT(t) } type TypesSuite struct{} var _ = check.Suite(&TypesSuite{}) func TestL4Addr_Equals(t *testing.T) { type args struct { o *L4Addr } tests := []struct { name string fields *L4Addr args args want bool }{ { name: "both equal", fields: &L4Addr{ Protocol: NONE, Port: 1, }, args: args{ o: &L4Addr{ Protocol: NONE, Port: 1, }, }, want: true, }, { name: "both different", fields: &L4Addr{ Protocol: NONE, Port: 0, }, args: args{ o: &L4Addr{ Protocol: NONE, Port: 1, }, }, want: false, }, { name: "both nil", args: args{}, want: true, }, { name: "other nil", fields: &L4Addr{ Protocol: NONE, Port: 1, }, args: args{}, want: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { l := tt.fields if got := l.Equals(tt.args.o); got != tt.want { t.Errorf("L4Addr.Equals() = %v, want %v", got, tt.want) } }) } } func TestFEPort_EqualsIgnoreID(t *testing.T) { type args struct { o *FEPort } tests := []struct { name string fields *FEPort args args want bool }{ { name: "both equal", fields: &FEPort{ L4Addr: &L4Addr{ Protocol: NONE, Port: 1, }, ID: 1, }, args: args{ o: &FEPort{ L4Addr: &L4Addr{ Protocol: NONE,<|fim▁hole|> }, want: true, }, { name: "IDs different are considered equal", fields: &FEPort{ L4Addr: &L4Addr{ Protocol: NONE, Port: 1, }, ID: 1, }, args: args{ o: &FEPort{ L4Addr: &L4Addr{ Protocol: NONE, Port: 1, }, ID: 1001, }, }, want: true, }, { name: "both nil", args: args{}, want: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { f := tt.fields if got := f.EqualsIgnoreID(tt.args.o); got != tt.want { t.Errorf("FEPort.EqualsIgnoreID() = %v, want %v", got, tt.want) } }) } } func TestFEPort_Equals(t *testing.T) { type args struct { o *FEPort } tests := []struct { name string fields *FEPort args args want bool }{ { name: "both equal", fields: &FEPort{ L4Addr: &L4Addr{ Protocol: NONE, Port: 1, }, ID: 1, }, args: args{ o: &FEPort{ L4Addr: &L4Addr{ Protocol: NONE, Port: 1, }, ID: 1, }, }, want: true, }, { name: "IDs different are considered different", fields: &FEPort{ L4Addr: &L4Addr{ Protocol: NONE, Port: 1, }, ID: 1, }, args: args{ o: &FEPort{ L4Addr: &L4Addr{ Protocol: NONE, Port: 1, }, ID: 1001, }, }, want: false, }, { name: "both nil", args: args{}, want: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { f := tt.fields if got := f.Equals(tt.args.o); got != tt.want { t.Errorf("FEPort.Equals() = %v, want %v", got, tt.want) } }) } }<|fim▁end|>
Port: 1, }, ID: 1, },
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use concurrency_manager::ConcurrencyManager; use criterion::{black_box, BatchSize, Bencher, Criterion}; use kvproto::kvrpcpb::Context; use test_util::KvGenerator; use tikv::storage::kv::{Engine, WriteData}; use tikv::storage::mvcc::{self, MvccReader, MvccTxn, SnapshotReader}; use tikv::storage::txn::{ cleanup, commit, prewrite, CommitKind, TransactionKind, TransactionProperties, }; use txn_types::{Key, Mutation, TimeStamp}; use super::{BenchConfig, EngineFactory, DEFAULT_ITERATIONS, DEFAULT_KV_GENERATOR_SEED}; fn setup_prewrite<E, F>( engine: &E, config: &BenchConfig<F>, start_ts: impl Into<TimeStamp>, ) -> (E::Snap, Vec<Key>) where E: Engine, F: EngineFactory<E>, { let ctx = Context::default(); let snapshot = engine.snapshot(Default::default()).unwrap(); let start_ts = start_ts.into(); let cm = ConcurrencyManager::new(start_ts); let mut txn = MvccTxn::new(start_ts, cm); let mut reader = SnapshotReader::new(start_ts, snapshot, true); let kvs = KvGenerator::with_seed( config.key_length, config.value_length, DEFAULT_KV_GENERATOR_SEED, ) .generate(DEFAULT_ITERATIONS); for (k, v) in &kvs { let txn_props = TransactionProperties { start_ts, kind: TransactionKind::Optimistic(false), commit_kind: CommitKind::TwoPc, primary: &k.clone(), txn_size: 0, lock_ttl: 0, min_commit_ts: TimeStamp::default(), need_old_value: false, }; prewrite( &mut txn, &mut reader, &txn_props, Mutation::Put((Key::from_raw(&k), v.clone())), &None, false, ) .unwrap(); } let write_data = WriteData::from_modifies(txn.into_modifies()); let _ = engine.async_write(&ctx, write_data, Box::new(move |(..)| {})); let keys: Vec<Key> = kvs.iter().map(|(k, _)| Key::from_raw(&k)).collect(); let snapshot = engine.snapshot(Default::default()).unwrap(); (snapshot, keys) } fn mvcc_prewrite<E: Engine, F: EngineFactory<E>>(b: &mut Bencher, config: &BenchConfig<F>) { let engine = config.engine_factory.build(); let cm = ConcurrencyManager::new(1.into()); b.iter_batched( || { let mutations: Vec<(Mutation, Vec<u8>)> = KvGenerator::with_seed( config.key_length, config.value_length, DEFAULT_KV_GENERATOR_SEED, ) .generate(DEFAULT_ITERATIONS) .iter() .map(|(k, v)| (Mutation::Put((Key::from_raw(&k), v.clone())), k.clone())) .collect(); let snapshot = engine.snapshot(Default::default()).unwrap(); (mutations, snapshot) }, |(mutations, snapshot)| { for (mutation, primary) in mutations { let mut txn = mvcc::MvccTxn::new(1.into(), cm.clone()); let mut reader = SnapshotReader::new(1.into(), snapshot.clone(), true); let txn_props = TransactionProperties { start_ts: TimeStamp::default(), kind: TransactionKind::Optimistic(false), commit_kind: CommitKind::TwoPc, primary: &primary, txn_size: 0, lock_ttl: 0, min_commit_ts: TimeStamp::default(), need_old_value: false, }; prewrite(&mut txn, &mut reader, &txn_props, mutation, &None, false).unwrap(); } }, BatchSize::SmallInput, ) } fn mvcc_commit<E: Engine, F: EngineFactory<E>>(b: &mut Bencher, config: &BenchConfig<F>) { let engine = config.engine_factory.build(); let cm = ConcurrencyManager::new(1.into()); b.iter_batched( || setup_prewrite(&engine, &config, 1), |(snapshot, keys)| { for key in keys { let mut txn = mvcc::MvccTxn::new(1.into(), cm.clone()); let mut reader = SnapshotReader::new(1.into(), snapshot.clone(), true); black_box(commit(&mut txn, &mut reader, key, 1.into())).unwrap(); } }, BatchSize::SmallInput, ); } fn mvcc_rollback_prewrote<E: Engine, F: EngineFactory<E>>( b: &mut Bencher, config: &BenchConfig<F>, ) { let engine = config.engine_factory.build(); let cm = ConcurrencyManager::new(1.into()); b.iter_batched( || setup_prewrite(&engine, &config, 1), |(snapshot, keys)| { for key in keys { let mut txn = mvcc::MvccTxn::new(1.into(), cm.clone()); let mut reader = SnapshotReader::new(1.into(), snapshot.clone(), true); black_box(cleanup( &mut txn, &mut reader, key, TimeStamp::zero(), false, )) .unwrap(); } }, BatchSize::SmallInput, ) } fn mvcc_rollback_conflict<E: Engine, F: EngineFactory<E>>( b: &mut Bencher, config: &BenchConfig<F>, ) { let engine = config.engine_factory.build();<|fim▁hole|> let cm = ConcurrencyManager::new(1.into()); b.iter_batched( || setup_prewrite(&engine, &config, 2), |(snapshot, keys)| { for key in keys { let mut txn = mvcc::MvccTxn::new(1.into(), cm.clone()); let mut reader = SnapshotReader::new(1.into(), snapshot.clone(), true); black_box(cleanup( &mut txn, &mut reader, key, TimeStamp::zero(), false, )) .unwrap(); } }, BatchSize::SmallInput, ) } fn mvcc_rollback_non_prewrote<E: Engine, F: EngineFactory<E>>( b: &mut Bencher, config: &BenchConfig<F>, ) { let engine = config.engine_factory.build(); let cm = ConcurrencyManager::new(1.into()); b.iter_batched( || { let kvs = KvGenerator::with_seed( config.key_length, config.value_length, DEFAULT_KV_GENERATOR_SEED, ) .generate(DEFAULT_ITERATIONS); let keys: Vec<Key> = kvs.iter().map(|(k, _)| Key::from_raw(&k)).collect(); let snapshot = engine.snapshot(Default::default()).unwrap(); (snapshot, keys) }, |(snapshot, keys)| { for key in keys { let mut txn = mvcc::MvccTxn::new(1.into(), cm.clone()); let mut reader = SnapshotReader::new(1.into(), snapshot.clone(), true); black_box(cleanup( &mut txn, &mut reader, key, TimeStamp::zero(), false, )) .unwrap(); } }, BatchSize::SmallInput, ) } fn mvcc_reader_load_lock<E: Engine, F: EngineFactory<E>>(b: &mut Bencher, config: &BenchConfig<F>) { let engine = config.engine_factory.build(); let test_keys: Vec<Key> = KvGenerator::with_seed( config.key_length, config.value_length, DEFAULT_KV_GENERATOR_SEED, ) .generate(DEFAULT_ITERATIONS) .iter() .map(|(k, _)| Key::from_raw(&k)) .collect(); b.iter_batched( || { let snapshot = engine.snapshot(Default::default()).unwrap(); (snapshot, &test_keys) }, |(snapshot, test_kvs)| { for key in test_kvs { let mut reader = MvccReader::new(snapshot.clone(), None, true); black_box(reader.load_lock(&key).unwrap()); } }, BatchSize::SmallInput, ); } fn mvcc_reader_seek_write<E: Engine, F: EngineFactory<E>>( b: &mut Bencher, config: &BenchConfig<F>, ) { let engine = config.engine_factory.build(); b.iter_batched( || { let snapshot = engine.snapshot(Default::default()).unwrap(); let test_keys: Vec<Key> = KvGenerator::with_seed( config.key_length, config.value_length, DEFAULT_KV_GENERATOR_SEED, ) .generate(DEFAULT_ITERATIONS) .iter() .map(|(k, _)| Key::from_raw(&k)) .collect(); (snapshot, test_keys) }, |(snapshot, test_keys)| { for key in &test_keys { let mut reader = MvccReader::new(snapshot.clone(), None, true); black_box(reader.seek_write(&key, TimeStamp::max()).unwrap()); } }, BatchSize::SmallInput, ); } pub fn bench_mvcc<E: Engine, F: EngineFactory<E>>(c: &mut Criterion, configs: &[BenchConfig<F>]) { let mut group = c.benchmark_group("mvcc"); for config in configs { group.bench_with_input(format!("prewrite/{:?}", config), config, mvcc_prewrite); group.bench_with_input(format!("commit/{:?}", config), config, mvcc_commit); group.bench_with_input( format!("rollback_prewrote/{:?}", config), config, mvcc_rollback_prewrote, ); group.bench_with_input( format!("rollback_conflict/{:?}", config), config, mvcc_rollback_conflict, ); group.bench_with_input( format!("rollback_non_prewrote/{:?}", config), config, mvcc_rollback_non_prewrote, ); group.bench_with_input( format!("load_lock/{:?}", config), config, mvcc_reader_load_lock, ); group.bench_with_input( format!("seek_write/{:?}", config), config, mvcc_reader_seek_write, ); } group.finish(); }<|fim▁end|>
<|file_name|>0005_auto_20160621_1438.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.10a1 on 2016-06-21 09:08 from __future__ import unicode_literals from django.conf import settings<|fim▁hole|>from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('discussions', '0004_post_author'), ] operations = [ migrations.AlterField( model_name='post', name='author', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]<|fim▁end|>
<|file_name|>XceiverClientSpi.java<|end_file_name|><|fim▁begin|>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdds.scm; import com.google.common.annotations.VisibleForTesting; import org.apache.hadoop.hdds.scm.container.common.helpers.Pipeline; import org.apache.hadoop.hdds.protocol.DatanodeDetails; import org.apache.hadoop.hdds.protocol.proto.ContainerProtos .ContainerCommandRequestProto; import org.apache.hadoop.hdds.protocol.proto.ContainerProtos .ContainerCommandResponseProto; import org.apache.hadoop.hdds.protocol.proto.HddsProtos; import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; /** * A Client for the storageContainer protocol. */ public abstract class XceiverClientSpi implements Closeable { final private AtomicInteger referenceCount; private boolean isEvicted; XceiverClientSpi() { this.referenceCount = new AtomicInteger(0); this.isEvicted = false; } void incrementReference() { this.referenceCount.incrementAndGet(); } void decrementReference() { this.referenceCount.decrementAndGet(); cleanup(); } void setEvicted() { isEvicted = true; cleanup(); } // close the xceiverClient only if, // 1) there is no refcount on the client // 2) it has been evicted from the cache. private void cleanup() { if (referenceCount.get() == 0 && isEvicted) { close(); } } @VisibleForTesting public int getRefcount() { return referenceCount.get(); } /** * Connects to the leader in the pipeline. */ public abstract void connect() throws Exception; @Override public abstract void close(); /** * Returns the pipeline of machines that host the container used by this * client. * * @return pipeline of machines that host the container */ public abstract Pipeline getPipeline(); /** * Sends a given command to server and gets the reply back. * @param request Request * @return Response to the command * @throws IOException */ public abstract ContainerCommandResponseProto sendCommand( ContainerCommandRequestProto request) throws IOException; <|fim▁hole|> * @return Response to the command * @throws IOException */ public abstract CompletableFuture<ContainerCommandResponseProto> sendCommandAsync(ContainerCommandRequestProto request) throws IOException, ExecutionException, InterruptedException; /** * Create a pipeline. * * @param pipelineID - Name of the pipeline. * @param datanodes - Datanodes */ public abstract void createPipeline(String pipelineID, List<DatanodeDetails> datanodes) throws IOException; /** * Returns pipeline Type. * * @return - {Stand_Alone, Ratis or Chained} */ public abstract HddsProtos.ReplicationType getPipelineType(); }<|fim▁end|>
/** * Sends a given command to server gets a waitable future back. * * @param request Request
<|file_name|>memory.js<|end_file_name|><|fim▁begin|>// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- var promises = require('../utilities/promises'), log = require('../logger'); module.exports = function (tables) { log.warn('The memory data provider is deprecated and will be removed from future versions. Use the sqlite provider instead.'); tables = tables || {}; return function (table) { return { read: function (query) { // need to evaluate query against each item before returning return promises.resolved(values(table)); }, update: function (item) { items(table)[item.id] = item; return promises.resolved(item); }, insert: function (item) { items(table)[item.id] = item; return promises.resolved(item); }, delete: function (id, version) { delete items(table)[id]; return promises.resolved(id); }, undelete: function (id) { // unsupported return promises.resolved({ id: id }); }, truncate: function () { tables[table.name] = {}; return promises.resolved(); }, initialize: function () { return promises.resolved(); } } <|fim▁hole|> if(!tables[name]) tables[name] = {}; return tables[name]; } function values(table) { var tableItems = items(table); return Object.keys(tableItems).map(function (id) { return tableItems[id]; }); } }; };<|fim▁end|>
function items(table) { var name = table.name.toLowerCase();
<|file_name|>Calibrate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # ====================================================================== import pangloss import sys,getopt,cPickle,numpy import scipy.stats as stats # ====================================================================== def Calibrate(argv): """ NAME Calibrate.py PURPOSE Transform the results of the lightcone reconstruction process, Pr(kappah|D), into our target PDF, Pr(kappa|D). COMMENTS All PDF input is provided as a list of samples. There are two modes of operation: 1) The Pr(kappah|C) for an ensemble of calibration lightcones are compressed into a single number (currently the median), and then combined with the true kappa values to make Pr(kappa,kappah|C). This is written out as a 2D sample list. 2) The Pr(kappah|D) for a single observed lightcone is compressed into a single number (currently the median). This is then used to take a slice from Pr(kappa,kappah|C) to make Pr(kappa|D,C). Both 1 and 2 can be carried out in series if desired (Mode=3). FLAGS -h Print this message [0] INPUTS configfile Plain text file containing Pangloss configuration OPTIONAL INPUTS --mode Operating mode 1,2 or 3. See COMMENTS above. OUTPUTS stdout Useful information samples From 1) Pr(kappa,kappah|C) or 2) Pr(kappa|D,C) EXAMPLE Calibrate.py example.config BUGS AUTHORS This file is part of the Pangloss project, distributed under the GPL v2, by Tom Collett (IoA) and Phil Marshall (Oxford). Please cite: Collett et al 2013, http://arxiv.org/abs/1303.6564 HISTORY 2013-03-21 started Collett & Marshall (Oxford) """ # -------------------------------------------------------------------- try: opts, args = getopt.getopt(argv,"hm:",["help","mode"]) except getopt.GetoptError, err: print str(err) # will print something like "option -a not recognized" print Calibrate.__doc__ # will print the big comment above. return Mode=3 for o,a in opts: if o in ("-h", "--help"): print Calibrate.__doc__ return elif o in ("-m", "--mode"): Mode = int(a) assert Mode < 4 and Mode >0, "unhandled Mode" else: assert False, "unhandled option" # Check for setup file in array args: if len(args) == 1: configfile = args[0] print pangloss.doubledashedline print pangloss.hello print pangloss.doubledashedline print "Calibrate: transforming Pr(kappah|D) to Pr(kappa|D)" print "Calibrate: taking instructions from",configfile else: print Calibrate.__doc__ return # -------------------------------------------------------------------- # Read in configuration, and extract the ones we need: experiment = pangloss.Configuration(configfile) EXP_NAME = experiment.parameters['ExperimentName'] Nc = experiment.parameters['NCalibrationLightcones'] comparator=experiment.parameters['Comparator'] comparatorType=experiment.parameters['ComparatorType'] comparatorWidth=experiment.parameters['ComparatorWidth'] # Figure out which mode is required: ModeName = experiment.parameters['CalibrateMode'] if ModeName=='Joint': Mode = 1 if ModeName=='Slice': Mode = 2 if ModeName=='JointAndSlice': Mode = 3 CALIB_DIR = experiment.parameters['CalibrationFolder'][0] jointdistfile= CALIB_DIR+'/'+comparator+'_'+comparatorType+'.pickle' jointdistasPDFfile= CALIB_DIR+'/'+comparator+'_'+comparatorType+'_asPDF.pickle' # Final result is PDF for kappa: x = experiment.parameters['ObservedCatalog'][0] resultfile = x.split('.')[0]+"_"+EXP_NAME+"_PofKappa.pickle" # -------------------------------------------------------------------- # Mode 1: generate a joint distribution, eg Pr(kappah,kappa) # from the calibration dataset: if Mode==1 or Mode==3: print pangloss.dashedline # First find the calibration pdfs for kappa_h: calpickles = [] for i in range(Nc): calpickles.append(experiment.getLightconePickleName('simulated',pointing=i)) calresultpickles=[] if comparator=="Kappah" and comparatorType=="median": for i in range(Nc): x = calpickles[i] pfile = x.split('.')[0].split("_lightcone")[0]+"_"+EXP_NAME+"_KappaHilbert_Kappah_median.pickle" calresultpickles.append(pfile) elif comparator=="Kappah" and comparatorType!="median": for i in range(Nc): x = calpickles[i] pfile = x.split('.')[0].split("_lightcone")[0]+"_"+EXP_NAME+"_KappaHilbert_Kappah_"+comparatorType+".pickle" calresultpickles.append(pfile) else: print "Calibrate: Unrecognised comparator "+Comparator print "Calibrate: If you want to use a comparator other than kappa_h, " print "Calibrate: you'll need to code it up!" print "Calibrate: (This should be easy, but you can ask [email protected] for help)." exit() # Now calculate comparators: callist=numpy.empty((Nc,2)) jd=pangloss.PDF(["kappa_ext",comparator+'_'+comparatorType]) for i in range(Nc): C = calresultpickles[i] pdf = pangloss.readPickle(C) if comparator=="Kappah": if comparatorType=="median": # Recall that we created a special file for this # choice of comparator and comparator type, in # Reconstruct. You could also use the # comparatortype=="mean" code, swapping mean for median. callist[i,0]=pdf[0] callist[i,1]=pdf[1][0] elif comparatorType=="mean": callist[i,0] = pdf.truth[0] callist[i,1] = numpy.mean(pdf.samples) else: print "Calibrate: Unrecognised comparatorType "+comparatorType print "Calibrate: If you want to use a comparatorType other than median " print "Calibrate: or mean, you'll need to code it up!" print "Calibrate: (This should be easy, but you can ask [email protected] for help)." exit() jd.append(callist[i]) pangloss.writePickle(callist,jointdistfile) # Also store the joint dist as a pangloss pdf: pangloss.writePickle(jd,jointdistasPDFfile) # Plot: plotfile = jointdistasPDFfile.split('.')[0]+'.png' jd.plot("Kappah_median","kappa_ext",weight=None,output=plotfile,title="The joint distribution of $\kappa_{\mathrm{ext}}$ and calibrator \n\n (more correlated means a better calibrator!)") print "Calibrate: calibration joint PDF saved in:" print "Calibrate: "+jointdistfile print "Calibrate: and "+jointdistasPDFfile print "Calibrate: you can view this PDF in "+plotfile # -------------------------------------------------------------------- # Mode 2: calibrate a real line of sight's Pr(kappah|D) using the<|fim▁hole|> # joint distribution Pr(kappa,<kappah>|D) if Mode==2 or Mode==3: print pangloss.dashedline callibguide = pangloss.readPickle(jointdistfile) obspickle = experiment.getLightconePickleName('real') pfile = obspickle.split('.')[0].split("_lightcone")[0]+'_'+EXP_NAME+"_PofKappah.pickle" pdf=pangloss.readPickle(pfile) if comparator=="Kappah": if comparatorType=="median":# note we created a special file for this choice of comparator and comparator type. You could also use the comparatortype=="mean" code swapping mean for median. RealComparator=numpy.median(pdf.samples) elif comparatorType=="mean": RealComparator=numpy.mean(pdf.samples) else: print "I don't know that comparatorType. exiting" exit() pdf = pangloss.PDF(["kappa_ext","weight"]) #print RealComparator #print numpy.median(callibguide[:,1]),numpy.std(callibguide[:,1]) dif=(callibguide[:,1]-RealComparator) weights=dif*0.0 weights[numpy.abs(dif)<comparatorWidth]=1. weights/=numpy.sum(weights) samples=callibguide[:,0] samplesandweights=callibguide.copy() samplesandweights[:,1]=weights pdf.samples=(samplesandweights) plotfile = resultfile.split('.')[0]+".png" pdf.plot('kappa_ext',weight='weight',output=plotfile) average = numpy.average(samples, weights=weights) variance = numpy.dot(weights, (samples-average)**2)/weights.sum() average,std=average, variance**.5 #if step function weights can calculate 68%CL easily: included=samples[weights>0] onesigconfidence=numpy.abs(\ stats.scoreatpercentile(included,84)- stats.scoreatpercentile(included,16)\ )/2. pangloss.writePickle(pdf,resultfile) print "Calibrate: your reconstructed lightcone has been calibrated," print "Calibrate: suggesting it has a kappa_ext of",\ "%.3f +\- %.3f"%(average,onesigconfidence) print "Calibrate: the PDF for kappa_ext has been output to "+resultfile print "Calibrate: in the form of sample kappa_ext values, and their weights." print "Calibrate: you can view this PDF in "+plotfile print print "Calibrate: To read and process this file, try:" print print " import pangloss" print " pdf = pangloss.readPickle(\"%s\")"%resultfile print " kappa_samples = pdf.getParameter(\"kappa_ext\")" print " kappa_weights = pdf.getParameter(\"weight\")" # -------------------------------------------------------------------- print print pangloss.doubledashedline return resultfile,jointdistasPDFfile # ====================================================================== if __name__ == '__main__': Calibrate(sys.argv[1:]) # ======================================================================<|fim▁end|>
<|file_name|>AppRouter.js<|end_file_name|><|fim▁begin|>/** * * app.js * * This is the entry file for the application * */ import FilmLocationSearchComponent from '../MovieSearchApp/Containers/FilmSearchContainer/FilmSearchComponent'; import AppComponent from '../CommonComponent/app.js'; import React from 'react'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; console.log("current href",window.location.href);<|fim▁hole|> <Route component={FilmLocationSearchComponent} path='/searchmovies' /> </Route> ); } export { getAppRouter }<|fim▁end|>
const getAppRouter = () => { return ( <Route component={AppComponent}>
<|file_name|>api.go<|end_file_name|><|fim▁begin|>// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package translate import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) const opText = "TranslateText" // TextRequest generates a "aws/request.Request" representing the // client's request for the Text operation. The "output" return // value will be populated with the request's response once the request complets // successfuly. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // // See Text for more information on using the Text // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // // // Example sending a request using the TextRequest method. // req, resp := client.TextRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // // See also, https://docs.aws.amazon.com/goto/WebAPI/translate-2017-07-01/Text func (c *Translate) TextRequest(input *TextInput) (req *request.Request, output *TextOutput) { op := &request.Operation{ Name: opText, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &TextInput{} } output = &TextOutput{} req = c.newRequest(op, input, output) return }<|fim▁hole|>// Translates input text from the source language to the target language. You // can translate between English (en) and one of the following languages, or // between one of the following languages and English. // // * Arabic (ar) // // * Chinese (Simplified) (zh) // // * French (fr) // // * German (de) // // * Portuguese (pt) // // * Spanish (es) // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for Amazon Translate's // API operation Text for usage and error information. // // Returned Error Codes: // * ErrCodeInvalidRequestException "InvalidRequestException" // The request is invalid. // // * ErrCodeTextSizeLimitExceededException "TextSizeLimitExceededException" // The size of the input text exceeds the length constraint for the Text field. // Try again with a shorter text. // // * ErrCodeTooManyRequestsException "TooManyRequestsException" // The number of requests exceeds the limit. Resubmit your request later. // // * ErrCodeUnsupportedLanguagePairException "UnsupportedLanguagePairException" // Amazon Translate cannot translate input text in the source language into // this target language. For more information, see how-to-error-msg. // // * ErrCodeInternalServerException "InternalServerException" // An internal server error occurred. Retry your request. // // * ErrCodeServiceUnavailableException "ServiceUnavailableException" // Amazon Translate is unavailable. Retry your request later. // // See also, https://docs.aws.amazon.com/goto/WebAPI/translate-2017-07-01/Text func (c *Translate) Text(input *TextInput) (*TextOutput, error) { req, out := c.TextRequest(input) return out, req.Send() } // TextWithContext is the same as Text with the addition of // the ability to pass a context and additional request options. // // See Text for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. func (c *Translate) TextWithContext(ctx aws.Context, input *TextInput, opts ...request.Option) (*TextOutput, error) { req, out := c.TextRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } type TextInput struct { _ struct{} `type:"structure"` // One of the supported language codes for the source text. If the TargetLanguageCode // is not "en", the SourceLanguageCode must be "en". // // SourceLanguageCode is a required field SourceLanguageCode *string `min:"2" type:"string" required:"true"` // One of the supported language codes for the target text. If the SourceLanguageCode // is not "en", the TargetLanguageCode must be "en". // // TargetLanguageCode is a required field TargetLanguageCode *string `min:"2" type:"string" required:"true"` // The text to translate. // // Text is a required field Text *string `min:"1" type:"string" required:"true"` } // String returns the string representation func (s TextInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s TextInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. func (s *TextInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "TextInput"} if s.SourceLanguageCode == nil { invalidParams.Add(request.NewErrParamRequired("SourceLanguageCode")) } if s.SourceLanguageCode != nil && len(*s.SourceLanguageCode) < 2 { invalidParams.Add(request.NewErrParamMinLen("SourceLanguageCode", 2)) } if s.TargetLanguageCode == nil { invalidParams.Add(request.NewErrParamRequired("TargetLanguageCode")) } if s.TargetLanguageCode != nil && len(*s.TargetLanguageCode) < 2 { invalidParams.Add(request.NewErrParamMinLen("TargetLanguageCode", 2)) } if s.Text == nil { invalidParams.Add(request.NewErrParamRequired("Text")) } if s.Text != nil && len(*s.Text) < 1 { invalidParams.Add(request.NewErrParamMinLen("Text", 1)) } if invalidParams.Len() > 0 { return invalidParams } return nil } // SetSourceLanguageCode sets the SourceLanguageCode field's value. func (s *TextInput) SetSourceLanguageCode(v string) *TextInput { s.SourceLanguageCode = &v return s } // SetTargetLanguageCode sets the TargetLanguageCode field's value. func (s *TextInput) SetTargetLanguageCode(v string) *TextInput { s.TargetLanguageCode = &v return s } // SetText sets the Text field's value. func (s *TextInput) SetText(v string) *TextInput { s.Text = &v return s } type TextOutput struct { _ struct{} `type:"structure"` // The language code for the language of the input text. // // SourceLanguageCode is a required field SourceLanguageCode *string `min:"2" type:"string" required:"true"` // The language code for the language of the translated text. // // TargetLanguageCode is a required field TargetLanguageCode *string `min:"2" type:"string" required:"true"` // The text translated into the target language. // // TranslatedText is a required field TranslatedText *string `min:"1" type:"string" required:"true"` } // String returns the string representation func (s TextOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s TextOutput) GoString() string { return s.String() } // SetSourceLanguageCode sets the SourceLanguageCode field's value. func (s *TextOutput) SetSourceLanguageCode(v string) *TextOutput { s.SourceLanguageCode = &v return s } // SetTargetLanguageCode sets the TargetLanguageCode field's value. func (s *TextOutput) SetTargetLanguageCode(v string) *TextOutput { s.TargetLanguageCode = &v return s } // SetTranslatedText sets the TranslatedText field's value. func (s *TextOutput) SetTranslatedText(v string) *TextOutput { s.TranslatedText = &v return s }<|fim▁end|>
// Text API operation for Amazon Translate. //
<|file_name|>web3.js<|end_file_name|><|fim▁begin|>require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ module.exports=[ { "constant": true, "inputs": [ { "name": "_owner", "type": "address" } ], "name": "name", "outputs": [ { "name": "o_name", "type": "bytes32" } ], "type": "function" }, { "constant": true, "inputs": [ { "name": "_name", "type": "bytes32" } ], "name": "owner", "outputs": [ { "name": "", "type": "address" } ], "type": "function" }, { "constant": true, "inputs": [ { "name": "_name", "type": "bytes32" } ], "name": "content", "outputs": [ { "name": "", "type": "bytes32" } ], "type": "function" }, { "constant": true, "inputs": [ { "name": "_name", "type": "bytes32" } ], "name": "addr", "outputs": [ { "name": "", "type": "address" } ], "type": "function" }, { "constant": false, "inputs": [ { "name": "_name", "type": "bytes32" } ], "name": "reserve", "outputs": [], "type": "function" }, { "constant": true, "inputs": [ { "name": "_name", "type": "bytes32" } ], "name": "subRegistrar", "outputs": [ { "name": "", "type": "address" } ], "type": "function" }, { "constant": false, "inputs": [ { "name": "_name", "type": "bytes32" }, { "name": "_newOwner", "type": "address" } ], "name": "transfer", "outputs": [], "type": "function" }, { "constant": false, "inputs": [ { "name": "_name", "type": "bytes32" }, { "name": "_registrar", "type": "address" } ], "name": "setSubRegistrar", "outputs": [], "type": "function" }, { "constant": false, "inputs": [], "name": "Registrar", "outputs": [], "type": "function" }, { "constant": false, "inputs": [ { "name": "_name", "type": "bytes32" }, { "name": "_a", "type": "address" }, { "name": "_primary", "type": "bool" } ], "name": "setAddress", "outputs": [], "type": "function" }, { "constant": false, "inputs": [ { "name": "_name", "type": "bytes32" }, { "name": "_content", "type": "bytes32" } ], "name": "setContent", "outputs": [], "type": "function" }, { "constant": false, "inputs": [ { "name": "_name", "type": "bytes32" } ], "name": "disown", "outputs": [], "type": "function" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "_name", "type": "bytes32" }, { "indexed": false, "name": "_winner", "type": "address" } ], "name": "AuctionEnded", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "_name", "type": "bytes32" }, { "indexed": false, "name": "_bidder", "type": "address" }, { "indexed": false, "name": "_value", "type": "uint256" } ], "name": "NewBid", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "name", "type": "bytes32" } ], "name": "Changed", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "name", "type": "bytes32" }, { "indexed": true, "name": "addr", "type": "address" } ], "name": "PrimaryChanged", "type": "event" } ] },{}],2:[function(require,module,exports){ module.exports=[ { "constant": true, "inputs": [ { "name": "_name", "type": "bytes32" } ], "name": "owner", "outputs": [ { "name": "", "type": "address" } ], "type": "function" }, { "constant": false, "inputs": [ { "name": "_name", "type": "bytes32" }, { "name": "_refund", "type": "address" } ], "name": "disown", "outputs": [], "type": "function" }, { "constant": true, "inputs": [ { "name": "_name", "type": "bytes32" } ], "name": "addr", "outputs": [ { "name": "", "type": "address" } ], "type": "function" }, { "constant": false, "inputs": [ { "name": "_name", "type": "bytes32" } ], "name": "reserve", "outputs": [], "type": "function" }, { "constant": false, "inputs": [ { "name": "_name", "type": "bytes32" }, { "name": "_newOwner", "type": "address" } ], "name": "transfer", "outputs": [], "type": "function" }, { "constant": false, "inputs": [ { "name": "_name", "type": "bytes32" }, { "name": "_a", "type": "address" } ], "name": "setAddr", "outputs": [], "type": "function" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "name", "type": "bytes32" } ], "name": "Changed", "type": "event" } ] },{}],3:[function(require,module,exports){ module.exports=[ { "constant": false, "inputs": [ { "name": "from", "type": "bytes32" }, { "name": "to", "type": "address" }, { "name": "value", "type": "uint256" } ], "name": "transfer", "outputs": [], "type": "function" }, { "constant": false, "inputs": [ { "name": "from", "type": "bytes32" }, { "name": "to", "type": "address" }, { "name": "indirectId", "type": "bytes32" }, { "name": "value", "type": "uint256" } ], "name": "icapTransfer", "outputs": [], "type": "function" }, { "constant": false, "inputs": [ { "name": "to", "type": "bytes32" } ], "name": "deposit", "outputs": [], "payable": true, "type": "function" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "from", "type": "address" }, { "indexed": false, "name": "value", "type": "uint256" } ], "name": "AnonymousDeposit", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "from", "type": "address" }, { "indexed": true, "name": "to", "type": "bytes32" }, { "indexed": false, "name": "value", "type": "uint256" } ], "name": "Deposit", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "from", "type": "bytes32" }, { "indexed": true, "name": "to", "type": "address" }, { "indexed": false, "name": "value", "type": "uint256" } ], "name": "Transfer", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "from", "type": "bytes32" }, { "indexed": true, "name": "to", "type": "address" }, { "indexed": false, "name": "indirectId", "type": "bytes32" }, { "indexed": false, "name": "value", "type": "uint256" } ], "name": "IcapTransfer", "type": "event" } ] },{}],4:[function(require,module,exports){ var f = require('./formatters'); var SolidityType = require('./type'); /** * SolidityTypeAddress is a prootype that represents address type * It matches: * address * address[] * address[4] * address[][] * address[3][] * address[][6][], ... */ var SolidityTypeAddress = function () { this._inputFormatter = f.formatInputInt; this._outputFormatter = f.formatOutputAddress; }; SolidityTypeAddress.prototype = new SolidityType({}); SolidityTypeAddress.prototype.constructor = SolidityTypeAddress; SolidityTypeAddress.prototype.isType = function (name) { return !!name.match(/address(\[([0-9]*)\])?/); }; module.exports = SolidityTypeAddress; },{"./formatters":9,"./type":14}],5:[function(require,module,exports){ var f = require('./formatters'); var SolidityType = require('./type'); /** * SolidityTypeBool is a prootype that represents bool type * It matches: * bool * bool[] * bool[4] * bool[][] * bool[3][] * bool[][6][], ... */ var SolidityTypeBool = function () { this._inputFormatter = f.formatInputBool; this._outputFormatter = f.formatOutputBool; }; SolidityTypeBool.prototype = new SolidityType({}); SolidityTypeBool.prototype.constructor = SolidityTypeBool; SolidityTypeBool.prototype.isType = function (name) { return !!name.match(/^bool(\[([0-9]*)\])*$/); }; module.exports = SolidityTypeBool; },{"./formatters":9,"./type":14}],6:[function(require,module,exports){ var f = require('./formatters'); var SolidityType = require('./type'); /** * SolidityTypeBytes is a prototype that represents the bytes type. * It matches: * bytes * bytes[] * bytes[4] * bytes[][] * bytes[3][] * bytes[][6][], ... * bytes32 * bytes8[4] * bytes[3][] */ var SolidityTypeBytes = function () { this._inputFormatter = f.formatInputBytes; this._outputFormatter = f.formatOutputBytes; }; SolidityTypeBytes.prototype = new SolidityType({}); SolidityTypeBytes.prototype.constructor = SolidityTypeBytes; SolidityTypeBytes.prototype.isType = function (name) { return !!name.match(/^bytes([0-9]{1,})(\[([0-9]*)\])*$/); }; module.exports = SolidityTypeBytes; },{"./formatters":9,"./type":14}],7:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file coder.js * @author Marek Kotewicz <[email protected]> * @date 2015 */ var f = require('./formatters'); var SolidityTypeAddress = require('./address'); var SolidityTypeBool = require('./bool'); var SolidityTypeInt = require('./int'); var SolidityTypeUInt = require('./uint'); var SolidityTypeDynamicBytes = require('./dynamicbytes'); var SolidityTypeString = require('./string'); var SolidityTypeReal = require('./real'); var SolidityTypeUReal = require('./ureal'); var SolidityTypeBytes = require('./bytes'); var isDynamic = function (solidityType, type) { return solidityType.isDynamicType(type) || solidityType.isDynamicArray(type); }; /** * SolidityCoder prototype should be used to encode/decode solidity params of any type */ var SolidityCoder = function (types) { this._types = types; }; /** * This method should be used to transform type to SolidityType * * @method _requireType * @param {String} type * @returns {SolidityType} * @throws {Error} throws if no matching type is found */ SolidityCoder.prototype._requireType = function (type) { var solidityType = this._types.filter(function (t) { return t.isType(type); })[0]; if (!solidityType) { throw Error('invalid solidity type!: ' + type); } return solidityType; }; /** * Should be used to encode plain param * * @method encodeParam * @param {String} type * @param {Object} plain param * @return {String} encoded plain param */ SolidityCoder.prototype.encodeParam = function (type, param) { return this.encodeParams([type], [param]); }; /** * Should be used to encode list of params * * @method encodeParams * @param {Array} types * @param {Array} params * @return {String} encoded list of params */ SolidityCoder.prototype.encodeParams = function (types, params) { var solidityTypes = this.getSolidityTypes(types); var encodeds = solidityTypes.map(function (solidityType, index) { return solidityType.encode(params[index], types[index]); }); var dynamicOffset = solidityTypes.reduce(function (acc, solidityType, index) { var staticPartLength = solidityType.staticPartLength(types[index]); var roundedStaticPartLength = Math.floor((staticPartLength + 31) / 32) * 32; return acc + (isDynamic(solidityTypes[index], types[index]) ? 32 : roundedStaticPartLength); }, 0); var result = this.encodeMultiWithOffset(types, solidityTypes, encodeds, dynamicOffset); return result; }; SolidityCoder.prototype.encodeMultiWithOffset = function (types, solidityTypes, encodeds, dynamicOffset) { var result = ""; var self = this; types.forEach(function (type, i) { if (isDynamic(solidityTypes[i], types[i])) { result += f.formatInputInt(dynamicOffset).encode(); var e = self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset); dynamicOffset += e.length / 2; } else { // don't add length to dynamicOffset. it's already counted result += self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset); } // TODO: figure out nested arrays }); types.forEach(function (type, i) { if (isDynamic(solidityTypes[i], types[i])) { var e = self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset); dynamicOffset += e.length / 2; result += e; } }); return result; }; SolidityCoder.prototype.encodeWithOffset = function (type, solidityType, encoded, offset) { /* jshint maxcomplexity: 17 */ /* jshint maxdepth: 5 */ var self = this; var encodingMode={dynamic:1,static:2,other:3}; var mode=(solidityType.isDynamicArray(type)?encodingMode.dynamic:(solidityType.isStaticArray(type)?encodingMode.static:encodingMode.other)); if(mode !== encodingMode.other){ var nestedName = solidityType.nestedName(type); var nestedStaticPartLength = solidityType.staticPartLength(nestedName); var result = (mode === encodingMode.dynamic ? encoded[0] : ''); if (solidityType.isDynamicArray(nestedName)) { var previousLength = (mode === encodingMode.dynamic ? 2 : 0); for (var i = 0; i < encoded.length; i++) { // calculate length of previous item if(mode === encodingMode.dynamic){ previousLength += +(encoded[i - 1])[0] || 0; } else if(mode === encodingMode.static){ previousLength += +(encoded[i - 1] || [])[0] || 0; } result += f.formatInputInt(offset + i * nestedStaticPartLength + previousLength * 32).encode(); } } var len= (mode === encodingMode.dynamic ? encoded.length-1 : encoded.length); for (var c = 0; c < len; c++) { var additionalOffset = result / 2; if(mode === encodingMode.dynamic){ result += self.encodeWithOffset(nestedName, solidityType, encoded[c + 1], offset + additionalOffset); } else if(mode === encodingMode.static){ result += self.encodeWithOffset(nestedName, solidityType, encoded[c], offset + additionalOffset); } } return result; } return encoded; }; /** * Should be used to decode bytes to plain param * * @method decodeParam * @param {String} type * @param {String} bytes * @return {Object} plain param */ SolidityCoder.prototype.decodeParam = function (type, bytes) { return this.decodeParams([type], bytes)[0]; }; /** * Should be used to decode list of params * * @method decodeParam * @param {Array} types * @param {String} bytes * @return {Array} array of plain params */ SolidityCoder.prototype.decodeParams = function (types, bytes) { var solidityTypes = this.getSolidityTypes(types); var offsets = this.getOffsets(types, solidityTypes); return solidityTypes.map(function (solidityType, index) { return solidityType.decode(bytes, offsets[index], types[index], index); }); }; SolidityCoder.prototype.getOffsets = function (types, solidityTypes) { var lengths = solidityTypes.map(function (solidityType, index) { return solidityType.staticPartLength(types[index]); }); for (var i = 1; i < lengths.length; i++) { // sum with length of previous element lengths[i] += lengths[i - 1]; } return lengths.map(function (length, index) { // remove the current length, so the length is sum of previous elements var staticPartLength = solidityTypes[index].staticPartLength(types[index]); return length - staticPartLength; }); }; SolidityCoder.prototype.getSolidityTypes = function (types) { var self = this; return types.map(function (type) { return self._requireType(type); }); }; var coder = new SolidityCoder([ new SolidityTypeAddress(), new SolidityTypeBool(), new SolidityTypeInt(), new SolidityTypeUInt(), new SolidityTypeDynamicBytes(), new SolidityTypeBytes(), new SolidityTypeString(), new SolidityTypeReal(), new SolidityTypeUReal() ]); module.exports = coder; },{"./address":4,"./bool":5,"./bytes":6,"./dynamicbytes":8,"./formatters":9,"./int":10,"./real":12,"./string":13,"./uint":15,"./ureal":16}],8:[function(require,module,exports){ var f = require('./formatters'); var SolidityType = require('./type'); var SolidityTypeDynamicBytes = function () { this._inputFormatter = f.formatInputDynamicBytes; this._outputFormatter = f.formatOutputDynamicBytes; }; SolidityTypeDynamicBytes.prototype = new SolidityType({}); SolidityTypeDynamicBytes.prototype.constructor = SolidityTypeDynamicBytes; SolidityTypeDynamicBytes.prototype.isType = function (name) { return !!name.match(/^bytes(\[([0-9]*)\])*$/); }; SolidityTypeDynamicBytes.prototype.isDynamicType = function () { return true; }; module.exports = SolidityTypeDynamicBytes; },{"./formatters":9,"./type":14}],9:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file formatters.js * @author Marek Kotewicz <[email protected]> * @date 2015 */ var BigNumber = require('bignumber.js'); var utils = require('../utils/utils'); var c = require('../utils/config'); var SolidityParam = require('./param'); /** * Formats input value to byte representation of int * If value is negative, return it's two's complement * If the value is floating point, round it down * * @method formatInputInt * @param {String|Number|BigNumber} value that needs to be formatted * @returns {SolidityParam} */ var formatInputInt = function (value) { BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE); var result = utils.padLeft(utils.toTwosComplement(value).toString(16), 64); return new SolidityParam(result); }; /** * Formats input bytes * * @method formatInputBytes * @param {String} * @returns {SolidityParam} */ var formatInputBytes = function (value) { var result = utils.toHex(value).substr(2); var l = Math.floor((result.length + 63) / 64); result = utils.padRight(result, l * 64); return new SolidityParam(result); }; /** * Formats input bytes * * @method formatDynamicInputBytes * @param {String} * @returns {SolidityParam} */ var formatInputDynamicBytes = function (value) { var result = utils.toHex(value).substr(2); var length = result.length / 2; var l = Math.floor((result.length + 63) / 64); result = utils.padRight(result, l * 64); return new SolidityParam(formatInputInt(length).value + result); }; /** * Formats input value to byte representation of string * * @method formatInputString * @param {String} * @returns {SolidityParam} */ var formatInputString = function (value) { var result = utils.fromUtf8(value).substr(2); var length = result.length / 2; var l = Math.floor((result.length + 63) / 64); result = utils.padRight(result, l * 64); return new SolidityParam(formatInputInt(length).value + result); }; /** * Formats input value to byte representation of bool * * @method formatInputBool * @param {Boolean} * @returns {SolidityParam} */ var formatInputBool = function (value) { var result = '000000000000000000000000000000000000000000000000000000000000000' + (value ? '1' : '0'); return new SolidityParam(result); }; /** * Formats input value to byte representation of real * Values are multiplied by 2^m and encoded as integers * * @method formatInputReal * @param {String|Number|BigNumber} * @returns {SolidityParam} */ var formatInputReal = function (value) { return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128))); }; /** * Check if input value is negative * * @method signedIsNegative * @param {String} value is hex format * @returns {Boolean} true if it is negative, otherwise false */ var signedIsNegative = function (value) { return (new BigNumber(value.substr(0, 1), 16).toString(2).substr(0, 1)) === '1'; }; /** * Formats right-aligned output bytes to int * * @method formatOutputInt * @param {SolidityParam} param * @returns {BigNumber} right-aligned output bytes formatted to big number */ var formatOutputInt = function (param) { var value = param.staticPart() || "0"; // check if it's negative number // it it is, return two's complement if (signedIsNegative(value)) { return new BigNumber(value, 16).minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16)).minus(1); } return new BigNumber(value, 16); }; /** * Formats right-aligned output bytes to uint * * @method formatOutputUInt * @param {SolidityParam} * @returns {BigNumeber} right-aligned output bytes formatted to uint */ var formatOutputUInt = function (param) { var value = param.staticPart() || "0"; return new BigNumber(value, 16); }; /** * Formats right-aligned output bytes to real * * @method formatOutputReal * @param {SolidityParam} * @returns {BigNumber} input bytes formatted to real */ var formatOutputReal = function (param) { return formatOutputInt(param).dividedBy(new BigNumber(2).pow(128)); }; /** * Formats right-aligned output bytes to ureal * * @method formatOutputUReal * @param {SolidityParam} * @returns {BigNumber} input bytes formatted to ureal */ var formatOutputUReal = function (param) { return formatOutputUInt(param).dividedBy(new BigNumber(2).pow(128)); }; /** * Should be used to format output bool * * @method formatOutputBool * @param {SolidityParam} * @returns {Boolean} right-aligned input bytes formatted to bool */ var formatOutputBool = function (param) { return param.staticPart() === '0000000000000000000000000000000000000000000000000000000000000001' ? true : false; }; /** * Should be used to format output bytes * * @method formatOutputBytes * @param {SolidityParam} left-aligned hex representation of string * @param {String} name type name * @returns {String} hex string */ var formatOutputBytes = function (param, name) { var matches = name.match(/^bytes([0-9]*)/); var size = parseInt(matches[1]); return '0x' + param.staticPart().slice(0, 2 * size); }; /** * Should be used to format output bytes * * @method formatOutputDynamicBytes * @param {SolidityParam} left-aligned hex representation of string * @returns {String} hex string */ var formatOutputDynamicBytes = function (param) { var length = (new BigNumber(param.dynamicPart().slice(0, 64), 16)).toNumber() * 2; return '0x' + param.dynamicPart().substr(64, length); }; /** * Should be used to format output string * * @method formatOutputString * @param {SolidityParam} left-aligned hex representation of string * @returns {String} ascii string */ var formatOutputString = function (param) { var length = (new BigNumber(param.dynamicPart().slice(0, 64), 16)).toNumber() * 2; return utils.toUtf8(param.dynamicPart().substr(64, length)); }; /** * Should be used to format output address * * @method formatOutputAddress * @param {SolidityParam} right-aligned input bytes * @returns {String} address */ var formatOutputAddress = function (param) { var value = param.staticPart(); return "0x" + value.slice(value.length - 40, value.length); }; module.exports = { formatInputInt: formatInputInt, formatInputBytes: formatInputBytes, formatInputDynamicBytes: formatInputDynamicBytes, formatInputString: formatInputString, formatInputBool: formatInputBool, formatInputReal: formatInputReal, formatOutputInt: formatOutputInt, formatOutputUInt: formatOutputUInt, formatOutputReal: formatOutputReal, formatOutputUReal: formatOutputUReal, formatOutputBool: formatOutputBool, formatOutputBytes: formatOutputBytes, formatOutputDynamicBytes: formatOutputDynamicBytes, formatOutputString: formatOutputString, formatOutputAddress: formatOutputAddress }; },{"../utils/config":18,"../utils/utils":20,"./param":11,"bignumber.js":"bignumber.js"}],10:[function(require,module,exports){ var f = require('./formatters'); var SolidityType = require('./type'); /** * SolidityTypeInt is a prootype that represents int type * It matches: * int * int[] * int[4] * int[][] * int[3][] * int[][6][], ... * int32 * int64[] * int8[4] * int256[][] * int[3][] * int64[][6][], ... */ var SolidityTypeInt = function () { this._inputFormatter = f.formatInputInt; this._outputFormatter = f.formatOutputInt; }; SolidityTypeInt.prototype = new SolidityType({}); SolidityTypeInt.prototype.constructor = SolidityTypeInt; SolidityTypeInt.prototype.isType = function (name) { return !!name.match(/^int([0-9]*)?(\[([0-9]*)\])*$/); }; module.exports = SolidityTypeInt; },{"./formatters":9,"./type":14}],11:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file param.js * @author Marek Kotewicz <[email protected]> * @date 2015 */ var utils = require('../utils/utils'); /** * SolidityParam object prototype. * Should be used when encoding, decoding solidity bytes */ var SolidityParam = function (value, offset) { this.value = value || ''; this.offset = offset; // offset in bytes }; /** * This method should be used to get length of params's dynamic part * * @method dynamicPartLength * @returns {Number} length of dynamic part (in bytes) */ SolidityParam.prototype.dynamicPartLength = function () { return this.dynamicPart().length / 2; }; /** * This method should be used to create copy of solidity param with different offset * * @method withOffset * @param {Number} offset length in bytes * @returns {SolidityParam} new solidity param with applied offset */ SolidityParam.prototype.withOffset = function (offset) { return new SolidityParam(this.value, offset); }; /** * This method should be used to combine solidity params together * eg. when appending an array * * @method combine * @param {SolidityParam} param with which we should combine * @param {SolidityParam} result of combination */ SolidityParam.prototype.combine = function (param) { return new SolidityParam(this.value + param.value); }; /** * This method should be called to check if param has dynamic size. * If it has, it returns true, otherwise false * * @method isDynamic * @returns {Boolean} */ SolidityParam.prototype.isDynamic = function () { return this.offset !== undefined; }; /** * This method should be called to transform offset to bytes * * @method offsetAsBytes * @returns {String} bytes representation of offset */ SolidityParam.prototype.offsetAsBytes = function () { return !this.isDynamic() ? '' : utils.padLeft(utils.toTwosComplement(this.offset).toString(16), 64); }; /** * This method should be called to get static part of param * * @method staticPart * @returns {String} offset if it is a dynamic param, otherwise value */ SolidityParam.prototype.staticPart = function () { if (!this.isDynamic()) { return this.value; } return this.offsetAsBytes(); }; /** * This method should be called to get dynamic part of param * * @method dynamicPart * @returns {String} returns a value if it is a dynamic param, otherwise empty string */ SolidityParam.prototype.dynamicPart = function () { return this.isDynamic() ? this.value : ''; }; /** * This method should be called to encode param * * @method encode * @returns {String} */ SolidityParam.prototype.encode = function () { return this.staticPart() + this.dynamicPart(); }; /** * This method should be called to encode array of params * * @method encodeList * @param {Array[SolidityParam]} params * @returns {String} */ SolidityParam.encodeList = function (params) { // updating offsets var totalOffset = params.length * 32; var offsetParams = params.map(function (param) { if (!param.isDynamic()) { return param; } var offset = totalOffset; totalOffset += param.dynamicPartLength(); return param.withOffset(offset); }); // encode everything! return offsetParams.reduce(function (result, param) { return result + param.dynamicPart(); }, offsetParams.reduce(function (result, param) { return result + param.staticPart(); }, '')); }; module.exports = SolidityParam; },{"../utils/utils":20}],12:[function(require,module,exports){ var f = require('./formatters'); var SolidityType = require('./type'); /** * SolidityTypeReal is a prootype that represents real type * It matches: * real * real[] * real[4] * real[][] * real[3][] * real[][6][], ... * real32 * real64[] * real8[4] * real256[][] * real[3][] * real64[][6][], ... */ var SolidityTypeReal = function () { this._inputFormatter = f.formatInputReal; this._outputFormatter = f.formatOutputReal; }; SolidityTypeReal.prototype = new SolidityType({}); SolidityTypeReal.prototype.constructor = SolidityTypeReal; SolidityTypeReal.prototype.isType = function (name) { return !!name.match(/real([0-9]*)?(\[([0-9]*)\])?/); }; module.exports = SolidityTypeReal; },{"./formatters":9,"./type":14}],13:[function(require,module,exports){ var f = require('./formatters'); var SolidityType = require('./type'); var SolidityTypeString = function () { this._inputFormatter = f.formatInputString; this._outputFormatter = f.formatOutputString; }; SolidityTypeString.prototype = new SolidityType({}); SolidityTypeString.prototype.constructor = SolidityTypeString; SolidityTypeString.prototype.isType = function (name) { return !!name.match(/^string(\[([0-9]*)\])*$/); }; SolidityTypeString.prototype.isDynamicType = function () { return true; }; module.exports = SolidityTypeString; },{"./formatters":9,"./type":14}],14:[function(require,module,exports){ var f = require('./formatters'); var SolidityParam = require('./param'); /** * SolidityType prototype is used to encode/decode solidity params of certain type */ var SolidityType = function (config) { this._inputFormatter = config.inputFormatter; this._outputFormatter = config.outputFormatter; }; /** * Should be used to determine if this SolidityType do match given name * * @method isType * @param {String} name * @return {Bool} true if type match this SolidityType, otherwise false */ SolidityType.prototype.isType = function (name) { throw "this method should be overrwritten for type " + name; }; /** * Should be used to determine what is the length of static part in given type * * @method staticPartLength * @param {String} name * @return {Number} length of static part in bytes */ SolidityType.prototype.staticPartLength = function (name) { // If name isn't an array then treat it like a single element array. return (this.nestedTypes(name) || ['[1]']) .map(function (type) { // the length of the nested array return parseInt(type.slice(1, -1), 10) || 1; }) .reduce(function (previous, current) { return previous * current; // all basic types are 32 bytes long }, 32); }; /** * Should be used to determine if type is dynamic array * eg: * "type[]" => true * "type[4]" => false * * @method isDynamicArray * @param {String} name * @return {Bool} true if the type is dynamic array */ SolidityType.prototype.isDynamicArray = function (name) { var nestedTypes = this.nestedTypes(name); return !!nestedTypes && !nestedTypes[nestedTypes.length - 1].match(/[0-9]{1,}/g); }; /** * Should be used to determine if type is static array * eg: * "type[]" => false * "type[4]" => true * * @method isStaticArray * @param {String} name * @return {Bool} true if the type is static array */ SolidityType.prototype.isStaticArray = function (name) { var nestedTypes = this.nestedTypes(name); return !!nestedTypes && !!nestedTypes[nestedTypes.length - 1].match(/[0-9]{1,}/g); }; /** * Should return length of static array * eg. * "int[32]" => 32 * "int256[14]" => 14 * "int[2][3]" => 3 * "int" => 1 * "int[1]" => 1 * "int[]" => 1 * * @method staticArrayLength * @param {String} name * @return {Number} static array length */ SolidityType.prototype.staticArrayLength = function (name) { var nestedTypes = this.nestedTypes(name); if (nestedTypes) { return parseInt(nestedTypes[nestedTypes.length - 1].match(/[0-9]{1,}/g) || 1); } return 1; }; /** * Should return nested type * eg. * "int[32]" => "int" * "int256[14]" => "int256" * "int[2][3]" => "int[2]" * "int" => "int" * "int[]" => "int" * * @method nestedName * @param {String} name * @return {String} nested name */ SolidityType.prototype.nestedName = function (name) { // remove last [] in name var nestedTypes = this.nestedTypes(name); if (!nestedTypes) { return name; } return name.substr(0, name.length - nestedTypes[nestedTypes.length - 1].length); }; /** * Should return true if type has dynamic size by default * such types are "string", "bytes" * * @method isDynamicType * @param {String} name * @return {Bool} true if is dynamic, otherwise false */ SolidityType.prototype.isDynamicType = function () { return false; }; /** * Should return array of nested types * eg. * "int[2][3][]" => ["[2]", "[3]", "[]"] * "int[] => ["[]"] * "int" => null * * @method nestedTypes * @param {String} name * @return {Array} array of nested types */ SolidityType.prototype.nestedTypes = function (name) { // return list of strings eg. "[]", "[3]", "[]", "[2]" return name.match(/(\[[0-9]*\])/g); }; /** * Should be used to encode the value * * @method encode * @param {Object} value * @param {String} name * @return {String} encoded value */ SolidityType.prototype.encode = function (value, name) { var self = this; if (this.isDynamicArray(name)) { return (function () { var length = value.length; // in int var nestedName = self.nestedName(name); var result = []; result.push(f.formatInputInt(length).encode()); value.forEach(function (v) { result.push(self.encode(v, nestedName)); }); return result; })(); } else if (this.isStaticArray(name)) { return (function () { var length = self.staticArrayLength(name); // in int var nestedName = self.nestedName(name); var result = []; for (var i = 0; i < length; i++) { result.push(self.encode(value[i], nestedName)); } return result; })(); } return this._inputFormatter(value, name).encode(); }; /** * Should be used to decode value from bytes * * @method decode * @param {String} bytes * @param {Number} offset in bytes * @param {String} name type name * @returns {Object} decoded value */ SolidityType.prototype.decode = function (bytes, offset, name) { var self = this; if (this.isDynamicArray(name)) { return (function () { var arrayOffset = parseInt('0x' + bytes.substr(offset * 2, 64)); // in bytes var length = parseInt('0x' + bytes.substr(arrayOffset * 2, 64)); // in int var arrayStart = arrayOffset + 32; // array starts after length; // in bytes var nestedName = self.nestedName(name); var nestedStaticPartLength = self.staticPartLength(nestedName); // in bytes var roundedNestedStaticPartLength = Math.floor((nestedStaticPartLength + 31) / 32) * 32; var result = []; for (var i = 0; i < length * roundedNestedStaticPartLength; i += roundedNestedStaticPartLength) { result.push(self.decode(bytes, arrayStart + i, nestedName)); } return result; })(); } else if (this.isStaticArray(name)) { return (function () { var length = self.staticArrayLength(name); // in int var arrayStart = offset; // in bytes var nestedName = self.nestedName(name); var nestedStaticPartLength = self.staticPartLength(nestedName); // in bytes var roundedNestedStaticPartLength = Math.floor((nestedStaticPartLength + 31) / 32) * 32; var result = []; for (var i = 0; i < length * roundedNestedStaticPartLength; i += roundedNestedStaticPartLength) { result.push(self.decode(bytes, arrayStart + i, nestedName)); } return result; })(); } else if (this.isDynamicType(name)) { return (function () { var dynamicOffset = parseInt('0x' + bytes.substr(offset * 2, 64)); // in bytes var length = parseInt('0x' + bytes.substr(dynamicOffset * 2, 64)); // in bytes var roundedLength = Math.floor((length + 31) / 32); // in int var param = new SolidityParam(bytes.substr(dynamicOffset * 2, ( 1 + roundedLength) * 64), 0); return self._outputFormatter(param, name); })(); } var length = this.staticPartLength(name); var param = new SolidityParam(bytes.substr(offset * 2, length * 2)); return this._outputFormatter(param, name); }; module.exports = SolidityType; },{"./formatters":9,"./param":11}],15:[function(require,module,exports){ var f = require('./formatters'); var SolidityType = require('./type'); /** * SolidityTypeUInt is a prootype that represents uint type * It matches: * uint * uint[] * uint[4] * uint[][] * uint[3][] * uint[][6][], ... * uint32 * uint64[] * uint8[4] * uint256[][] * uint[3][] * uint64[][6][], ... */ var SolidityTypeUInt = function () { this._inputFormatter = f.formatInputInt; this._outputFormatter = f.formatOutputUInt; }; SolidityTypeUInt.prototype = new SolidityType({}); SolidityTypeUInt.prototype.constructor = SolidityTypeUInt; SolidityTypeUInt.prototype.isType = function (name) { return !!name.match(/^uint([0-9]*)?(\[([0-9]*)\])*$/); }; module.exports = SolidityTypeUInt; },{"./formatters":9,"./type":14}],16:[function(require,module,exports){ var f = require('./formatters'); var SolidityType = require('./type'); /** * SolidityTypeUReal is a prootype that represents ureal type * It matches: * ureal * ureal[] * ureal[4] * ureal[][] * ureal[3][] * ureal[][6][], ... * ureal32 * ureal64[] * ureal8[4] * ureal256[][] * ureal[3][] * ureal64[][6][], ... */ var SolidityTypeUReal = function () { this._inputFormatter = f.formatInputReal; this._outputFormatter = f.formatOutputUReal; }; SolidityTypeUReal.prototype = new SolidityType({}); SolidityTypeUReal.prototype.constructor = SolidityTypeUReal; SolidityTypeUReal.prototype.isType = function (name) { return !!name.match(/^ureal([0-9]*)?(\[([0-9]*)\])*$/); }; module.exports = SolidityTypeUReal; },{"./formatters":9,"./type":14}],17:[function(require,module,exports){ 'use strict'; // go env doesn't have and need XMLHttpRequest if (typeof XMLHttpRequest === 'undefined') { exports.XMLHttpRequest = {}; } else { exports.XMLHttpRequest = XMLHttpRequest; // jshint ignore:line } },{}],18:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** @file config.js * @authors: * Marek Kotewicz <[email protected]> * @date 2015 */ /** * Utils * * @module utils */ /** * Utility functions * * @class [utils] config * @constructor */ /// required to define ETH_BIGNUMBER_ROUNDING_MODE var BigNumber = require('bignumber.js'); var ETH_UNITS = [ 'wei', 'kwei', 'Mwei', 'Gwei', 'szabo', 'finney', 'femtoether', 'picoether', 'nanoether', 'microether', 'milliether', 'nano', 'micro', 'milli', 'ether', 'grand', 'Mether', 'Gether', 'Tether', 'Pether', 'Eether', 'Zether', 'Yether', 'Nether', 'Dether', 'Vether', 'Uether' ]; module.exports = { ETH_PADDING: 32, ETH_SIGNATURE_LENGTH: 4, ETH_UNITS: ETH_UNITS, ETH_BIGNUMBER_ROUNDING_MODE: { ROUNDING_MODE: BigNumber.ROUND_DOWN }, ETH_POLLING_TIMEOUT: 1000/2, defaultBlock: 'latest', defaultAccount: undefined }; },{"bignumber.js":"bignumber.js"}],19:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file sha3.js * @author Marek Kotewicz <[email protected]> * @date 2015 */ var CryptoJS = require('crypto-js'); var sha3 = require('crypto-js/sha3'); module.exports = function (value, options) { if (options && options.encoding === 'hex') { if (value.length > 2 && value.substr(0, 2) === '0x') { value = value.substr(2); } value = CryptoJS.enc.Hex.parse(value); } return sha3(value, { outputLength: 256 }).toString(); }; },{"crypto-js":58,"crypto-js/sha3":79}],20:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file utils.js * @author Marek Kotewicz <[email protected]> * @date 2015 */ /** * Utils * * @module utils */ /** * Utility functions * * @class [utils] utils * @constructor */ var BigNumber = require('bignumber.js'); var sha3 = require('./sha3.js'); var utf8 = require('utf8'); var unitMap = { 'noether': '0', 'wei': '1', 'kwei': '1000', 'Kwei': '1000', 'babbage': '1000', 'femtoether': '1000', 'mwei': '1000000', 'Mwei': '1000000', 'lovelace': '1000000', 'picoether': '1000000', 'gwei': '1000000000', 'Gwei': '1000000000', 'shannon': '1000000000', 'nanoether': '1000000000', 'nano': '1000000000', 'szabo': '1000000000000', 'microether': '1000000000000', 'micro': '1000000000000', 'finney': '1000000000000000', 'milliether': '1000000000000000', 'milli': '1000000000000000', 'ether': '1000000000000000000', 'kether': '1000000000000000000000', 'grand': '1000000000000000000000', 'mether': '1000000000000000000000000', 'gether': '1000000000000000000000000000', 'tether': '1000000000000000000000000000000' }; /** * Should be called to pad string to expected length * * @method padLeft * @param {String} string to be padded * @param {Number} characters that result string should have * @param {String} sign, by default 0 * @returns {String} right aligned string */ var padLeft = function (string, chars, sign) { return new Array(chars - string.length + 1).join(sign ? sign : "0") + string; }; /** * Should be called to pad string to expected length * * @method padRight * @param {String} string to be padded * @param {Number} characters that result string should have * @param {String} sign, by default 0 * @returns {String} right aligned string */ var padRight = function (string, chars, sign) { return string + (new Array(chars - string.length + 1).join(sign ? sign : "0")); }; /** * Should be called to get utf8 from it's hex representation * * @method toUtf8 * @param {String} string in hex * @returns {String} ascii string representation of hex value */ var toUtf8 = function(hex) { // Find termination var str = ""; var i = 0, l = hex.length; if (hex.substring(0, 2) === '0x') { i = 2; } for (; i < l; i+=2) { var code = parseInt(hex.substr(i, 2), 16); if (code === 0) break; str += String.fromCharCode(code); } return utf8.decode(str); }; /** * Should be called to get ascii from it's hex representation * * @method toAscii * @param {String} string in hex * @returns {String} ascii string representation of hex value */ var toAscii = function(hex) { // Find termination var str = ""; var i = 0, l = hex.length; if (hex.substring(0, 2) === '0x') { i = 2; } for (; i < l; i+=2) { var code = parseInt(hex.substr(i, 2), 16); str += String.fromCharCode(code); } return str; }; /** * Should be called to get hex representation (prefixed by 0x) of utf8 string * * @method fromUtf8 * @param {String} string * @param {Number} optional padding * @returns {String} hex representation of input string */ var fromUtf8 = function(str) { str = utf8.encode(str); var hex = ""; for(var i = 0; i < str.length; i++) { var code = str.charCodeAt(i); if (code === 0) break; var n = code.toString(16); hex += n.length < 2 ? '0' + n : n; } return "0x" + hex; }; /** * Should be called to get hex representation (prefixed by 0x) of ascii string * * @method fromAscii * @param {String} string * @param {Number} optional padding * @returns {String} hex representation of input string */ var fromAscii = function(str) { var hex = ""; for(var i = 0; i < str.length; i++) { var code = str.charCodeAt(i); var n = code.toString(16); hex += n.length < 2 ? '0' + n : n; } return "0x" + hex; }; /** * Should be used to create full function/event name from json abi * * @method transformToFullName * @param {Object} json-abi * @return {String} full fnction/event name */ var transformToFullName = function (json) { if (json.name.indexOf('(') !== -1) { return json.name; } var typeName = json.inputs.map(function(i){return i.type; }).join(); return json.name + '(' + typeName + ')'; }; /** * Should be called to get display name of contract function * * @method extractDisplayName * @param {String} name of function/event * @returns {String} display name for function/event eg. multiply(uint256) -> multiply */ var extractDisplayName = function (name) { var length = name.indexOf('('); return length !== -1 ? name.substr(0, length) : name; }; /// @returns overloaded part of function/event name var extractTypeName = function (name) { /// TODO: make it invulnerable var length = name.indexOf('('); return length !== -1 ? name.substr(length + 1, name.length - 1 - (length + 1)).replace(' ', '') : ""; }; /** * Converts value to it's decimal representation in string * * @method toDecimal * @param {String|Number|BigNumber} * @return {String} */ var toDecimal = function (value) { return toBigNumber(value).toNumber(); }; /** * Converts value to it's hex representation * * @method fromDecimal * @param {String|Number|BigNumber} * @return {String} */ var fromDecimal = function (value) { var number = toBigNumber(value); var result = number.toString(16); return number.lessThan(0) ? '-0x' + result.substr(1) : '0x' + result; }; /** * Auto converts any given value into it's hex representation. * * And even stringifys objects before. * * @method toHex * @param {String|Number|BigNumber|Object} * @return {String} */ var toHex = function (val) { /*jshint maxcomplexity: 8 */ if (isBoolean(val)) return fromDecimal(+val); if (isBigNumber(val)) return fromDecimal(val); if (typeof val === 'object') return fromUtf8(JSON.stringify(val)); // if its a negative number, pass it through fromDecimal if (isString(val)) { if (val.indexOf('-0x') === 0) return fromDecimal(val); else if(val.indexOf('0x') === 0) return val; else if (!isFinite(val)) return fromAscii(val); } return fromDecimal(val); }; /** * Returns value of unit in Wei * * @method getValueOfUnit * @param {String} unit the unit to convert to, default ether * @returns {BigNumber} value of the unit (in Wei) * @throws error if the unit is not correct:w */ var getValueOfUnit = function (unit) { unit = unit ? unit.toLowerCase() : 'ether'; var unitValue = unitMap[unit]; if (unitValue === undefined) { throw new Error('This unit doesn\'t exists, please use the one of the following units' + JSON.stringify(unitMap, null, 2)); } return new BigNumber(unitValue, 10); }; /** * Takes a number of wei and converts it to any other ether unit. * * Possible units are: * SI Short SI Full Effigy Other * - kwei femtoether babbage * - mwei picoether lovelace * - gwei nanoether shannon nano * - -- microether szabo micro * - -- milliether finney milli * - ether -- -- * - kether -- grand * - mether * - gether * - tether * * @method fromWei * @param {Number|String} number can be a number, number string or a HEX of a decimal * @param {String} unit the unit to convert to, default ether * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number */ var fromWei = function(number, unit) { var returnValue = toBigNumber(number).dividedBy(getValueOfUnit(unit)); return isBigNumber(number) ? returnValue : returnValue.toString(10); }; /** * Takes a number of a unit and converts it to wei. * * Possible units are: * SI Short SI Full Effigy Other * - kwei femtoether babbage * - mwei picoether lovelace * - gwei nanoether shannon nano * - -- microether szabo micro * - -- microether szabo micro * - -- milliether finney milli * - ether -- -- * - kether -- grand * - mether * - gether * - tether * * @method toWei * @param {Number|String|BigNumber} number can be a number, number string or a HEX of a decimal * @param {String} unit the unit to convert from, default ether * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number */ var toWei = function(number, unit) { var returnValue = toBigNumber(number).times(getValueOfUnit(unit)); return isBigNumber(number) ? returnValue : returnValue.toString(10); }; /** * Takes an input and transforms it into an bignumber * * @method toBigNumber * @param {Number|String|BigNumber} a number, string, HEX string or BigNumber * @return {BigNumber} BigNumber */ var toBigNumber = function(number) { /*jshint maxcomplexity:5 */ number = number || 0; if (isBigNumber(number)) return number; if (isString(number) && (number.indexOf('0x') === 0 || number.indexOf('-0x') === 0)) { return new BigNumber(number.replace('0x',''), 16); } return new BigNumber(number.toString(10), 10); }; /** * Takes and input transforms it into bignumber and if it is negative value, into two's complement * * @method toTwosComplement * @param {Number|String|BigNumber} * @return {BigNumber} */ var toTwosComplement = function (number) { var bigNumber = toBigNumber(number).round(); if (bigNumber.lessThan(0)) { return new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(bigNumber).plus(1); } return bigNumber; }; /** * Checks if the given string is strictly an address * * @method isStrictAddress * @param {String} address the given HEX adress * @return {Boolean} */ var isStrictAddress = function (address) { return /^0x[0-9a-f]{40}$/i.test(address); }; /** * Checks if the given string is an address * * @method isAddress * @param {String} address the given HEX adress * @return {Boolean} */ var isAddress = function (address) { if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) { // check if it has the basic requirements of an address return false; } else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) { // If it's all small caps or all all caps, return true return true; } else { // Otherwise check each case return isChecksumAddress(address); } }; /** * Checks if the given string is a checksummed address * * @method isChecksumAddress * @param {String} address the given HEX adress * @return {Boolean} */ var isChecksumAddress = function (address) { // Check each case address = address.replace('0x',''); var addressHash = sha3(address.toLowerCase()); for (var i = 0; i < 40; i++ ) { // the nth letter should be uppercase if the nth digit of casemap is 1 if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) { return false; } } return true; }; /** * Makes a checksum address * * @method toChecksumAddress * @param {String} address the given HEX adress * @return {String} */ var toChecksumAddress = function (address) { if (typeof address === 'undefined') return ''; address = address.toLowerCase().replace('0x',''); var addressHash = sha3(address); var checksumAddress = '0x'; for (var i = 0; i < address.length; i++ ) { // If ith character is 9 to f then make it uppercase if (parseInt(addressHash[i], 16) > 7) { checksumAddress += address[i].toUpperCase(); } else { checksumAddress += address[i]; } } return checksumAddress; }; /** * Transforms given string to valid 20 bytes-length addres with 0x prefix * * @method toAddress * @param {String} address * @return {String} formatted address */ var toAddress = function (address) { if (isStrictAddress(address)) { return address; } if (/^[0-9a-f]{40}$/.test(address)) { return '0x' + address; } return '0x' + padLeft(toHex(address).substr(2), 40); }; /** * Returns true if object is BigNumber, otherwise false * * @method isBigNumber * @param {Object} * @return {Boolean} */ var isBigNumber = function (object) { return object instanceof BigNumber || (object && object.constructor && object.constructor.name === 'BigNumber'); }; /** * Returns true if object is string, otherwise false * * @method isString * @param {Object} * @return {Boolean} */ var isString = function (object) { return typeof object === 'string' || (object && object.constructor && object.constructor.name === 'String'); }; /** * Returns true if object is function, otherwise false * * @method isFunction * @param {Object} * @return {Boolean} */ var isFunction = function (object) { return typeof object === 'function'; }; /** * Returns true if object is Objet, otherwise false * * @method isObject * @param {Object} * @return {Boolean} */ var isObject = function (object) { return object !== null && !(Array.isArray(object)) && typeof object === 'object'; }; /** * Returns true if object is boolean, otherwise false * * @method isBoolean * @param {Object} * @return {Boolean} */ var isBoolean = function (object) { return typeof object === 'boolean'; }; /** * Returns true if object is array, otherwise false * * @method isArray * @param {Object} * @return {Boolean} */ var isArray = function (object) { return Array.isArray(object); }; /** * Returns true if given string is valid json object * * @method isJson * @param {String} * @return {Boolean} */ var isJson = function (str) { try { return !!JSON.parse(str); } catch (e) { return false; } }; /** * Returns true if given string is a valid Ethereum block header bloom. * * @method isBloom * @param {String} hex encoded bloom filter * @return {Boolean} */ var isBloom = function (bloom) { if (!/^(0x)?[0-9a-f]{512}$/i.test(bloom)) { return false; } else if (/^(0x)?[0-9a-f]{512}$/.test(bloom) || /^(0x)?[0-9A-F]{512}$/.test(bloom)) { return true; } return false; }; /** * Returns true if given string is a valid log topic. * * @method isTopic * @param {String} hex encoded topic * @return {Boolean} */ var isTopic = function (topic) { if (!/^(0x)?[0-9a-f]{64}$/i.test(topic)) { return false; } else if (/^(0x)?[0-9a-f]{64}$/.test(topic) || /^(0x)?[0-9A-F]{64}$/.test(topic)) { return true; } return false; }; module.exports = { padLeft: padLeft, padRight: padRight, toHex: toHex, toDecimal: toDecimal, fromDecimal: fromDecimal, toUtf8: toUtf8, toAscii: toAscii, fromUtf8: fromUtf8, fromAscii: fromAscii, transformToFullName: transformToFullName, extractDisplayName: extractDisplayName, extractTypeName: extractTypeName, toWei: toWei, fromWei: fromWei, toBigNumber: toBigNumber, toTwosComplement: toTwosComplement, toAddress: toAddress, isBigNumber: isBigNumber, isStrictAddress: isStrictAddress, isAddress: isAddress, isChecksumAddress: isChecksumAddress, toChecksumAddress: toChecksumAddress, isFunction: isFunction, isString: isString, isObject: isObject, isBoolean: isBoolean, isArray: isArray, isJson: isJson, isBloom: isBloom, isTopic: isTopic, }; },{"./sha3.js":19,"bignumber.js":"bignumber.js","utf8":84}],21:[function(require,module,exports){ module.exports={ "version": "0.20.2" } },{}],22:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file web3.js * @authors: * Jeffrey Wilcke <[email protected]> * Marek Kotewicz <[email protected]> * Marian Oancea <[email protected]> * Fabian Vogelsteller <[email protected]> * Gav Wood <[email protected]> * @date 2014 */ var RequestManager = require('./web3/requestmanager'); var Iban = require('./web3/iban'); var Eth = require('./web3/methods/eth'); var DB = require('./web3/methods/db'); var Shh = require('./web3/methods/shh'); var Net = require('./web3/methods/net'); var Personal = require('./web3/methods/personal'); var Swarm = require('./web3/methods/swarm'); var Settings = require('./web3/settings'); var version = require('./version.json'); var utils = require('./utils/utils'); var sha3 = require('./utils/sha3'); var extend = require('./web3/extend'); var Batch = require('./web3/batch'); var Property = require('./web3/property'); var HttpProvider = require('./web3/httpprovider'); var IpcProvider = require('./web3/ipcprovider'); var BigNumber = require('bignumber.js'); function Web3 (provider) { this._requestManager = new RequestManager(provider); this.currentProvider = provider; this.eth = new Eth(this); this.db = new DB(this); this.shh = new Shh(this); this.net = new Net(this); this.personal = new Personal(this); this.bzz = new Swarm(this); this.settings = new Settings(); this.version = { api: version.version }; this.providers = { HttpProvider: HttpProvider, IpcProvider: IpcProvider }; this._extend = extend(this); this._extend({ properties: properties() }); } // expose providers on the class Web3.providers = { HttpProvider: HttpProvider, IpcProvider: IpcProvider }; Web3.prototype.setProvider = function (provider) { this._requestManager.setProvider(provider); this.currentProvider = provider; }; Web3.prototype.reset = function (keepIsSyncing) { this._requestManager.reset(keepIsSyncing); this.settings = new Settings(); }; Web3.prototype.BigNumber = BigNumber; Web3.prototype.toHex = utils.toHex; Web3.prototype.toAscii = utils.toAscii; Web3.prototype.toUtf8 = utils.toUtf8; Web3.prototype.fromAscii = utils.fromAscii; Web3.prototype.fromUtf8 = utils.fromUtf8; Web3.prototype.toDecimal = utils.toDecimal; Web3.prototype.fromDecimal = utils.fromDecimal; Web3.prototype.toBigNumber = utils.toBigNumber; Web3.prototype.toWei = utils.toWei; Web3.prototype.fromWei = utils.fromWei; Web3.prototype.isAddress = utils.isAddress; Web3.prototype.isChecksumAddress = utils.isChecksumAddress; Web3.prototype.toChecksumAddress = utils.toChecksumAddress; Web3.prototype.isIBAN = utils.isIBAN; Web3.prototype.padLeft = utils.padLeft; Web3.prototype.padRight = utils.padRight; Web3.prototype.sha3 = function(string, options) { return '0x' + sha3(string, options); }; /** * Transforms direct icap to address */ Web3.prototype.fromICAP = function (icap) { var iban = new Iban(icap); return iban.address(); }; var properties = function () { return [ new Property({ name: 'version.node', getter: 'web3_clientVersion' }), new Property({ name: 'version.network', getter: 'net_version', inputFormatter: utils.toDecimal }), new Property({ name: 'version.ethereum', getter: 'eth_protocolVersion', inputFormatter: utils.toDecimal }), new Property({ name: 'version.whisper', getter: 'shh_version', inputFormatter: utils.toDecimal }) ]; }; Web3.prototype.isConnected = function(){ return (this.currentProvider && this.currentProvider.isConnected()); }; Web3.prototype.createBatch = function () { return new Batch(this); }; module.exports = Web3; },{"./utils/sha3":19,"./utils/utils":20,"./version.json":21,"./web3/batch":24,"./web3/extend":28,"./web3/httpprovider":32,"./web3/iban":33,"./web3/ipcprovider":34,"./web3/methods/db":37,"./web3/methods/eth":38,"./web3/methods/net":39,"./web3/methods/personal":40,"./web3/methods/shh":41,"./web3/methods/swarm":42,"./web3/property":45,"./web3/requestmanager":46,"./web3/settings":47,"bignumber.js":"bignumber.js"}],23:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file allevents.js * @author Marek Kotewicz <[email protected]> * @date 2014 */ var sha3 = require('../utils/sha3'); var SolidityEvent = require('./event'); var formatters = require('./formatters'); var utils = require('../utils/utils'); var Filter = require('./filter'); var watches = require('./methods/watches'); var AllSolidityEvents = function (requestManager, json, address) { this._requestManager = requestManager; this._json = json; this._address = address; }; AllSolidityEvents.prototype.encode = function (options) { options = options || {}; var result = {}; ['fromBlock', 'toBlock'].filter(function (f) { return options[f] !== undefined; }).forEach(function (f) { result[f] = formatters.inputBlockNumberFormatter(options[f]); }); result.address = this._address; return result; }; AllSolidityEvents.prototype.decode = function (data) { data.data = data.data || ''; data.topics = data.topics || []; var eventTopic = data.topics[0].slice(2); var match = this._json.filter(function (j) { return eventTopic === sha3(utils.transformToFullName(j)); })[0]; if (!match) { // cannot find matching event? console.warn('cannot find event for log'); return data; } var event = new SolidityEvent(this._requestManager, match, this._address); return event.decode(data); }; AllSolidityEvents.prototype.execute = function (options, callback) { if (utils.isFunction(arguments[arguments.length - 1])) { callback = arguments[arguments.length - 1]; if(arguments.length === 1) options = null; } var o = this.encode(options); var formatter = this.decode.bind(this); return new Filter(o, 'eth', this._requestManager, watches.eth(), formatter, callback); }; AllSolidityEvents.prototype.attachToContract = function (contract) { var execute = this.execute.bind(this); contract.allEvents = execute; }; module.exports = AllSolidityEvents; },{"../utils/sha3":19,"../utils/utils":20,"./event":27,"./filter":29,"./formatters":30,"./methods/watches":43}],24:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file batch.js * @author Marek Kotewicz <[email protected]> * @date 2015 */ var Jsonrpc = require('./jsonrpc'); var errors = require('./errors'); var Batch = function (web3) { this.requestManager = web3._requestManager; this.requests = []; }; /** * Should be called to add create new request to batch request * * @method add * @param {Object} jsonrpc requet object */ Batch.prototype.add = function (request) { this.requests.push(request); }; /** * Should be called to execute batch request * * @method execute */ Batch.prototype.execute = function () { var requests = this.requests; this.requestManager.sendBatch(requests, function (err, results) { results = results || []; requests.map(function (request, index) { return results[index] || {}; }).forEach(function (result, index) { if (requests[index].callback) { if (!Jsonrpc.isValidResponse(result)) { return requests[index].callback(errors.InvalidResponse(result)); } requests[index].callback(null, (requests[index].format ? requests[index].format(result.result) : result.result)); } }); }); }; module.exports = Batch; },{"./errors":26,"./jsonrpc":35}],25:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file contract.js * @author Marek Kotewicz <[email protected]> * @date 2014 */ var utils = require('../utils/utils'); var coder = require('../solidity/coder'); var SolidityEvent = require('./event'); var SolidityFunction = require('./function'); var AllEvents = require('./allevents'); /** * Should be called to encode constructor params * * @method encodeConstructorParams * @param {Array} abi * @param {Array} constructor params */ var encodeConstructorParams = function (abi, params) { return abi.filter(function (json) { return json.type === 'constructor' && json.inputs.length === params.length; }).map(function (json) { return json.inputs.map(function (input) { return input.type; }); }).map(function (types) { return coder.encodeParams(types, params); })[0] || ''; }; /** * Should be called to add functions to contract object * * @method addFunctionsToContract * @param {Contract} contract * @param {Array} abi */ var addFunctionsToContract = function (contract) { contract.abi.filter(function (json) { return json.type === 'function'; }).map(function (json) { return new SolidityFunction(contract._eth, json, contract.address); }).forEach(function (f) { f.attachToContract(contract); }); }; /** * Should be called to add events to contract object * * @method addEventsToContract * @param {Contract} contract * @param {Array} abi */ var addEventsToContract = function (contract) { var events = contract.abi.filter(function (json) { return json.type === 'event'; }); var All = new AllEvents(contract._eth._requestManager, events, contract.address); All.attachToContract(contract); events.map(function (json) { return new SolidityEvent(contract._eth._requestManager, json, contract.address); }).forEach(function (e) { e.attachToContract(contract); }); }; /** * Should be called to check if the contract gets properly deployed on the blockchain. * * @method checkForContractAddress * @param {Object} contract * @param {Function} callback * @returns {Undefined} */ var checkForContractAddress = function(contract, callback){ var count = 0, callbackFired = false; // wait for receipt var filter = contract._eth.filter('latest', function(e){ if (!e && !callbackFired) { count++; // stop watching after 50 blocks (timeout) if (count > 50) { filter.stopWatching(function() {}); callbackFired = true; if (callback) callback(new Error('Contract transaction couldn\'t be found after 50 blocks')); else throw new Error('Contract transaction couldn\'t be found after 50 blocks'); } else { contract._eth.getTransactionReceipt(contract.transactionHash, function(e, receipt){ if(receipt && !callbackFired) { contract._eth.getCode(receipt.contractAddress, function(e, code){ /*jshint maxcomplexity: 6 */ if(callbackFired || !code) return; filter.stopWatching(function() {}); callbackFired = true; if(code.length > 3) { // console.log('Contract code deployed!'); contract.address = receipt.contractAddress; // attach events and methods again after we have addFunctionsToContract(contract); addEventsToContract(contract); // call callback for the second time if(callback) callback(null, contract); } else { if(callback) callback(new Error('The contract code couldn\'t be stored, please check your gas amount.')); else throw new Error('The contract code couldn\'t be stored, please check your gas amount.'); } }); } }); } } }); }; /** * Should be called to create new ContractFactory instance * * @method ContractFactory * @param {Array} abi */ var ContractFactory = function (eth, abi) { this.eth = eth; this.abi = abi; /** * Should be called to create new contract on a blockchain * * @method new * @param {Any} contract constructor param1 (optional) * @param {Any} contract constructor param2 (optional) * @param {Object} contract transaction object (required) * @param {Function} callback * @returns {Contract} returns contract instance */ this.new = function () { /*jshint maxcomplexity: 7 */ var contract = new Contract(this.eth, this.abi); // parse arguments var options = {}; // required! var callback; var args = Array.prototype.slice.call(arguments); if (utils.isFunction(args[args.length - 1])) { callback = args.pop(); } var last = args[args.length - 1]; if (utils.isObject(last) && !utils.isArray(last)) { options = args.pop(); } if (options.value > 0) { var constructorAbi = abi.filter(function (json) { return json.type === 'constructor' && json.inputs.length === args.length; })[0] || {}; if (!constructorAbi.payable) { throw new Error('Cannot send value to non-payable constructor'); } } var bytes = encodeConstructorParams(this.abi, args); options.data += bytes; if (callback) { // wait for the contract address adn check if the code was deployed this.eth.sendTransaction(options, function (err, hash) { if (err) { callback(err); } else { // add the transaction hash contract.transactionHash = hash; // call callback for the first time callback(null, contract); checkForContractAddress(contract, callback); } }); } else { var hash = this.eth.sendTransaction(options); // add the transaction hash contract.transactionHash = hash; checkForContractAddress(contract); } return contract; }; this.new.getData = this.getData.bind(this); }; /** * Should be called to create new ContractFactory * * @method contract * @param {Array} abi * @returns {ContractFactory} new contract factory */ //var contract = function (abi) { //return new ContractFactory(abi); //}; /** * Should be called to get access to existing contract on a blockchain * * @method at * @param {Address} contract address (required) * @param {Function} callback {optional) * @returns {Contract} returns contract if no callback was passed, * otherwise calls callback function (err, contract) */ ContractFactory.prototype.at = function (address, callback) { var contract = new Contract(this.eth, this.abi, address); // this functions are not part of prototype, // because we dont want to spoil the interface addFunctionsToContract(contract); addEventsToContract(contract); if (callback) { callback(null, contract); } return contract; }; /** * Gets the data, which is data to deploy plus constructor params * * @method getData */ ContractFactory.prototype.getData = function () { var options = {}; // required! var args = Array.prototype.slice.call(arguments); var last = args[args.length - 1]; if (utils.isObject(last) && !utils.isArray(last)) { options = args.pop(); } var bytes = encodeConstructorParams(this.abi, args); options.data += bytes; return options.data; }; /** * Should be called to create new contract instance * * @method Contract * @param {Array} abi * @param {Address} contract address */ var Contract = function (eth, abi, address) { this._eth = eth; this.transactionHash = null; this.address = address; this.abi = abi; }; module.exports = ContractFactory; },{"../solidity/coder":7,"../utils/utils":20,"./allevents":23,"./event":27,"./function":31}],26:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file errors.js * @author Marek Kotewicz <[email protected]> * @date 2015 */ module.exports = { InvalidNumberOfSolidityArgs: function () { return new Error('Invalid number of arguments to Solidity function'); }, InvalidNumberOfRPCParams: function () { return new Error('Invalid number of input parameters to RPC method'); }, InvalidConnection: function (host){ return new Error('CONNECTION ERROR: Couldn\'t connect to node '+ host +'.'); }, InvalidProvider: function () { return new Error('Provider not set or invalid'); }, InvalidResponse: function (result){ var message = !!result && !!result.error && !!result.error.message ? result.error.message : 'Invalid JSON RPC response: ' + JSON.stringify(result); return new Error(message); }, ConnectionTimeout: function (ms){ return new Error('CONNECTION TIMEOUT: timeout of ' + ms + ' ms achived'); } }; },{}],27:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file event.js * @author Marek Kotewicz <[email protected]> * @date 2014 */ var utils = require('../utils/utils'); var coder = require('../solidity/coder'); var formatters = require('./formatters'); var sha3 = require('../utils/sha3'); var Filter = require('./filter'); var watches = require('./methods/watches'); /** * This prototype should be used to create event filters */ var SolidityEvent = function (requestManager, json, address) { this._requestManager = requestManager; this._params = json.inputs; this._name = utils.transformToFullName(json); this._address = address; this._anonymous = json.anonymous; }; /** * Should be used to get filtered param types * * @method types * @param {Bool} decide if returned typed should be indexed * @return {Array} array of types */ SolidityEvent.prototype.types = function (indexed) { return this._params.filter(function (i) { return i.indexed === indexed; }).map(function (i) { return i.type; }); }; /** * Should be used to get event display name * * @method displayName * @return {String} event display name */ SolidityEvent.prototype.displayName = function () { return utils.extractDisplayName(this._name); }; /** * Should be used to get event type name * * @method typeName * @return {String} event type name */ SolidityEvent.prototype.typeName = function () { return utils.extractTypeName(this._name); }; /** * Should be used to get event signature * * @method signature * @return {String} event signature */ SolidityEvent.prototype.signature = function () { return sha3(this._name); }; /** * Should be used to encode indexed params and options to one final object * * @method encode * @param {Object} indexed * @param {Object} options * @return {Object} everything combined together and encoded */ SolidityEvent.prototype.encode = function (indexed, options) { indexed = indexed || {}; options = options || {}; var result = {}; ['fromBlock', 'toBlock'].filter(function (f) { return options[f] !== undefined; }).forEach(function (f) { result[f] = formatters.inputBlockNumberFormatter(options[f]); }); result.topics = []; result.address = this._address; if (!this._anonymous) { result.topics.push('0x' + this.signature()); } var indexedTopics = this._params.filter(function (i) { return i.indexed === true; }).map(function (i) { var value = indexed[i.name]; if (value === undefined || value === null) { return null; } if (utils.isArray(value)) { return value.map(function (v) { return '0x' + coder.encodeParam(i.type, v); }); } return '0x' + coder.encodeParam(i.type, value); }); result.topics = result.topics.concat(indexedTopics); return result; }; /** * Should be used to decode indexed params and options * * @method decode * @param {Object} data * @return {Object} result object with decoded indexed && not indexed params */ SolidityEvent.prototype.decode = function (data) { data.data = data.data || ''; data.topics = data.topics || []; var argTopics = this._anonymous ? data.topics : data.topics.slice(1); var indexedData = argTopics.map(function (topics) { return topics.slice(2); }).join(""); var indexedParams = coder.decodeParams(this.types(true), indexedData); var notIndexedData = data.data.slice(2); var notIndexedParams = coder.decodeParams(this.types(false), notIndexedData); var result = formatters.outputLogFormatter(data); result.event = this.displayName(); result.address = data.address; result.args = this._params.reduce(function (acc, current) { acc[current.name] = current.indexed ? indexedParams.shift() : notIndexedParams.shift(); return acc; }, {}); delete result.data; delete result.topics; return result; }; /** * Should be used to create new filter object from event * * @method execute * @param {Object} indexed * @param {Object} options * @return {Object} filter object */ SolidityEvent.prototype.execute = function (indexed, options, callback) { if (utils.isFunction(arguments[arguments.length - 1])) { callback = arguments[arguments.length - 1]; if(arguments.length === 2) options = null; if(arguments.length === 1) { options = null; indexed = {}; } } var o = this.encode(indexed, options); var formatter = this.decode.bind(this); return new Filter(o, 'eth', this._requestManager, watches.eth(), formatter, callback); }; /** * Should be used to attach event to contract object * * @method attachToContract * @param {Contract} */ SolidityEvent.prototype.attachToContract = function (contract) { var execute = this.execute.bind(this); var displayName = this.displayName(); if (!contract[displayName]) { contract[displayName] = execute; } contract[displayName][this.typeName()] = this.execute.bind(this, contract); }; module.exports = SolidityEvent; },{"../solidity/coder":7,"../utils/sha3":19,"../utils/utils":20,"./filter":29,"./formatters":30,"./methods/watches":43}],28:[function(require,module,exports){ var formatters = require('./formatters'); var utils = require('./../utils/utils'); var Method = require('./method'); var Property = require('./property'); // TODO: refactor, so the input params are not altered. // it's necessary to make same 'extension' work with multiple providers var extend = function (web3) { /* jshint maxcomplexity:5 */ var ex = function (extension) { var extendedObject; if (extension.property) { if (!web3[extension.property]) { web3[extension.property] = {}; } extendedObject = web3[extension.property]; } else { extendedObject = web3; } if (extension.methods) { extension.methods.forEach(function (method) { method.attachToObject(extendedObject); method.setRequestManager(web3._requestManager); }); } if (extension.properties) { extension.properties.forEach(function (property) { property.attachToObject(extendedObject); property.setRequestManager(web3._requestManager); }); } }; ex.formatters = formatters; ex.utils = utils; ex.Method = Method; ex.Property = Property; return ex; }; module.exports = extend; },{"./../utils/utils":20,"./formatters":30,"./method":36,"./property":45}],29:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** @file filter.js * @authors: * Jeffrey Wilcke <[email protected]> * Marek Kotewicz <[email protected]> * Marian Oancea <[email protected]> * Fabian Vogelsteller <[email protected]> * Gav Wood <[email protected]> * @date 2014 */ var formatters = require('./formatters'); var utils = require('../utils/utils'); /** * Converts a given topic to a hex string, but also allows null values. * * @param {Mixed} value * @return {String} */ var toTopic = function(value){ if(value === null || typeof value === 'undefined') return null; value = String(value); if(value.indexOf('0x') === 0) return value; else return utils.fromUtf8(value); }; /// This method should be called on options object, to verify deprecated properties && lazy load dynamic ones /// @param should be string or object /// @returns options string or object var getOptions = function (options, type) { /*jshint maxcomplexity: 6 */ if (utils.isString(options)) { return options; } options = options || {}; switch(type) { case 'eth': // make sure topics, get converted to hex options.topics = options.topics || []; options.topics = options.topics.map(function(topic){ return (utils.isArray(topic)) ? topic.map(toTopic) : toTopic(topic); }); return { topics: options.topics, from: options.from, to: options.to, address: options.address, fromBlock: formatters.inputBlockNumberFormatter(options.fromBlock), toBlock: formatters.inputBlockNumberFormatter(options.toBlock) }; case 'shh': return options; } }; /** Adds the callback and sets up the methods, to iterate over the results. @method getLogsAtStart @param {Object} self @param {function} callback */ var getLogsAtStart = function(self, callback){ // call getFilterLogs for the first watch callback start if (!utils.isString(self.options)) { self.get(function (err, messages) { // don't send all the responses to all the watches again... just to self one if (err) { callback(err); } if(utils.isArray(messages)) { messages.forEach(function (message) { callback(null, message); }); } }); } }; /** Adds the callback and sets up the methods, to iterate over the results. @method pollFilter @param {Object} self */ var pollFilter = function(self) { var onMessage = function (error, messages) { if (error) { return self.callbacks.forEach(function (callback) { callback(error); }); } if(utils.isArray(messages)) { messages.forEach(function (message) { message = self.formatter ? self.formatter(message) : message; self.callbacks.forEach(function (callback) { callback(null, message); }); }); } }; self.requestManager.startPolling({ method: self.implementation.poll.call, params: [self.filterId], }, self.filterId, onMessage, self.stopWatching.bind(self)); }; var Filter = function (options, type, requestManager, methods, formatter, callback, filterCreationErrorCallback) { var self = this; var implementation = {}; methods.forEach(function (method) { method.setRequestManager(requestManager); method.attachToObject(implementation); }); this.requestManager = requestManager; this.options = getOptions(options, type); this.implementation = implementation; this.filterId = null; this.callbacks = []; this.getLogsCallbacks = []; this.pollFilters = []; this.formatter = formatter; this.implementation.newFilter(this.options, function(error, id){ if(error) { self.callbacks.forEach(function(cb){ cb(error); }); if (typeof filterCreationErrorCallback === 'function') { filterCreationErrorCallback(error); } } else { self.filterId = id; // check if there are get pending callbacks as a consequence // of calling get() with filterId unassigned. self.getLogsCallbacks.forEach(function (cb){ self.get(cb); }); self.getLogsCallbacks = []; // get filter logs for the already existing watch calls self.callbacks.forEach(function(cb){ getLogsAtStart(self, cb); }); if(self.callbacks.length > 0) pollFilter(self); // start to watch immediately if(typeof callback === 'function') { return self.watch(callback); } } }); return this; }; Filter.prototype.watch = function (callback) { this.callbacks.push(callback); if(this.filterId) { getLogsAtStart(this, callback); pollFilter(this); } return this; }; Filter.prototype.stopWatching = function (callback) { this.requestManager.stopPolling(this.filterId); this.callbacks = []; // remove filter async if (callback) { this.implementation.uninstallFilter(this.filterId, callback); } else { return this.implementation.uninstallFilter(this.filterId); } }; Filter.prototype.get = function (callback) { var self = this; if (utils.isFunction(callback)) { if (this.filterId === null) { // If filterId is not set yet, call it back // when newFilter() assigns it. this.getLogsCallbacks.push(callback); } else { this.implementation.getLogs(this.filterId, function(err, res){ if (err) { callback(err); } else { callback(null, res.map(function (log) { return self.formatter ? self.formatter(log) : log; })); } }); } } else { if (this.filterId === null) { throw new Error('Filter ID Error: filter().get() can\'t be chained synchronous, please provide a callback for the get() method.'); } var logs = this.implementation.getLogs(this.filterId); return logs.map(function (log) { return self.formatter ? self.formatter(log) : log; }); } return this; }; module.exports = Filter; },{"../utils/utils":20,"./formatters":30}],30:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file formatters.js * @author Marek Kotewicz <[email protected]> * @author Fabian Vogelsteller <[email protected]> * @date 2015 */ 'use strict'; var utils = require('../utils/utils'); var config = require('../utils/config'); var Iban = require('./iban'); /** * Should the format output to a big number * * @method outputBigNumberFormatter * @param {String|Number|BigNumber} * @returns {BigNumber} object */ var outputBigNumberFormatter = function (number) { return utils.toBigNumber(number); }; var isPredefinedBlockNumber = function (blockNumber) { return blockNumber === 'latest' || blockNumber === 'pending' || blockNumber === 'earliest'; }; var inputDefaultBlockNumberFormatter = function (blockNumber) { if (blockNumber === undefined) { return config.defaultBlock; } return inputBlockNumberFormatter(blockNumber); }; var inputBlockNumberFormatter = function (blockNumber) { if (blockNumber === undefined) { return undefined; } else if (isPredefinedBlockNumber(blockNumber)) { return blockNumber; } return utils.toHex(blockNumber); }; /** * Formats the input of a transaction and converts all values to HEX * * @method inputCallFormatter * @param {Object} transaction options * @returns object */ var inputCallFormatter = function (options){ options.from = options.from || config.defaultAccount; if (options.from) { options.from = inputAddressFormatter(options.from); } if (options.to) { // it might be contract creation options.to = inputAddressFormatter(options.to); } ['gasPrice', 'gas', 'value', 'nonce'].filter(function (key) { return options[key] !== undefined; }).forEach(function(key){ options[key] = utils.fromDecimal(options[key]); }); return options; }; /** * Formats the input of a transaction and converts all values to HEX * * @method inputTransactionFormatter * @param {Object} transaction options * @returns object */ var inputTransactionFormatter = function (options){ options.from = options.from || config.defaultAccount; options.from = inputAddressFormatter(options.from); if (options.to) { // it might be contract creation options.to = inputAddressFormatter(options.to); } ['gasPrice', 'gas', 'value', 'nonce'].filter(function (key) { return options[key] !== undefined; }).forEach(function(key){ options[key] = utils.fromDecimal(options[key]); }); return options; }; /** * Formats the output of a transaction to its proper values * * @method outputTransactionFormatter * @param {Object} tx * @returns {Object} */ var outputTransactionFormatter = function (tx){ if(tx.blockNumber !== null) tx.blockNumber = utils.toDecimal(tx.blockNumber); if(tx.transactionIndex !== null) tx.transactionIndex = utils.toDecimal(tx.transactionIndex); tx.nonce = utils.toDecimal(tx.nonce); tx.gas = utils.toDecimal(tx.gas); tx.gasPrice = utils.toBigNumber(tx.gasPrice); tx.value = utils.toBigNumber(tx.value); return tx; }; /** * Formats the output of a transaction receipt to its proper values * * @method outputTransactionReceiptFormatter * @param {Object} receipt * @returns {Object} */ var outputTransactionReceiptFormatter = function (receipt){ if(receipt.blockNumber !== null) receipt.blockNumber = utils.toDecimal(receipt.blockNumber); if(receipt.transactionIndex !== null) receipt.transactionIndex = utils.toDecimal(receipt.transactionIndex); receipt.cumulativeGasUsed = utils.toDecimal(receipt.cumulativeGasUsed); receipt.gasUsed = utils.toDecimal(receipt.gasUsed); if(utils.isArray(receipt.logs)) { receipt.logs = receipt.logs.map(function(log){ return outputLogFormatter(log); }); } return receipt; }; /** * Formats the output of a block to its proper values * * @method outputBlockFormatter * @param {Object} block * @returns {Object} */ var outputBlockFormatter = function(block) { // transform to number block.gasLimit = utils.toDecimal(block.gasLimit); block.gasUsed = utils.toDecimal(block.gasUsed); block.size = utils.toDecimal(block.size); block.timestamp = utils.toDecimal(block.timestamp); if(block.number !== null) block.number = utils.toDecimal(block.number); block.difficulty = utils.toBigNumber(block.difficulty); block.totalDifficulty = utils.toBigNumber(block.totalDifficulty); if (utils.isArray(block.transactions)) { block.transactions.forEach(function(item){ if(!utils.isString(item)) return outputTransactionFormatter(item); }); } return block; }; /** * Formats the output of a log * * @method outputLogFormatter * @param {Object} log object * @returns {Object} log */ var outputLogFormatter = function(log) { if(log.blockNumber) log.blockNumber = utils.toDecimal(log.blockNumber); if(log.transactionIndex) log.transactionIndex = utils.toDecimal(log.transactionIndex); if(log.logIndex) log.logIndex = utils.toDecimal(log.logIndex); return log; }; /** * Formats the input of a whisper post and converts all values to HEX * * @method inputPostFormatter * @param {Object} transaction object * @returns {Object} */ var inputPostFormatter = function(post) { // post.payload = utils.toHex(post.payload); post.ttl = utils.fromDecimal(post.ttl); post.workToProve = utils.fromDecimal(post.workToProve); post.priority = utils.fromDecimal(post.priority); // fallback if (!utils.isArray(post.topics)) { post.topics = post.topics ? [post.topics] : []; } // format the following options post.topics = post.topics.map(function(topic){ // convert only if not hex return (topic.indexOf('0x') === 0) ? topic : utils.fromUtf8(topic); }); return post; }; /** * Formats the output of a received post message * * @method outputPostFormatter * @param {Object} * @returns {Object} */ var outputPostFormatter = function(post){ post.expiry = utils.toDecimal(post.expiry); post.sent = utils.toDecimal(post.sent); post.ttl = utils.toDecimal(post.ttl); post.workProved = utils.toDecimal(post.workProved); // post.payloadRaw = post.payload; // post.payload = utils.toAscii(post.payload); // if (utils.isJson(post.payload)) { // post.payload = JSON.parse(post.payload); // } // format the following options if (!post.topics) { post.topics = []; } post.topics = post.topics.map(function(topic){ return utils.toAscii(topic); }); return post; }; var inputAddressFormatter = function (address) { var iban = new Iban(address); if (iban.isValid() && iban.isDirect()) { return '0x' + iban.address(); } else if (utils.isStrictAddress(address)) { return address; } else if (utils.isAddress(address)) { return '0x' + address; } throw new Error('invalid address'); }; var outputSyncingFormatter = function(result) { if (!result) { return result; } result.startingBlock = utils.toDecimal(result.startingBlock); result.currentBlock = utils.toDecimal(result.currentBlock); result.highestBlock = utils.toDecimal(result.highestBlock); if (result.knownStates) { result.knownStates = utils.toDecimal(result.knownStates); result.pulledStates = utils.toDecimal(result.pulledStates); } return result; }; module.exports = { inputDefaultBlockNumberFormatter: inputDefaultBlockNumberFormatter, inputBlockNumberFormatter: inputBlockNumberFormatter, inputCallFormatter: inputCallFormatter, inputTransactionFormatter: inputTransactionFormatter, inputAddressFormatter: inputAddressFormatter, inputPostFormatter: inputPostFormatter, outputBigNumberFormatter: outputBigNumberFormatter, outputTransactionFormatter: outputTransactionFormatter, outputTransactionReceiptFormatter: outputTransactionReceiptFormatter, outputBlockFormatter: outputBlockFormatter, outputLogFormatter: outputLogFormatter, outputPostFormatter: outputPostFormatter, outputSyncingFormatter: outputSyncingFormatter }; },{"../utils/config":18,"../utils/utils":20,"./iban":33}],31:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file function.js * @author Marek Kotewicz <[email protected]> * @date 2015 */ var coder = require('../solidity/coder'); var utils = require('../utils/utils'); var errors = require('./errors'); var formatters = require('./formatters'); var sha3 = require('../utils/sha3'); /** * This prototype should be used to call/sendTransaction to solidity functions */ var SolidityFunction = function (eth, json, address) { this._eth = eth; this._inputTypes = json.inputs.map(function (i) { return i.type; }); this._outputTypes = json.outputs.map(function (i) { return i.type; }); this._constant = json.constant; this._payable = json.payable; this._name = utils.transformToFullName(json); this._address = address; }; SolidityFunction.prototype.extractCallback = function (args) { if (utils.isFunction(args[args.length - 1])) { return args.pop(); // modify the args array! } }; SolidityFunction.prototype.extractDefaultBlock = function (args) { if (args.length > this._inputTypes.length && !utils.isObject(args[args.length -1])) { return formatters.inputDefaultBlockNumberFormatter(args.pop()); // modify the args array! } }; /** * Should be called to check if the number of arguments is correct * * @method validateArgs * @param {Array} arguments * @throws {Error} if it is not */ SolidityFunction.prototype.validateArgs = function (args) { var inputArgs = args.filter(function (a) { // filter the options object but not arguments that are arrays return !( (utils.isObject(a) === true) && (utils.isArray(a) === false) && (utils.isBigNumber(a) === false) ); }); if (inputArgs.length !== this._inputTypes.length) { throw errors.InvalidNumberOfSolidityArgs(); } }; /** * Should be used to create payload from arguments * * @method toPayload * @param {Array} solidity function params * @param {Object} optional payload options */ SolidityFunction.prototype.toPayload = function (args) { var options = {}; if (args.length > this._inputTypes.length && utils.isObject(args[args.length -1])) { options = args[args.length - 1]; } this.validateArgs(args); options.to = this._address; options.data = '0x' + this.signature() + coder.encodeParams(this._inputTypes, args); return options; }; /** * Should be used to get function signature * * @method signature * @return {String} function signature */ SolidityFunction.prototype.signature = function () { return sha3(this._name).slice(0, 8); }; SolidityFunction.prototype.unpackOutput = function (output) { if (!output) { return; } output = output.length >= 2 ? output.slice(2) : output; var result = coder.decodeParams(this._outputTypes, output); return result.length === 1 ? result[0] : result; }; /** * Calls a contract function. * * @method call * @param {...Object} Contract function arguments * @param {function} If the last argument is a function, the contract function * call will be asynchronous, and the callback will be passed the * error and result. * @return {String} output bytes */ SolidityFunction.prototype.call = function () { var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; }); var callback = this.extractCallback(args); var defaultBlock = this.extractDefaultBlock(args); var payload = this.toPayload(args); if (!callback) { var output = this._eth.call(payload, defaultBlock); return this.unpackOutput(output); } var self = this; this._eth.call(payload, defaultBlock, function (error, output) { if (error) return callback(error, null); var unpacked = null; try { unpacked = self.unpackOutput(output); } catch (e) { error = e; } callback(error, unpacked); }); }; /** * Should be used to sendTransaction to solidity function * * @method sendTransaction */ SolidityFunction.prototype.sendTransaction = function () { var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; }); var callback = this.extractCallback(args); var payload = this.toPayload(args); if (payload.value > 0 && !this._payable) { throw new Error('Cannot send value to non-payable function'); } if (!callback) { return this._eth.sendTransaction(payload); } this._eth.sendTransaction(payload, callback); }; /** * Should be used to estimateGas of solidity function * * @method estimateGas */ SolidityFunction.prototype.estimateGas = function () { var args = Array.prototype.slice.call(arguments); var callback = this.extractCallback(args); var payload = this.toPayload(args); if (!callback) { return this._eth.estimateGas(payload); } this._eth.estimateGas(payload, callback); }; /** * Return the encoded data of the call * * @method getData * @return {String} the encoded data */ SolidityFunction.prototype.getData = function () { var args = Array.prototype.slice.call(arguments); var payload = this.toPayload(args); return payload.data; }; /** * Should be used to get function display name * * @method displayName * @return {String} display name of the function */ SolidityFunction.prototype.displayName = function () { return utils.extractDisplayName(this._name); }; /** * Should be used to get function type name * * @method typeName * @return {String} type name of the function */ SolidityFunction.prototype.typeName = function () { return utils.extractTypeName(this._name); }; /** * Should be called to get rpc requests from solidity function * * @method request * @returns {Object} */ SolidityFunction.prototype.request = function () { var args = Array.prototype.slice.call(arguments); var callback = this.extractCallback(args); var payload = this.toPayload(args); var format = this.unpackOutput.bind(this); return { method: this._constant ? 'eth_call' : 'eth_sendTransaction', callback: callback, params: [payload], format: format }; }; /** * Should be called to execute function * * @method execute */ SolidityFunction.prototype.execute = function () { var transaction = !this._constant; // send transaction if (transaction) { return this.sendTransaction.apply(this, Array.prototype.slice.call(arguments)); } // call return this.call.apply(this, Array.prototype.slice.call(arguments)); }; /** * Should be called to attach function to contract * * @method attachToContract * @param {Contract} */ SolidityFunction.prototype.attachToContract = function (contract) { var execute = this.execute.bind(this); execute.request = this.request.bind(this); execute.call = this.call.bind(this); execute.sendTransaction = this.sendTransaction.bind(this); execute.estimateGas = this.estimateGas.bind(this); execute.getData = this.getData.bind(this); var displayName = this.displayName(); if (!contract[displayName]) { contract[displayName] = execute; } contract[displayName][this.typeName()] = execute; // circular!!!! }; module.exports = SolidityFunction; },{"../solidity/coder":7,"../utils/sha3":19,"../utils/utils":20,"./errors":26,"./formatters":30}],32:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** @file httpprovider.js * @authors: * Marek Kotewicz <[email protected]> * Marian Oancea <[email protected]> * Fabian Vogelsteller <[email protected]> * @date 2015 */ var errors = require('./errors'); // workaround to use httpprovider in different envs // browser if (typeof window !== 'undefined' && window.XMLHttpRequest) { XMLHttpRequest = window.XMLHttpRequest; // jshint ignore: line // node } else { XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // jshint ignore: line } var XHR2 = require('xhr2'); // jshint ignore: line /** * HttpProvider should be used to send rpc calls over http */ var HttpProvider = function (host, timeout, user, password) { this.host = host || 'http://localhost:8545'; this.timeout = timeout || 0; this.user = user; this.password = password; }; /** * Should be called to prepare new XMLHttpRequest * * @method prepareRequest * @param {Boolean} true if request should be async * @return {XMLHttpRequest} object */ HttpProvider.prototype.prepareRequest = function (async) { var request; if (async) { request = new XHR2(); request.timeout = this.timeout; } else { request = new XMLHttpRequest(); } request.open('POST', this.host, async); if (this.user && this.password) { var auth = 'Basic ' + new Buffer(this.user + ':' + this.password).toString('base64'); request.setRequestHeader('Authorization', auth); } request.setRequestHeader('Content-Type', 'application/json'); return request; }; /** * Should be called to make sync request * * @method send * @param {Object} payload * @return {Object} result */ HttpProvider.prototype.send = function (payload) { var request = this.prepareRequest(false); try { request.send(JSON.stringify(payload)); } catch (error) { throw errors.InvalidConnection(this.host); } var result = request.responseText; try { result = JSON.parse(result); } catch (e) { throw errors.InvalidResponse(request.responseText); } return result; }; /** * Should be used to make async request * * @method sendAsync * @param {Object} payload * @param {Function} callback triggered on end with (err, result) */ HttpProvider.prototype.sendAsync = function (payload, callback) { var request = this.prepareRequest(true); request.onreadystatechange = function () { if (request.readyState === 4 && request.timeout !== 1) { var result = request.responseText; var error = null; try { result = JSON.parse(result); } catch (e) { error = errors.InvalidResponse(request.responseText); } callback(error, result); } }; request.ontimeout = function () { callback(errors.ConnectionTimeout(this.timeout)); }; try { request.send(JSON.stringify(payload)); } catch (error) { callback(errors.InvalidConnection(this.host)); } }; /** * Synchronously tries to make Http request * * @method isConnected * @return {Boolean} returns true if request haven't failed. Otherwise false */ HttpProvider.prototype.isConnected = function () { try { this.send({ id: 9999999999, jsonrpc: '2.0', method: 'net_listening', params: [] }); return true; } catch (e) { return false; } }; module.exports = HttpProvider; },{"./errors":26,"xhr2":85,"xmlhttprequest":17}],33:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file iban.js * @author Marek Kotewicz <[email protected]> * @date 2015 */ var BigNumber = require('bignumber.js'); var padLeft = function (string, bytes) { var result = string; while (result.length < bytes * 2) { result = '0' + result; } return result; }; /** * Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to * numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616. * * @method iso13616Prepare * @param {String} iban the IBAN * @returns {String} the prepared IBAN */ var iso13616Prepare = function (iban) { var A = 'A'.charCodeAt(0); var Z = 'Z'.charCodeAt(0); iban = iban.toUpperCase(); iban = iban.substr(4) + iban.substr(0,4); return iban.split('').map(function(n){ var code = n.charCodeAt(0); if (code >= A && code <= Z){ // A = 10, B = 11, ... Z = 35 return code - A + 10; } else { return n; } }).join(''); }; /** * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. * * @method mod9710 * @param {String} iban * @returns {Number} */ var mod9710 = function (iban) { var remainder = iban, block; while (remainder.length > 2){ block = remainder.slice(0, 9); remainder = parseInt(block, 10) % 97 + remainder.slice(block.length); } return parseInt(remainder, 10) % 97; }; /** * This prototype should be used to create iban object from iban correct string * * @param {String} iban */ var Iban = function (iban) { this._iban = iban; }; /** * This method should be used to create iban object from ethereum address * * @method fromAddress * @param {String} address * @return {Iban} the IBAN object */ Iban.fromAddress = function (address) { var asBn = new BigNumber(address, 16); var base36 = asBn.toString(36); var padded = padLeft(base36, 15); return Iban.fromBban(padded.toUpperCase()); }; /** * Convert the passed BBAN to an IBAN for this country specification. * Please note that <i>"generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account"</i>. * This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits * * @method fromBban * @param {String} bban the BBAN to convert to IBAN * @returns {Iban} the IBAN object */ Iban.fromBban = function (bban) { var countryCode = 'XE'; var remainder = mod9710(iso13616Prepare(countryCode + '00' + bban)); var checkDigit = ('0' + (98 - remainder)).slice(-2); return new Iban(countryCode + checkDigit + bban); }; /** * Should be used to create IBAN object for given institution and identifier * * @method createIndirect * @param {Object} options, required options are "institution" and "identifier" * @return {Iban} the IBAN object */ Iban.createIndirect = function (options) { return Iban.fromBban('ETH' + options.institution + options.identifier); }; /** * Thos method should be used to check if given string is valid iban object * * @method isValid * @param {String} iban string * @return {Boolean} true if it is valid IBAN */ Iban.isValid = function (iban) { var i = new Iban(iban); return i.isValid(); }; /** * Should be called to check if iban is correct * * @method isValid * @returns {Boolean} true if it is, otherwise false */ Iban.prototype.isValid = function () { return /^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(this._iban) && mod9710(iso13616Prepare(this._iban)) === 1; }; /** * Should be called to check if iban number is direct * * @method isDirect * @returns {Boolean} true if it is, otherwise false */ Iban.prototype.isDirect = function () { return this._iban.length === 34 || this._iban.length === 35; }; /** * Should be called to check if iban number if indirect * * @method isIndirect * @returns {Boolean} true if it is, otherwise false */ Iban.prototype.isIndirect = function () { return this._iban.length === 20; }; /** * Should be called to get iban checksum * Uses the mod-97-10 checksumming protocol (ISO/IEC 7064:2003) * * @method checksum * @returns {String} checksum */ Iban.prototype.checksum = function () { return this._iban.substr(2, 2); }; /** * Should be called to get institution identifier * eg. XREG * * @method institution * @returns {String} institution identifier */ Iban.prototype.institution = function () { return this.isIndirect() ? this._iban.substr(7, 4) : ''; }; /** * Should be called to get client identifier within institution * eg. GAVOFYORK * * @method client * @returns {String} client identifier */ Iban.prototype.client = function () { return this.isIndirect() ? this._iban.substr(11) : ''; }; /** * Should be called to get client direct address * * @method address * @returns {String} client direct address */ Iban.prototype.address = function () { if (this.isDirect()) { var base36 = this._iban.substr(4); var asBn = new BigNumber(base36, 36); return padLeft(asBn.toString(16), 20); } return ''; }; Iban.prototype.toString = function () { return this._iban; }; module.exports = Iban; },{"bignumber.js":"bignumber.js"}],34:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** @file ipcprovider.js * @authors: * Fabian Vogelsteller <[email protected]> * @date 2015 */ "use strict"; var utils = require('../utils/utils'); var errors = require('./errors'); var IpcProvider = function (path, net) { var _this = this; this.responseCallbacks = {}; this.path = path; this.connection = net.connect({path: this.path}); this.connection.on('error', function(e){ console.error('IPC Connection Error', e); _this._timeout(); }); this.connection.on('end', function(){ _this._timeout(); }); // LISTEN FOR CONNECTION RESPONSES this.connection.on('data', function(data) { /*jshint maxcomplexity: 6 */ _this._parseResponse(data.toString()).forEach(function(result){ var id = null; // get the id which matches the returned id if(utils.isArray(result)) { result.forEach(function(load){ if(_this.responseCallbacks[load.id]) id = load.id; }); } else { id = result.id; } // fire the callback if(_this.responseCallbacks[id]) { _this.responseCallbacks[id](null, result); delete _this.responseCallbacks[id]; } }); }); }; /** Will parse the response and make an array out of it. @method _parseResponse @param {String} data */ IpcProvider.prototype._parseResponse = function(data) { var _this = this, returnValues = []; // DE-CHUNKER var dechunkedData = data .replace(/\}[\n\r]?\{/g,'}|--|{') // }{ .replace(/\}\][\n\r]?\[\{/g,'}]|--|[{') // }][{ .replace(/\}[\n\r]?\[\{/g,'}|--|[{') // }[{ .replace(/\}\][\n\r]?\{/g,'}]|--|{') // }]{ .split('|--|'); dechunkedData.forEach(function(data){ // prepend the last chunk if(_this.lastChunk) data = _this.lastChunk + data; var result = null; try { result = JSON.parse(data); } catch(e) { _this.lastChunk = data; // start timeout to cancel all requests clearTimeout(_this.lastChunkTimeout); _this.lastChunkTimeout = setTimeout(function(){ _this._timeout(); throw errors.InvalidResponse(data); }, 1000 * 15); return; } // cancel timeout and set chunk to null clearTimeout(_this.lastChunkTimeout); _this.lastChunk = null; if(result) returnValues.push(result); }); return returnValues; }; /** Get the adds a callback to the responseCallbacks object, which will be called if a response matching the response Id will arrive. @method _addResponseCallback */ IpcProvider.prototype._addResponseCallback = function(payload, callback) { var id = payload.id || payload[0].id; var method = payload.method || payload[0].method; this.responseCallbacks[id] = callback; this.responseCallbacks[id].method = method; }; /** Timeout all requests when the end/error event is fired @method _timeout */ IpcProvider.prototype._timeout = function() { for(var key in this.responseCallbacks) { if(this.responseCallbacks.hasOwnProperty(key)){ this.responseCallbacks[key](errors.InvalidConnection('on IPC')); delete this.responseCallbacks[key]; } } }; /** Check if the current connection is still valid. @method isConnected */ IpcProvider.prototype.isConnected = function() { var _this = this; // try reconnect, when connection is gone if(!_this.connection.writable) _this.connection.connect({path: _this.path}); return !!this.connection.writable; }; IpcProvider.prototype.send = function (payload) { if(this.connection.writeSync) { var result; // try reconnect, when connection is gone if(!this.connection.writable) this.connection.connect({path: this.path}); var data = this.connection.writeSync(JSON.stringify(payload)); try { result = JSON.parse(data); } catch(e) { throw errors.InvalidResponse(data); } return result; } else { throw new Error('You tried to send "'+ payload.method +'" synchronously. Synchronous requests are not supported by the IPC provider.'); } }; IpcProvider.prototype.sendAsync = function (payload, callback) { // try reconnect, when connection is gone if(!this.connection.writable) this.connection.connect({path: this.path}); this.connection.write(JSON.stringify(payload)); this._addResponseCallback(payload, callback); }; module.exports = IpcProvider; },{"../utils/utils":20,"./errors":26}],35:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** @file jsonrpc.js * @authors: * Marek Kotewicz <[email protected]> * Aaron Kumavis <[email protected]> * @date 2015 */ // Initialize Jsonrpc as a simple object with utility functions. var Jsonrpc = { messageId: 0 }; /** * Should be called to valid json create payload object * * @method toPayload * @param {Function} method of jsonrpc call, required * @param {Array} params, an array of method params, optional * @returns {Object} valid jsonrpc payload object */ Jsonrpc.toPayload = function (method, params) { if (!method) console.error('jsonrpc method should be specified!'); // advance message ID Jsonrpc.messageId++; return { jsonrpc: '2.0', id: Jsonrpc.messageId, method: method, params: params || [] }; }; /** * Should be called to check if jsonrpc response is valid * * @method isValidResponse * @param {Object} * @returns {Boolean} true if response is valid, otherwise false */ Jsonrpc.isValidResponse = function (response) { return Array.isArray(response) ? response.every(validateSingleMessage) : validateSingleMessage(response); function validateSingleMessage(message){ return !!message && !message.error && message.jsonrpc === '2.0' && typeof message.id === 'number' && message.result !== undefined; // only undefined is not valid json object } }; /** * Should be called to create batch payload object * * @method toBatchPayload * @param {Array} messages, an array of objects with method (required) and params (optional) fields * @returns {Array} batch payload */ Jsonrpc.toBatchPayload = function (messages) { return messages.map(function (message) { return Jsonrpc.toPayload(message.method, message.params); }); }; module.exports = Jsonrpc; },{}],36:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file method.js * @author Marek Kotewicz <[email protected]> * @date 2015 */ var utils = require('../utils/utils'); var errors = require('./errors'); var Method = function (options) { this.name = options.name; this.call = options.call; this.params = options.params || 0; this.inputFormatter = options.inputFormatter; this.outputFormatter = options.outputFormatter; this.requestManager = null; }; Method.prototype.setRequestManager = function (rm) { this.requestManager = rm; }; /** * Should be used to determine name of the jsonrpc method based on arguments * * @method getCall * @param {Array} arguments * @return {String} name of jsonrpc method */ Method.prototype.getCall = function (args) { return utils.isFunction(this.call) ? this.call(args) : this.call; }; /** * Should be used to extract callback from array of arguments. Modifies input param * * @method extractCallback * @param {Array} arguments * @return {Function|Null} callback, if exists */ Method.prototype.extractCallback = function (args) { if (utils.isFunction(args[args.length - 1])) { return args.pop(); // modify the args array! } }; /** * Should be called to check if the number of arguments is correct * * @method validateArgs * @param {Array} arguments * @throws {Error} if it is not */ Method.prototype.validateArgs = function (args) { if (args.length !== this.params) { throw errors.InvalidNumberOfRPCParams(); } }; /** * Should be called to format input args of method * * @method formatInput * @param {Array} * @return {Array} */ Method.prototype.formatInput = function (args) { if (!this.inputFormatter) { return args; } return this.inputFormatter.map(function (formatter, index) { return formatter ? formatter(args[index]) : args[index]; }); }; /** * Should be called to format output(result) of method * * @method formatOutput * @param {Object} * @return {Object} */ Method.prototype.formatOutput = function (result) { return this.outputFormatter && result ? this.outputFormatter(result) : result; }; /** * Should create payload from given input args * * @method toPayload * @param {Array} args * @return {Object} */ Method.prototype.toPayload = function (args) { var call = this.getCall(args); var callback = this.extractCallback(args); var params = this.formatInput(args); this.validateArgs(params); return { method: call, params: params, callback: callback }; }; Method.prototype.attachToObject = function (obj) { var func = this.buildCall(); func.call = this.call; // TODO!!! that's ugly. filter.js uses it var name = this.name.split('.'); if (name.length > 1) { obj[name[0]] = obj[name[0]] || {}; obj[name[0]][name[1]] = func; } else { obj[name[0]] = func; } }; Method.prototype.buildCall = function() { var method = this; var send = function () { var payload = method.toPayload(Array.prototype.slice.call(arguments)); if (payload.callback) { return method.requestManager.sendAsync(payload, function (err, result) { payload.callback(err, method.formatOutput(result)); }); } return method.formatOutput(method.requestManager.send(payload)); }; send.request = this.request.bind(this); return send; }; /** * Should be called to create pure JSONRPC request which can be used in batch request * * @method request * @param {...} params * @return {Object} jsonrpc request */ Method.prototype.request = function () { var payload = this.toPayload(Array.prototype.slice.call(arguments)); payload.format = this.formatOutput.bind(this); return payload; }; module.exports = Method; },{"../utils/utils":20,"./errors":26}],37:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** @file db.js * @authors: * Marek Kotewicz <[email protected]> * @date 2015 */ var Method = require('../method'); var DB = function (web3) { this._requestManager = web3._requestManager; var self = this; methods().forEach(function(method) { method.attachToObject(self); method.setRequestManager(web3._requestManager); }); }; var methods = function () { var putString = new Method({ name: 'putString', call: 'db_putString', params: 3 }); var getString = new Method({ name: 'getString', call: 'db_getString', params: 2 }); var putHex = new Method({ name: 'putHex', call: 'db_putHex', params: 3 }); var getHex = new Method({ name: 'getHex', call: 'db_getHex', params: 2 }); return [ putString, getString, putHex, getHex ]; }; module.exports = DB; },{"../method":36}],38:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file eth.js * @author Marek Kotewicz <[email protected]> * @author Fabian Vogelsteller <[email protected]> * @date 2015 */ "use strict"; var formatters = require('../formatters'); var utils = require('../../utils/utils'); var Method = require('../method'); var Property = require('../property'); var c = require('../../utils/config'); var Contract = require('../contract'); var watches = require('./watches'); var Filter = require('../filter'); var IsSyncing = require('../syncing'); var namereg = require('../namereg'); var Iban = require('../iban'); var transfer = require('../transfer'); var blockCall = function (args) { return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? "eth_getBlockByHash" : "eth_getBlockByNumber"; }; var transactionFromBlockCall = function (args) { return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getTransactionByBlockHashAndIndex' : 'eth_getTransactionByBlockNumberAndIndex'; }; var uncleCall = function (args) { return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleByBlockHashAndIndex' : 'eth_getUncleByBlockNumberAndIndex'; }; var getBlockTransactionCountCall = function (args) { return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getBlockTransactionCountByHash' : 'eth_getBlockTransactionCountByNumber'; }; var uncleCountCall = function (args) { return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleCountByBlockHash' : 'eth_getUncleCountByBlockNumber'; }; function Eth(web3) { this._requestManager = web3._requestManager; var self = this; methods().forEach(function(method) { method.attachToObject(self); method.setRequestManager(self._requestManager); }); properties().forEach(function(p) { p.attachToObject(self); p.setRequestManager(self._requestManager); }); this.iban = Iban; this.sendIBANTransaction = transfer.bind(null, this); } Object.defineProperty(Eth.prototype, 'defaultBlock', { get: function () { return c.defaultBlock; }, set: function (val) { c.defaultBlock = val; return val; } }); Object.defineProperty(Eth.prototype, 'defaultAccount', { get: function () { return c.defaultAccount; }, set: function (val) { c.defaultAccount = val; return val; } }); var methods = function () { var getBalance = new Method({ name: 'getBalance', call: 'eth_getBalance', params: 2, inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter], outputFormatter: formatters.outputBigNumberFormatter }); var getStorageAt = new Method({ name: 'getStorageAt', call: 'eth_getStorageAt', params: 3, inputFormatter: [null, utils.toHex, formatters.inputDefaultBlockNumberFormatter] }); var getCode = new Method({ name: 'getCode', call: 'eth_getCode', params: 2, inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter] }); var getBlock = new Method({ name: 'getBlock', call: blockCall, params: 2, inputFormatter: [formatters.inputBlockNumberFormatter, function (val) { return !!val; }], outputFormatter: formatters.outputBlockFormatter }); var getUncle = new Method({ name: 'getUncle', call: uncleCall, params: 2, inputFormatter: [formatters.inputBlockNumberFormatter, utils.toHex], outputFormatter: formatters.outputBlockFormatter, }); var getCompilers = new Method({ name: 'getCompilers', call: 'eth_getCompilers', params: 0 }); var getBlockTransactionCount = new Method({ name: 'getBlockTransactionCount', call: getBlockTransactionCountCall, params: 1, inputFormatter: [formatters.inputBlockNumberFormatter], outputFormatter: utils.toDecimal }); var getBlockUncleCount = new Method({ name: 'getBlockUncleCount', call: uncleCountCall, params: 1, inputFormatter: [formatters.inputBlockNumberFormatter], outputFormatter: utils.toDecimal }); var getTransaction = new Method({ name: 'getTransaction', call: 'eth_getTransactionByHash', params: 1, outputFormatter: formatters.outputTransactionFormatter }); var getTransactionFromBlock = new Method({ name: 'getTransactionFromBlock', call: transactionFromBlockCall, params: 2, inputFormatter: [formatters.inputBlockNumberFormatter, utils.toHex], outputFormatter: formatters.outputTransactionFormatter }); var getTransactionReceipt = new Method({ name: 'getTransactionReceipt', call: 'eth_getTransactionReceipt', params: 1, outputFormatter: formatters.outputTransactionReceiptFormatter }); var getTransactionCount = new Method({ name: 'getTransactionCount', call: 'eth_getTransactionCount', params: 2, inputFormatter: [null, formatters.inputDefaultBlockNumberFormatter], outputFormatter: utils.toDecimal }); var sendRawTransaction = new Method({ name: 'sendRawTransaction', call: 'eth_sendRawTransaction', params: 1, inputFormatter: [null] }); var sendTransaction = new Method({ name: 'sendTransaction', call: 'eth_sendTransaction', params: 1, inputFormatter: [formatters.inputTransactionFormatter] }); var signTransaction = new Method({ name: 'signTransaction', call: 'eth_signTransaction', params: 1, inputFormatter: [formatters.inputTransactionFormatter] }); var sign = new Method({ name: 'sign', call: 'eth_sign', params: 2, inputFormatter: [formatters.inputAddressFormatter, null] }); var call = new Method({ name: 'call', call: 'eth_call', params: 2, inputFormatter: [formatters.inputCallFormatter, formatters.inputDefaultBlockNumberFormatter] }); var estimateGas = new Method({ name: 'estimateGas', call: 'eth_estimateGas', params: 1, inputFormatter: [formatters.inputCallFormatter], outputFormatter: utils.toDecimal }); var compileSolidity = new Method({ name: 'compile.solidity', call: 'eth_compileSolidity', params: 1 }); var compileLLL = new Method({ name: 'compile.lll', call: 'eth_compileLLL', params: 1 }); var compileSerpent = new Method({ name: 'compile.serpent', call: 'eth_compileSerpent', params: 1 }); var submitWork = new Method({ name: 'submitWork', call: 'eth_submitWork', params: 3 }); var getWork = new Method({ name: 'getWork', call: 'eth_getWork', params: 0 }); return [ getBalance, getStorageAt, getCode, getBlock, getUncle, getCompilers, getBlockTransactionCount, getBlockUncleCount, getTransaction, getTransactionFromBlock, getTransactionReceipt, getTransactionCount, call, estimateGas, sendRawTransaction, signTransaction, sendTransaction, sign, compileSolidity, compileLLL, compileSerpent, submitWork, getWork ]; }; var properties = function () { return [ new Property({ name: 'coinbase', getter: 'eth_coinbase' }), new Property({ name: 'mining', getter: 'eth_mining' }), new Property({ name: 'hashrate', getter: 'eth_hashrate', outputFormatter: utils.toDecimal }), new Property({ name: 'syncing', getter: 'eth_syncing', outputFormatter: formatters.outputSyncingFormatter }), new Property({ name: 'gasPrice', getter: 'eth_gasPrice', outputFormatter: formatters.outputBigNumberFormatter }), new Property({ name: 'accounts', getter: 'eth_accounts' }), new Property({ name: 'blockNumber', getter: 'eth_blockNumber', outputFormatter: utils.toDecimal }), new Property({ name: 'protocolVersion', getter: 'eth_protocolVersion' }) ]; }; Eth.prototype.contract = function (abi) { var factory = new Contract(this, abi); return factory; }; Eth.prototype.filter = function (options, callback, filterCreationErrorCallback) { return new Filter(options, 'eth', this._requestManager, watches.eth(), formatters.outputLogFormatter, callback, filterCreationErrorCallback); }; Eth.prototype.namereg = function () { return this.contract(namereg.global.abi).at(namereg.global.address); }; Eth.prototype.icapNamereg = function () { return this.contract(namereg.icap.abi).at(namereg.icap.address); }; Eth.prototype.isSyncing = function (callback) { return new IsSyncing(this._requestManager, callback); }; module.exports = Eth; },{"../../utils/config":18,"../../utils/utils":20,"../contract":25,"../filter":29,"../formatters":30,"../iban":33,"../method":36,"../namereg":44,"../property":45,"../syncing":48,"../transfer":49,"./watches":43}],39:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** @file eth.js * @authors: * Marek Kotewicz <[email protected]> * @date 2015 */ var utils = require('../../utils/utils'); var Property = require('../property'); var Net = function (web3) { this._requestManager = web3._requestManager; var self = this; properties().forEach(function(p) { p.attachToObject(self); p.setRequestManager(web3._requestManager); }); }; /// @returns an array of objects describing web3.eth api properties var properties = function () { return [ new Property({ name: 'listening', getter: 'net_listening' }), new Property({ name: 'peerCount', getter: 'net_peerCount', outputFormatter: utils.toDecimal }) ]; }; module.exports = Net; },{"../../utils/utils":20,"../property":45}],40:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file eth.js * @author Marek Kotewicz <[email protected]> * @author Fabian Vogelsteller <[email protected]> * @date 2015 */ "use strict"; var Method = require('../method'); var Property = require('../property'); var formatters = require('../formatters'); function Personal(web3) { this._requestManager = web3._requestManager; var self = this; methods().forEach(function(method) { method.attachToObject(self); method.setRequestManager(self._requestManager); }); properties().forEach(function(p) { p.attachToObject(self); p.setRequestManager(self._requestManager); }); } var methods = function () { var newAccount = new Method({ name: 'newAccount', call: 'personal_newAccount', params: 1, inputFormatter: [null] }); var importRawKey = new Method({ name: 'importRawKey', call: 'personal_importRawKey', params: 2 }); var sign = new Method({ name: 'sign', call: 'personal_sign', params: 3, inputFormatter: [null, formatters.inputAddressFormatter, null] }); var ecRecover = new Method({ name: 'ecRecover', call: 'personal_ecRecover', params: 2 }); var unlockAccount = new Method({ name: 'unlockAccount', call: 'personal_unlockAccount', params: 3, inputFormatter: [formatters.inputAddressFormatter, null, null] }); var sendTransaction = new Method({ name: 'sendTransaction', call: 'personal_sendTransaction', params: 2, inputFormatter: [formatters.inputTransactionFormatter, null] }); var lockAccount = new Method({ name: 'lockAccount', call: 'personal_lockAccount', params: 1, inputFormatter: [formatters.inputAddressFormatter] }); return [ newAccount, importRawKey, unlockAccount, ecRecover, sign, sendTransaction, lockAccount ]; }; var properties = function () { return [ new Property({ name: 'listAccounts', getter: 'personal_listAccounts' }) ]; }; module.exports = Personal; },{"../formatters":30,"../method":36,"../property":45}],41:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** @file shh.js * @authors: * Fabian Vogelsteller <[email protected]> * Marek Kotewicz <[email protected]> * @date 2017 */ var Method = require('../method'); var Filter = require('../filter'); var watches = require('./watches'); var Shh = function (web3) { this._requestManager = web3._requestManager; var self = this; methods().forEach(function(method) { method.attachToObject(self); method.setRequestManager(self._requestManager); }); }; Shh.prototype.newMessageFilter = function (options, callback, filterCreationErrorCallback) { return new Filter(options, 'shh', this._requestManager, watches.shh(), null, callback, filterCreationErrorCallback); }; var methods = function () { return [ new Method({ name: 'version', call: 'shh_version', params: 0 }), new Method({ name: 'info', call: 'shh_info', params: 0 }), new Method({ name: 'setMaxMessageSize', call: 'shh_setMaxMessageSize', params: 1 }), new Method({ name: 'setMinPoW', call: 'shh_setMinPoW', params: 1 }), new Method({ name: 'markTrustedPeer', call: 'shh_markTrustedPeer', params: 1 }), new Method({ name: 'newKeyPair', call: 'shh_newKeyPair', params: 0 }), new Method({ name: 'addPrivateKey', call: 'shh_addPrivateKey', params: 1 }), new Method({ name: 'deleteKeyPair', call: 'shh_deleteKeyPair', params: 1 }), new Method({ name: 'hasKeyPair', call: 'shh_hasKeyPair', params: 1 }), new Method({ name: 'getPublicKey', call: 'shh_getPublicKey', params: 1 }), new Method({ name: 'getPrivateKey', call: 'shh_getPrivateKey', params: 1 }), new Method({ name: 'newSymKey', call: 'shh_newSymKey', params: 0 }), new Method({ name: 'addSymKey', call: 'shh_addSymKey', params: 1 }), new Method({ name: 'generateSymKeyFromPassword', call: 'shh_generateSymKeyFromPassword', params: 1 }), new Method({ name: 'hasSymKey', call: 'shh_hasSymKey', params: 1 }), new Method({ name: 'getSymKey', call: 'shh_getSymKey', params: 1 }), new Method({ name: 'deleteSymKey', call: 'shh_deleteSymKey', params: 1 }), // subscribe and unsubscribe missing new Method({ name: 'post', call: 'shh_post', params: 1, inputFormatter: [null] }) ]; }; module.exports = Shh; },{"../filter":29,"../method":36,"./watches":43}],42:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file bzz.js * @author Alex Beregszaszi <[email protected]> * @date 2016 * * Reference: https://github.com/ethereum/go-ethereum/blob/swarm/internal/web3ext/web3ext.go#L33 */ "use strict"; var Method = require('../method'); var Property = require('../property'); function Swarm(web3) { this._requestManager = web3._requestManager; var self = this; methods().forEach(function(method) { method.attachToObject(self); method.setRequestManager(self._requestManager); }); properties().forEach(function(p) { p.attachToObject(self); p.setRequestManager(self._requestManager); }); } var methods = function () { var blockNetworkRead = new Method({ name: 'blockNetworkRead', call: 'bzz_blockNetworkRead', params: 1, inputFormatter: [null] }); var syncEnabled = new Method({ name: 'syncEnabled', call: 'bzz_syncEnabled', params: 1, inputFormatter: [null] }); var swapEnabled = new Method({ name: 'swapEnabled', call: 'bzz_swapEnabled', params: 1, inputFormatter: [null] }); var download = new Method({ name: 'download', call: 'bzz_download', params: 2, inputFormatter: [null, null] }); var upload = new Method({ name: 'upload', call: 'bzz_upload', params: 2, inputFormatter: [null, null] }); var retrieve = new Method({ name: 'retrieve', call: 'bzz_retrieve', params: 1, inputFormatter: [null] }); var store = new Method({ name: 'store', call: 'bzz_store', params: 2, inputFormatter: [null, null] }); var get = new Method({ name: 'get', call: 'bzz_get', params: 1, inputFormatter: [null] }); var put = new Method({ name: 'put', call: 'bzz_put', params: 2, inputFormatter: [null, null] }); var modify = new Method({ name: 'modify', call: 'bzz_modify', params: 4, inputFormatter: [null, null, null, null] }); return [ blockNetworkRead, syncEnabled, swapEnabled, download, upload, retrieve, store, get, put, modify ]; }; var properties = function () { return [ new Property({ name: 'hive', getter: 'bzz_hive' }), new Property({ name: 'info', getter: 'bzz_info' }) ]; }; module.exports = Swarm; },{"../method":36,"../property":45}],43:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** @file watches.js * @authors: * Marek Kotewicz <[email protected]> * @date 2015 */ var Method = require('../method'); /// @returns an array of objects describing web3.eth.filter api methods var eth = function () { var newFilterCall = function (args) { var type = args[0]; switch(type) { case 'latest': args.shift(); this.params = 0; return 'eth_newBlockFilter'; case 'pending': args.shift(); this.params = 0; return 'eth_newPendingTransactionFilter'; default: return 'eth_newFilter'; } }; var newFilter = new Method({ name: 'newFilter', call: newFilterCall, params: 1 }); var uninstallFilter = new Method({ name: 'uninstallFilter', call: 'eth_uninstallFilter', params: 1 }); var getLogs = new Method({ name: 'getLogs', call: 'eth_getFilterLogs', params: 1 }); var poll = new Method({ name: 'poll', call: 'eth_getFilterChanges', params: 1 }); return [ newFilter, uninstallFilter, getLogs, poll ]; }; /// @returns an array of objects describing web3.shh.watch api methods var shh = function () { return [ new Method({ name: 'newFilter', call: 'shh_newMessageFilter', params: 1 }), new Method({ name: 'uninstallFilter', call: 'shh_deleteMessageFilter', params: 1 }), new Method({ name: 'getLogs', call: 'shh_getFilterMessages', params: 1 }), new Method({ name: 'poll', call: 'shh_getFilterMessages', params: 1 }) ]; }; module.exports = { eth: eth, shh: shh }; },{"../method":36}],44:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file namereg.js * @author Marek Kotewicz <[email protected]> * @date 2015 */ var globalRegistrarAbi = require('../contracts/GlobalRegistrar.json'); var icapRegistrarAbi= require('../contracts/ICAPRegistrar.json'); var globalNameregAddress = '0xc6d9d2cd449a754c494264e1809c50e34d64562b'; var icapNameregAddress = '0xa1a111bc074c9cfa781f0c38e63bd51c91b8af00'; module.exports = { global: { abi: globalRegistrarAbi, address: globalNameregAddress }, icap: { abi: icapRegistrarAbi, address: icapNameregAddress } }; },{"../contracts/GlobalRegistrar.json":1,"../contracts/ICAPRegistrar.json":2}],45:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file property.js * @author Fabian Vogelsteller <[email protected]> * @author Marek Kotewicz <[email protected]> * @date 2015 */ var utils = require('../utils/utils'); var Property = function (options) { this.name = options.name; this.getter = options.getter; this.setter = options.setter; this.outputFormatter = options.outputFormatter; this.inputFormatter = options.inputFormatter; this.requestManager = null; }; Property.prototype.setRequestManager = function (rm) { this.requestManager = rm; }; /** * Should be called to format input args of method * * @method formatInput * @param {Array} * @return {Array} */ Property.prototype.formatInput = function (arg) { return this.inputFormatter ? this.inputFormatter(arg) : arg; }; /** * Should be called to format output(result) of method * * @method formatOutput * @param {Object} * @return {Object} */ Property.prototype.formatOutput = function (result) { return this.outputFormatter && result !== null && result !== undefined ? this.outputFormatter(result) : result; }; /** * Should be used to extract callback from array of arguments. Modifies input param * * @method extractCallback * @param {Array} arguments * @return {Function|Null} callback, if exists */ Property.prototype.extractCallback = function (args) { if (utils.isFunction(args[args.length - 1])) { return args.pop(); // modify the args array! } }; /** * Should attach function to method * * @method attachToObject * @param {Object} * @param {Function} */ Property.prototype.attachToObject = function (obj) { var proto = { get: this.buildGet(), enumerable: true }; var names = this.name.split('.'); var name = names[0]; if (names.length > 1) { obj[names[0]] = obj[names[0]] || {}; obj = obj[names[0]]; name = names[1]; } Object.defineProperty(obj, name, proto); obj[asyncGetterName(name)] = this.buildAsyncGet(); }; var asyncGetterName = function (name) { return 'get' + name.charAt(0).toUpperCase() + name.slice(1); }; Property.prototype.buildGet = function () { var property = this; return function get() { return property.formatOutput(property.requestManager.send({ method: property.getter })); }; }; Property.prototype.buildAsyncGet = function () { var property = this; var get = function (callback) { property.requestManager.sendAsync({ method: property.getter }, function (err, result) { callback(err, property.formatOutput(result)); }); }; get.request = this.request.bind(this); return get; }; /** * Should be called to create pure JSONRPC request which can be used in batch request * * @method request * @param {...} params * @return {Object} jsonrpc request */ Property.prototype.request = function () { var payload = { method: this.getter, params: [], callback: this.extractCallback(Array.prototype.slice.call(arguments)) }; payload.format = this.formatOutput.bind(this); return payload; }; module.exports = Property; },{"../utils/utils":20}],46:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file requestmanager.js * @author Jeffrey Wilcke <[email protected]> * @author Marek Kotewicz <[email protected]> * @author Marian Oancea <[email protected]> * @author Fabian Vogelsteller <[email protected]> * @author Gav Wood <[email protected]> * @date 2014 */ var Jsonrpc = require('./jsonrpc'); var utils = require('../utils/utils'); var c = require('../utils/config'); var errors = require('./errors'); /** * It's responsible for passing messages to providers * It's also responsible for polling the ethereum node for incoming messages * Default poll timeout is 1 second * Singleton */ var RequestManager = function (provider) { this.provider = provider; this.polls = {}; this.timeout = null; }; /** * Should be used to synchronously send request * * @method send * @param {Object} data * @return {Object} */ RequestManager.prototype.send = function (data) { if (!this.provider) { console.error(errors.InvalidProvider()); return null; } var payload = Jsonrpc.toPayload(data.method, data.params); var result = this.provider.send(payload); if (!Jsonrpc.isValidResponse(result)) { throw errors.InvalidResponse(result); } return result.result; }; /** * Should be used to asynchronously send request * * @method sendAsync * @param {Object} data * @param {Function} callback */ RequestManager.prototype.sendAsync = function (data, callback) { if (!this.provider) { return callback(errors.InvalidProvider()); } var payload = Jsonrpc.toPayload(data.method, data.params); this.provider.sendAsync(payload, function (err, result) { if (err) { return callback(err); } if (!Jsonrpc.isValidResponse(result)) { return callback(errors.InvalidResponse(result)); } callback(null, result.result); }); }; /** * Should be called to asynchronously send batch request * * @method sendBatch * @param {Array} batch data * @param {Function} callback */ RequestManager.prototype.sendBatch = function (data, callback) { if (!this.provider) { return callback(errors.InvalidProvider()); } var payload = Jsonrpc.toBatchPayload(data); this.provider.sendAsync(payload, function (err, results) { if (err) { return callback(err); } if (!utils.isArray(results)) { return callback(errors.InvalidResponse(results)); } callback(err, results); }); }; /** * Should be used to set provider of request manager * * @method setProvider * @param {Object} */ RequestManager.prototype.setProvider = function (p) { this.provider = p; }; /** * Should be used to start polling * * @method startPolling * @param {Object} data * @param {Number} pollId * @param {Function} callback * @param {Function} uninstall * * @todo cleanup number of params */ RequestManager.prototype.startPolling = function (data, pollId, callback, uninstall) { this.polls[pollId] = {data: data, id: pollId, callback: callback, uninstall: uninstall}; // start polling if (!this.timeout) { this.poll(); } }; /** * Should be used to stop polling for filter with given id * * @method stopPolling * @param {Number} pollId */ RequestManager.prototype.stopPolling = function (pollId) { delete this.polls[pollId]; // stop polling if(Object.keys(this.polls).length === 0 && this.timeout) { clearTimeout(this.timeout); this.timeout = null; } }; /** * Should be called to reset the polling mechanism of the request manager * * @method reset */ RequestManager.prototype.reset = function (keepIsSyncing) { /*jshint maxcomplexity:5 */ for (var key in this.polls) { // remove all polls, except sync polls, // they need to be removed manually by calling syncing.stopWatching() if(!keepIsSyncing || key.indexOf('syncPoll_') === -1) { this.polls[key].uninstall(); delete this.polls[key]; } } // stop polling if(Object.keys(this.polls).length === 0 && this.timeout) { clearTimeout(this.timeout); this.timeout = null; } }; /** * Should be called to poll for changes on filter with given id * * @method poll */ RequestManager.prototype.poll = function () { /*jshint maxcomplexity: 6 */ this.timeout = setTimeout(this.poll.bind(this), c.ETH_POLLING_TIMEOUT); if (Object.keys(this.polls).length === 0) { return; } if (!this.provider) { console.error(errors.InvalidProvider()); return; } var pollsData = []; var pollsIds = []; for (var key in this.polls) { pollsData.push(this.polls[key].data); pollsIds.push(key); } if (pollsData.length === 0) { return; } var payload = Jsonrpc.toBatchPayload(pollsData); // map the request id to they poll id var pollsIdMap = {}; payload.forEach(function(load, index){ pollsIdMap[load.id] = pollsIds[index]; }); var self = this; this.provider.sendAsync(payload, function (error, results) { // TODO: console log? if (error) { return; } if (!utils.isArray(results)) { throw errors.InvalidResponse(results); } results.map(function (result) { var id = pollsIdMap[result.id]; // make sure the filter is still installed after arrival of the request if (self.polls[id]) { result.callback = self.polls[id].callback; return result; } else return false; }).filter(function (result) { return !!result; }).filter(function (result) { var valid = Jsonrpc.isValidResponse(result); if (!valid) { result.callback(errors.InvalidResponse(result)); } return valid; }).forEach(function (result) { result.callback(null, result.result); }); }); }; module.exports = RequestManager; },{"../utils/config":18,"../utils/utils":20,"./errors":26,"./jsonrpc":35}],47:[function(require,module,exports){ var Settings = function () { this.defaultBlock = 'latest'; this.defaultAccount = undefined; }; module.exports = Settings; },{}],48:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** @file syncing.js * @authors: * Fabian Vogelsteller <[email protected]> * @date 2015 */ var formatters = require('./formatters'); var utils = require('../utils/utils'); var count = 1; /** Adds the callback and sets up the methods, to iterate over the results. @method pollSyncing @param {Object} self */ var pollSyncing = function(self) { var onMessage = function (error, sync) { if (error) { return self.callbacks.forEach(function (callback) { callback(error); }); } if(utils.isObject(sync) && sync.startingBlock) sync = formatters.outputSyncingFormatter(sync); self.callbacks.forEach(function (callback) { if (self.lastSyncState !== sync) { // call the callback with true first so the app can stop anything, before receiving the sync data if(!self.lastSyncState && utils.isObject(sync)) callback(null, true); // call on the next CPU cycle, so the actions of the sync stop can be processes first setTimeout(function() { callback(null, sync); }, 0); self.lastSyncState = sync; } }); }; self.requestManager.startPolling({ method: 'eth_syncing', params: [], }, self.pollId, onMessage, self.stopWatching.bind(self)); }; var IsSyncing = function (requestManager, callback) { this.requestManager = requestManager; this.pollId = 'syncPoll_'+ count++; this.callbacks = []; this.addCallback(callback); this.lastSyncState = false; pollSyncing(this); return this; }; IsSyncing.prototype.addCallback = function (callback) { if(callback) this.callbacks.push(callback); return this; }; IsSyncing.prototype.stopWatching = function () { this.requestManager.stopPolling(this.pollId); this.callbacks = []; }; module.exports = IsSyncing; },{"../utils/utils":20,"./formatters":30}],49:[function(require,module,exports){ /* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file transfer.js * @author Marek Kotewicz <[email protected]> * @date 2015 */ var Iban = require('./iban'); var exchangeAbi = require('../contracts/SmartExchange.json'); /** * Should be used to make Iban transfer * * @method transfer * @param {String} from * @param {String} to iban * @param {Value} value to be tranfered * @param {Function} callback, callback */ var transfer = function (eth, from, to, value, callback) { var iban = new Iban(to); if (!iban.isValid()) { throw new Error('invalid iban address'); } if (iban.isDirect()) { return transferToAddress(eth, from, iban.address(), value, callback); } if (!callback) { var address = eth.icapNamereg().addr(iban.institution()); return deposit(eth, from, address, value, iban.client()); } eth.icapNamereg().addr(iban.institution(), function (err, address) { return deposit(eth, from, address, value, iban.client(), callback); }); }; /** * Should be used to transfer funds to certain address * * @method transferToAddress * @param {String} from * @param {String} to * @param {Value} value to be tranfered * @param {Function} callback, callback */ var transferToAddress = function (eth, from, to, value, callback) { return eth.sendTransaction({ address: to, from: from, value: value }, callback); }; /** * Should be used to deposit funds to generic Exchange contract (must implement deposit(bytes32) method!) * * @method deposit * @param {String} from * @param {String} to * @param {Value} value to be transfered * @param {String} client unique identifier * @param {Function} callback, callback */ var deposit = function (eth, from, to, value, client, callback) { var abi = exchangeAbi; return eth.contract(abi).at(to).deposit(client, { from: from, value: value }, callback); }; module.exports = transfer; },{"../contracts/SmartExchange.json":3,"./iban":33}],50:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Lookup tables var SBOX = []; var INV_SBOX = []; var SUB_MIX_0 = []; var SUB_MIX_1 = []; var SUB_MIX_2 = []; var SUB_MIX_3 = []; var INV_SUB_MIX_0 = []; var INV_SUB_MIX_1 = []; var INV_SUB_MIX_2 = []; var INV_SUB_MIX_3 = []; // Compute lookup tables (function () { // Compute double table var d = []; for (var i = 0; i < 256; i++) { if (i < 128) { d[i] = i << 1; } else { d[i] = (i << 1) ^ 0x11b; } } // Walk GF(2^8) var x = 0; var xi = 0; for (var i = 0; i < 256; i++) { // Compute sbox var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; SBOX[x] = sx; INV_SBOX[sx] = x; // Compute multiplication var x2 = d[x]; var x4 = d[x2]; var x8 = d[x4]; // Compute sub bytes, mix columns tables var t = (d[sx] * 0x101) ^ (sx * 0x1010100); SUB_MIX_0[x] = (t << 24) | (t >>> 8); SUB_MIX_1[x] = (t << 16) | (t >>> 16); SUB_MIX_2[x] = (t << 8) | (t >>> 24); SUB_MIX_3[x] = t; // Compute inv sub bytes, inv mix columns tables var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); INV_SUB_MIX_3[sx] = t; // Compute next counter if (!x) { x = xi = 1; } else { x = x2 ^ d[d[d[x8 ^ x2]]]; xi ^= d[d[xi]]; } } }()); // Precomputed Rcon lookup var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; /** * AES block cipher algorithm. */ var AES = C_algo.AES = BlockCipher.extend({ _doReset: function () { // Skip reset of nRounds has been set before and key did not change if (this._nRounds && this._keyPriorReset === this._key) { return; } // Shortcuts var key = this._keyPriorReset = this._key; var keyWords = key.words; var keySize = key.sigBytes / 4; // Compute number of rounds var nRounds = this._nRounds = keySize + 6; // Compute number of key schedule rows var ksRows = (nRounds + 1) * 4; // Compute key schedule var keySchedule = this._keySchedule = []; for (var ksRow = 0; ksRow < ksRows; ksRow++) { if (ksRow < keySize) { keySchedule[ksRow] = keyWords[ksRow]; } else { var t = keySchedule[ksRow - 1]; if (!(ksRow % keySize)) { // Rot word t = (t << 8) | (t >>> 24); // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; // Mix Rcon t ^= RCON[(ksRow / keySize) | 0] << 24; } else if (keySize > 6 && ksRow % keySize == 4) { // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; } keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; } } // Compute inv key schedule var invKeySchedule = this._invKeySchedule = []; for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { var ksRow = ksRows - invKsRow; if (invKsRow % 4) { var t = keySchedule[ksRow]; } else { var t = keySchedule[ksRow - 4]; } if (invKsRow < 4 || ksRow <= 4) { invKeySchedule[invKsRow] = t; } else { invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; } } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); }, decryptBlock: function (M, offset) { // Swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); // Inv swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; }, _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { // Shortcut var nRounds = this._nRounds; // Get input, add round key var s0 = M[offset] ^ keySchedule[0]; var s1 = M[offset + 1] ^ keySchedule[1]; var s2 = M[offset + 2] ^ keySchedule[2]; var s3 = M[offset + 3] ^ keySchedule[3]; // Key schedule row counter var ksRow = 4; // Rounds for (var round = 1; round < nRounds; round++) { // Shift rows, sub bytes, mix columns, add round key var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; // Update state s0 = t0; s1 = t1; s2 = t2; s3 = t3; } // Shift rows, sub bytes, add round key var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; // Set output M[offset] = t0; M[offset + 1] = t1; M[offset + 2] = t2; M[offset + 3] = t3; }, keySize: 256/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); */ C.AES = BlockCipher._createHelper(AES); }()); return CryptoJS.AES; })); },{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],51:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher core components. */ CryptoJS.lib.Cipher || (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var Base64 = C_enc.Base64; var C_algo = C.algo; var EvpKDF = C_algo.EvpKDF; /** * Abstract base cipher template. * * @property {number} keySize This cipher's key size. Default: 4 (128 bits) * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. */ var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ /** * Configuration options. * * @property {WordArray} iv The IV to use for this operation. */ cfg: Base.extend(), /** * Creates this cipher in encryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); */ createEncryptor: function (key, cfg) { return this.create(this._ENC_XFORM_MODE, key, cfg); }, /** * Creates this cipher in decryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); */ createDecryptor: function (key, cfg) { return this.create(this._DEC_XFORM_MODE, key, cfg); }, /** * Initializes a newly created cipher. * * @param {number} xformMode Either the encryption or decryption transormation mode constant. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @example * * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); */ init: function (xformMode, key, cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Store transform mode and key this._xformMode = xformMode; this._key = key; // Set initial values this.reset(); }, /** * Resets this cipher to its initial state. * * @example * * cipher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-cipher logic this._doReset(); }, /** * Adds data to be encrypted or decrypted. * * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. * * @return {WordArray} The data after processing. * * @example * * var encrypted = cipher.process('data'); * var encrypted = cipher.process(wordArray); */ process: function (dataUpdate) { // Append this._append(dataUpdate); // Process available blocks return this._process(); }, /** * Finalizes the encryption or decryption process. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. * * @return {WordArray} The data after final processing. * * @example * * var encrypted = cipher.finalize(); * var encrypted = cipher.finalize('data'); * var encrypted = cipher.finalize(wordArray); */ finalize: function (dataUpdate) { // Final data update if (dataUpdate) { this._append(dataUpdate); } // Perform concrete-cipher logic var finalProcessedData = this._doFinalize(); return finalProcessedData; }, keySize: 128/32, ivSize: 128/32, _ENC_XFORM_MODE: 1, _DEC_XFORM_MODE: 2, /** * Creates shortcut functions to a cipher's object interface. * * @param {Cipher} cipher The cipher to create a helper for. * * @return {Object} An object with encrypt and decrypt shortcut functions. * * @static * * @example * * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); */ _createHelper: (function () { function selectCipherStrategy(key) { if (typeof key == 'string') { return PasswordBasedCipher; } else { return SerializableCipher; } } return function (cipher) { return { encrypt: function (message, key, cfg) { return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); }, decrypt: function (ciphertext, key, cfg) { return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); } }; }; }()) }); /** * Abstract base stream cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) */ var StreamCipher = C_lib.StreamCipher = Cipher.extend({ _doFinalize: function () { // Process partial blocks var finalProcessedBlocks = this._process(!!'flush'); return finalProcessedBlocks; }, blockSize: 1 }); /** * Mode namespace. */ var C_mode = C.mode = {}; /** * Abstract base block cipher mode template. */ var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ /** * Creates this mode for encryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); */ createEncryptor: function (cipher, iv) { return this.Encryptor.create(cipher, iv); }, /** * Creates this mode for decryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); */ createDecryptor: function (cipher, iv) { return this.Decryptor.create(cipher, iv); }, /** * Initializes a newly created mode. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @example * * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); */ init: function (cipher, iv) { this._cipher = cipher; this._iv = iv; } }); /** * Cipher Block Chaining mode. */ var CBC = C_mode.CBC = (function () { /** * Abstract base CBC mode. */ var CBC = BlockCipherMode.extend(); /** * CBC encryptor. */ CBC.Encryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // XOR and encrypt xorBlock.call(this, words, offset, blockSize); cipher.encryptBlock(words, offset); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); /** * CBC decryptor. */ CBC.Decryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); // Decrypt and XOR cipher.decryptBlock(words, offset); xorBlock.call(this, words, offset, blockSize); // This block becomes the previous block this._prevBlock = thisBlock; } }); function xorBlock(words, offset, blockSize) { // Shortcut var iv = this._iv; // Choose mixing block if (iv) { var block = iv; // Remove IV for subsequent blocks this._iv = undefined; } else { var block = this._prevBlock; } // XOR blocks for (var i = 0; i < blockSize; i++) { words[offset + i] ^= block[i]; } } return CBC; }()); /** * Padding namespace. */ var C_pad = C.pad = {}; /** * PKCS #5/7 padding strategy. */ var Pkcs7 = C_pad.Pkcs7 = { /** * Pads data using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to pad. * @param {number} blockSize The multiple that the data should be padded to. * * @static * * @example * * CryptoJS.pad.Pkcs7.pad(wordArray, 4); */ pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Create padding word var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; // Create padding var paddingWords = []; for (var i = 0; i < nPaddingBytes; i += 4) { paddingWords.push(paddingWord); } var padding = WordArray.create(paddingWords, nPaddingBytes); // Add padding data.concat(padding); }, /** * Unpads data that had been padded using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to unpad. * * @static * * @example * * CryptoJS.pad.Pkcs7.unpad(wordArray); */ unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; /** * Abstract base block cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) */ var BlockCipher = C_lib.BlockCipher = Cipher.extend({ /** * Configuration options. * * @property {Mode} mode The block mode to use. Default: CBC * @property {Padding} padding The padding strategy to use. Default: Pkcs7 */ cfg: Cipher.cfg.extend({ mode: CBC, padding: Pkcs7 }), reset: function () { // Reset cipher Cipher.reset.call(this); // Shortcuts var cfg = this.cfg; var iv = cfg.iv; var mode = cfg.mode; // Reset block mode if (this._xformMode == this._ENC_XFORM_MODE) { var modeCreator = mode.createEncryptor; } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { var modeCreator = mode.createDecryptor; // Keep at least one block in the buffer for unpadding this._minBufferSize = 1; } this._mode = modeCreator.call(mode, this, iv && iv.words); }, _doProcessBlock: function (words, offset) { this._mode.processBlock(words, offset); }, _doFinalize: function () { // Shortcut var padding = this.cfg.padding; // Finalize if (this._xformMode == this._ENC_XFORM_MODE) { // Pad data padding.pad(this._data, this.blockSize); // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); // Unpad data padding.unpad(finalProcessedBlocks); } return finalProcessedBlocks; }, blockSize: 128/32 }); /** * A collection of cipher parameters. * * @property {WordArray} ciphertext The raw ciphertext. * @property {WordArray} key The key to this ciphertext. * @property {WordArray} iv The IV used in the ciphering operation. * @property {WordArray} salt The salt used with a key derivation function. * @property {Cipher} algorithm The cipher algorithm. * @property {Mode} mode The block mode used in the ciphering operation. * @property {Padding} padding The padding scheme used in the ciphering operation. * @property {number} blockSize The block size of the cipher. * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. */ var CipherParams = C_lib.CipherParams = Base.extend({ /** * Initializes a newly created cipher params object. * * @param {Object} cipherParams An object with any of the possible cipher parameters. * * @example * * var cipherParams = CryptoJS.lib.CipherParams.create({ * ciphertext: ciphertextWordArray, * key: keyWordArray, * iv: ivWordArray, * salt: saltWordArray, * algorithm: CryptoJS.algo.AES, * mode: CryptoJS.mode.CBC, * padding: CryptoJS.pad.PKCS7, * blockSize: 4, * formatter: CryptoJS.format.OpenSSL * }); */ init: function (cipherParams) { this.mixIn(cipherParams); }, /** * Converts this cipher params object to a string. * * @param {Format} formatter (Optional) The formatting strategy to use. * * @return {string} The stringified cipher params. * * @throws Error If neither the formatter nor the default formatter is set. * * @example * * var string = cipherParams + ''; * var string = cipherParams.toString(); * var string = cipherParams.toString(CryptoJS.format.OpenSSL); */ toString: function (formatter) { return (formatter || this.formatter).stringify(this); } }); /** * Format namespace. */ var C_format = C.format = {}; /** * OpenSSL formatting strategy. */ var OpenSSLFormatter = C_format.OpenSSL = { /** * Converts a cipher params object to an OpenSSL-compatible string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The OpenSSL-compatible string. * * @static * * @example * * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); */ stringify: function (cipherParams) { // Shortcuts var ciphertext = cipherParams.ciphertext; var salt = cipherParams.salt; // Format if (salt) { var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); } else { var wordArray = ciphertext; } return wordArray.toString(Base64); }, /** * Converts an OpenSSL-compatible string to a cipher params object. * * @param {string} openSSLStr The OpenSSL-compatible string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); */ parse: function (openSSLStr) { // Parse base64 var ciphertext = Base64.parse(openSSLStr); // Shortcut var ciphertextWords = ciphertext.words; // Test for salt if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { // Extract salt var salt = WordArray.create(ciphertextWords.slice(2, 4)); // Remove salt from ciphertext ciphertextWords.splice(0, 4); ciphertext.sigBytes -= 16; } return CipherParams.create({ ciphertext: ciphertext, salt: salt }); } }; /** * A cipher wrapper that returns ciphertext as a serializable cipher params object. */ var SerializableCipher = C_lib.SerializableCipher = Base.extend({ /** * Configuration options. * * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL */ cfg: Base.extend({ format: OpenSSLFormatter }), /** * Encrypts a message. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Encrypt var encryptor = cipher.createEncryptor(key, cfg); var ciphertext = encryptor.finalize(message); // Shortcut var cipherCfg = encryptor.cfg; // Create and return serializable cipher params return CipherParams.create({ ciphertext: ciphertext, key: key, iv: cipherCfg.iv, algorithm: cipher, mode: cipherCfg.mode, padding: cipherCfg.padding, blockSize: cipher.blockSize, formatter: cfg.format }); }, /** * Decrypts serialized ciphertext. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Decrypt var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; }, /** * Converts serialized ciphertext to CipherParams, * else assumed CipherParams already and returns ciphertext unchanged. * * @param {CipherParams|string} ciphertext The ciphertext. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. * * @return {CipherParams} The unserialized ciphertext. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); */ _parse: function (ciphertext, format) { if (typeof ciphertext == 'string') { return format.parse(ciphertext, this); } else { return ciphertext; } } }); /** * Key derivation function namespace. */ var C_kdf = C.kdf = {}; /** * OpenSSL key derivation function. */ var OpenSSLKdf = C_kdf.OpenSSL = { /** * Derives a key and IV from a password. * * @param {string} password The password to derive from. * @param {number} keySize The size in words of the key to generate. * @param {number} ivSize The size in words of the IV to generate. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. * * @return {CipherParams} A cipher params object with the key, IV, and salt. * * @static * * @example * * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); */ execute: function (password, keySize, ivSize, salt) { // Generate random salt if (!salt) { salt = WordArray.random(64/8); } // Derive key and IV var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); // Separate key and IV var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); key.sigBytes = keySize * 4; // Return params return CipherParams.create({ key: key, iv: iv, salt: salt }); } }; /** * A serializable cipher wrapper that derives the key from a password, * and returns ciphertext as a serializable cipher params object. */ var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ /** * Configuration options. * * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL */ cfg: SerializableCipher.cfg.extend({ kdf: OpenSSLKdf }), /** * Encrypts a message using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); // Add IV to config cfg.iv = derivedParams.iv; // Encrypt var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); // Mix in derived params ciphertext.mixIn(derivedParams); return ciphertext; }, /** * Decrypts serialized ciphertext using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); // Add IV to config cfg.iv = derivedParams.iv; // Decrypt var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; } }); }()); })); },{"./core":52}],52:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(); } else if (typeof define === "function" && define.amd) { // AMD define([], factory); } else { // Global (browser) root.CryptoJS = factory(); } }(this, function () { /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { /* * Local polyfil of Object.create */ var create = Object.create || (function () { function F() {}; return function (obj) { var subtype; F.prototype = obj; subtype = new F(); F.prototype = null; return subtype; }; }()) /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn var subtype = create(this); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; var r = (function (m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function () { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); },{}],53:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strategy. */ var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; var reverseMap = this._reverseMap; if (!reverseMap) { reverseMap = this._reverseMap = []; for (var j = 0; j < map.length; j++) { reverseMap[map.charCodeAt(j)] = j; } } // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex !== -1) { base64StrLength = paddingIndex; } } // Convert return parseLoop(base64Str, base64StrLength, reverseMap); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; function parseLoop(base64Str, base64StrLength, reverseMap) { var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); } }()); return CryptoJS.enc.Base64; })); },{"./core":52}],54:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * UTF-16 BE encoding strategy. */ var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { /** * Converts a word array to a UTF-16 BE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 BE string. * * @static * * @example * * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 BE string to a word array. * * @param {string} utf16Str The UTF-16 BE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); } return WordArray.create(words, utf16StrLength * 2); } }; /** * UTF-16 LE encoding strategy. */ C_enc.Utf16LE = { /** * Converts a word array to a UTF-16 LE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 LE string. * * @static * * @example * * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 LE string to a word array. * * @param {string} utf16Str The UTF-16 LE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); } return WordArray.create(words, utf16StrLength * 2); } }; function swapEndian(word) { return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); } }()); return CryptoJS.enc.Utf16; })); },{"./core":52}],55:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var MD5 = C_algo.MD5; /** * This key derivation function is meant to conform with EVP_BytesToKey. * www.openssl.org/docs/crypto/EVP_BytesToKey.html */ var EvpKDF = C_algo.EvpKDF = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hash algorithm to use. Default: MD5 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: MD5, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.EvpKDF.create(); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init hasher var hasher = cfg.hasher.create(); // Initial values var derivedKey = WordArray.create(); // Shortcuts var derivedKeyWords = derivedKey.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { if (block) { hasher.update(block); } var block = hasher.update(password).finalize(salt); hasher.reset(); // Iterations for (var i = 1; i < iterations; i++) { block = hasher.finalize(block); hasher.reset(); } derivedKey.concat(block); } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.EvpKDF(password, salt); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); */ C.EvpKDF = function (password, salt, cfg) { return EvpKDF.create(cfg).compute(password, salt); }; }()); return CryptoJS.EvpKDF; })); },{"./core":52,"./hmac":57,"./sha1":76}],56:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var CipherParams = C_lib.CipherParams; var C_enc = C.enc; var Hex = C_enc.Hex; var C_format = C.format; var HexFormatter = C_format.Hex = { /** * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The hexadecimally encoded string. * * @static * * @example * * var hexString = CryptoJS.format.Hex.stringify(cipherParams); */ stringify: function (cipherParams) { return cipherParams.ciphertext.toString(Hex); }, /** * Converts a hexadecimally encoded ciphertext string to a cipher params object. * * @param {string} input The hexadecimally encoded string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.Hex.parse(hexString); */ parse: function (input) { var ciphertext = Hex.parse(input); return CipherParams.create({ ciphertext: ciphertext }); } }; }()); return CryptoJS.format.Hex; })); },{"./cipher-core":51,"./core":52}],57:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var C_algo = C.algo; /** * HMAC algorithm. */ var HMAC = C_algo.HMAC = Base.extend({ /** * Initializes a newly created HMAC. * * @param {Hasher} hasher The hash algorithm to use. * @param {WordArray|string} key The secret key. * * @example * * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); */ init: function (hasher, key) { // Init hasher hasher = this._hasher = new hasher.init(); // Convert string to WordArray, else assume WordArray already if (typeof key == 'string') { key = Utf8.parse(key); } // Shortcuts var hasherBlockSize = hasher.blockSize; var hasherBlockSizeBytes = hasherBlockSize * 4; // Allow arbitrary length keys if (key.sigBytes > hasherBlockSizeBytes) { key = hasher.finalize(key); } // Clamp excess bits key.clamp(); // Clone key for inner and outer pads var oKey = this._oKey = key.clone(); var iKey = this._iKey = key.clone(); // Shortcuts var oKeyWords = oKey.words; var iKeyWords = iKey.words; // XOR keys with pad constants for (var i = 0; i < hasherBlockSize; i++) { oKeyWords[i] ^= 0x5c5c5c5c; iKeyWords[i] ^= 0x36363636; } oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; // Set initial values this.reset(); }, /** * Resets this HMAC to its initial state. * * @example * * hmacHasher.reset(); */ reset: function () { // Shortcut var hasher = this._hasher; // Reset hasher.reset(); hasher.update(this._iKey); }, /** * Updates this HMAC with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {HMAC} This HMAC instance. * * @example * * hmacHasher.update('message'); * hmacHasher.update(wordArray); */ update: function (messageUpdate) { this._hasher.update(messageUpdate); // Chainable return this; }, /** * Finalizes the HMAC computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The HMAC. * * @example * * var hmac = hmacHasher.finalize(); * var hmac = hmacHasher.finalize('message'); * var hmac = hmacHasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Shortcut var hasher = this._hasher; // Compute HMAC var innerHash = hasher.finalize(messageUpdate); hasher.reset(); var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); return hmac; } }); }()); })); },{"./core":52}],58:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./x64-core"), require("./lib-typedarrays"), require("./enc-utf16"), require("./enc-base64"), require("./md5"), require("./sha1"), require("./sha256"), require("./sha224"), require("./sha512"), require("./sha384"), require("./sha3"), require("./ripemd160"), require("./hmac"), require("./pbkdf2"), require("./evpkdf"), require("./cipher-core"), require("./mode-cfb"), require("./mode-ctr"), require("./mode-ctr-gladman"), require("./mode-ofb"), require("./mode-ecb"), require("./pad-ansix923"), require("./pad-iso10126"), require("./pad-iso97971"), require("./pad-zeropadding"), require("./pad-nopadding"), require("./format-hex"), require("./aes"), require("./tripledes"), require("./rc4"), require("./rabbit"), require("./rabbit-legacy")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory); } else { // Global (browser) root.CryptoJS = factory(root.CryptoJS); } }(this, function (CryptoJS) { return CryptoJS; })); },{"./aes":50,"./cipher-core":51,"./core":52,"./enc-base64":53,"./enc-utf16":54,"./evpkdf":55,"./format-hex":56,"./hmac":57,"./lib-typedarrays":59,"./md5":60,"./mode-cfb":61,"./mode-ctr":63,"./mode-ctr-gladman":62,"./mode-ecb":64,"./mode-ofb":65,"./pad-ansix923":66,"./pad-iso10126":67,"./pad-iso97971":68,"./pad-nopadding":69,"./pad-zeropadding":70,"./pbkdf2":71,"./rabbit":73,"./rabbit-legacy":72,"./rc4":74,"./ripemd160":75,"./sha1":76,"./sha224":77,"./sha256":78,"./sha3":79,"./sha384":80,"./sha512":81,"./tripledes":82,"./x64-core":83}],59:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Check if typed arrays are supported if (typeof ArrayBuffer != 'function') { return; } // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; // Reference original init var superInit = WordArray.init; // Augment WordArray.init to handle typed arrays var subInit = WordArray.init = function (typedArray) { // Convert buffers to uint8 if (typedArray instanceof ArrayBuffer) { typedArray = new Uint8Array(typedArray); } // Convert other array views to uint8 if ( typedArray instanceof Int8Array || (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array ) { typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); } // Handle Uint8Array if (typedArray instanceof Uint8Array) { // Shortcut var typedArrayByteLength = typedArray.byteLength; // Extract bytes var words = []; for (var i = 0; i < typedArrayByteLength; i++) { words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); } // Initialize this word array superInit.call(this, words, typedArrayByteLength); } else { // Else call normal init superInit.apply(this, arguments); } }; subInit.prototype = WordArray; }()); return CryptoJS.lib.WordArray; })); },{"./core":52}],60:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var T = []; // Compute constants (function () { for (var i = 0; i < 64; i++) { T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; } }()); /** * MD5 hash algorithm. */ var MD5 = C_algo.MD5 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 ]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcuts var H = this._hash.words; var M_offset_0 = M[offset + 0]; var M_offset_1 = M[offset + 1]; var M_offset_2 = M[offset + 2]; var M_offset_3 = M[offset + 3]; var M_offset_4 = M[offset + 4]; var M_offset_5 = M[offset + 5]; var M_offset_6 = M[offset + 6]; var M_offset_7 = M[offset + 7]; var M_offset_8 = M[offset + 8]; var M_offset_9 = M[offset + 9]; var M_offset_10 = M[offset + 10]; var M_offset_11 = M[offset + 11]; var M_offset_12 = M[offset + 12]; var M_offset_13 = M[offset + 13]; var M_offset_14 = M[offset + 14]; var M_offset_15 = M[offset + 15]; // Working varialbes var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; // Computation a = FF(a, b, c, d, M_offset_0, 7, T[0]); d = FF(d, a, b, c, M_offset_1, 12, T[1]); c = FF(c, d, a, b, M_offset_2, 17, T[2]); b = FF(b, c, d, a, M_offset_3, 22, T[3]); a = FF(a, b, c, d, M_offset_4, 7, T[4]); d = FF(d, a, b, c, M_offset_5, 12, T[5]); c = FF(c, d, a, b, M_offset_6, 17, T[6]); b = FF(b, c, d, a, M_offset_7, 22, T[7]); a = FF(a, b, c, d, M_offset_8, 7, T[8]); d = FF(d, a, b, c, M_offset_9, 12, T[9]); c = FF(c, d, a, b, M_offset_10, 17, T[10]); b = FF(b, c, d, a, M_offset_11, 22, T[11]); a = FF(a, b, c, d, M_offset_12, 7, T[12]); d = FF(d, a, b, c, M_offset_13, 12, T[13]); c = FF(c, d, a, b, M_offset_14, 17, T[14]); b = FF(b, c, d, a, M_offset_15, 22, T[15]); a = GG(a, b, c, d, M_offset_1, 5, T[16]); d = GG(d, a, b, c, M_offset_6, 9, T[17]); c = GG(c, d, a, b, M_offset_11, 14, T[18]); b = GG(b, c, d, a, M_offset_0, 20, T[19]); a = GG(a, b, c, d, M_offset_5, 5, T[20]); d = GG(d, a, b, c, M_offset_10, 9, T[21]); c = GG(c, d, a, b, M_offset_15, 14, T[22]); b = GG(b, c, d, a, M_offset_4, 20, T[23]); a = GG(a, b, c, d, M_offset_9, 5, T[24]); d = GG(d, a, b, c, M_offset_14, 9, T[25]); c = GG(c, d, a, b, M_offset_3, 14, T[26]); b = GG(b, c, d, a, M_offset_8, 20, T[27]); a = GG(a, b, c, d, M_offset_13, 5, T[28]); d = GG(d, a, b, c, M_offset_2, 9, T[29]); c = GG(c, d, a, b, M_offset_7, 14, T[30]); b = GG(b, c, d, a, M_offset_12, 20, T[31]); a = HH(a, b, c, d, M_offset_5, 4, T[32]); d = HH(d, a, b, c, M_offset_8, 11, T[33]); c = HH(c, d, a, b, M_offset_11, 16, T[34]); b = HH(b, c, d, a, M_offset_14, 23, T[35]); a = HH(a, b, c, d, M_offset_1, 4, T[36]); d = HH(d, a, b, c, M_offset_4, 11, T[37]); c = HH(c, d, a, b, M_offset_7, 16, T[38]); b = HH(b, c, d, a, M_offset_10, 23, T[39]); a = HH(a, b, c, d, M_offset_13, 4, T[40]); d = HH(d, a, b, c, M_offset_0, 11, T[41]); c = HH(c, d, a, b, M_offset_3, 16, T[42]); b = HH(b, c, d, a, M_offset_6, 23, T[43]); a = HH(a, b, c, d, M_offset_9, 4, T[44]); d = HH(d, a, b, c, M_offset_12, 11, T[45]); c = HH(c, d, a, b, M_offset_15, 16, T[46]); b = HH(b, c, d, a, M_offset_2, 23, T[47]); a = II(a, b, c, d, M_offset_0, 6, T[48]); d = II(d, a, b, c, M_offset_7, 10, T[49]); c = II(c, d, a, b, M_offset_14, 15, T[50]); b = II(b, c, d, a, M_offset_5, 21, T[51]); a = II(a, b, c, d, M_offset_12, 6, T[52]); d = II(d, a, b, c, M_offset_3, 10, T[53]); c = II(c, d, a, b, M_offset_10, 15, T[54]); b = II(b, c, d, a, M_offset_1, 21, T[55]); a = II(a, b, c, d, M_offset_8, 6, T[56]); d = II(d, a, b, c, M_offset_15, 10, T[57]); c = II(c, d, a, b, M_offset_6, 15, T[58]); b = II(b, c, d, a, M_offset_13, 21, T[59]); a = II(a, b, c, d, M_offset_4, 6, T[60]); d = II(d, a, b, c, M_offset_11, 10, T[61]); c = II(c, d, a, b, M_offset_2, 15, T[62]); b = II(b, c, d, a, M_offset_9, 21, T[63]); // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); var nBitsTotalL = nBitsTotal; dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) ); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 4; i++) { // Shortcut var H_i = H[i]; H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function FF(a, b, c, d, x, s, t) { var n = a + ((b & c) | (~b & d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function GG(a, b, c, d, x, s, t) { var n = a + ((b & d) | (c & ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function HH(a, b, c, d, x, s, t) { var n = a + (b ^ c ^ d) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function II(a, b, c, d, x, s, t) { var n = a + (c ^ (b | ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.MD5('message'); * var hash = CryptoJS.MD5(wordArray); */ C.MD5 = Hasher._createHelper(MD5); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacMD5(message, key); */ C.HmacMD5 = Hasher._createHmacHelper(MD5); }(Math)); return CryptoJS.MD5; })); },{"./core":52}],61:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher Feedback block mode. */ CryptoJS.mode.CFB = (function () { var CFB = CryptoJS.lib.BlockCipherMode.extend(); CFB.Encryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); CFB.Decryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // This block becomes the previous block this._prevBlock = thisBlock; } }); function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { // Shortcut var iv = this._iv; // Generate keystream if (iv) { var keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } else { var keystream = this._prevBlock; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } return CFB; }()); return CryptoJS.mode.CFB; })); },{"./cipher-core":51,"./core":52}],62:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve * Counter block mode compatible with Dr Brian Gladman fileenc.c * derived from CryptoJS.mode.CTR * Jan Hruby [email protected] */ CryptoJS.mode.CTRGladman = (function () { var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); function incWord(word) { if (((word >> 24) & 0xff) === 0xff) { //overflow var b1 = (word >> 16)&0xff; var b2 = (word >> 8)&0xff; var b3 = word & 0xff; if (b1 === 0xff) // overflow b1 { b1 = 0; if (b2 === 0xff) { b2 = 0; if (b3 === 0xff) { b3 = 0; } else { ++b3; } } else { ++b2; } } else { ++b1; } word = 0; word += (b1 << 16); word += (b2 << 8); word += b3; } else { word += (0x01 << 24); } return word; } function incCounter(counter) { if ((counter[0] = incWord(counter[0])) === 0) { // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 counter[1] = incWord(counter[1]); } return counter; } var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } incCounter(counter); var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTRGladman.Decryptor = Encryptor; return CTRGladman; }()); return CryptoJS.mode.CTRGladman; })); },{"./cipher-core":51,"./core":52}],63:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Counter block mode. */ CryptoJS.mode.CTR = (function () { var CTR = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = CTR.Encryptor = CTR.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Increment counter counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTR.Decryptor = Encryptor; return CTR; }()); return CryptoJS.mode.CTR; })); },{"./cipher-core":51,"./core":52}],64:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Electronic Codebook block mode. */ CryptoJS.mode.ECB = (function () { var ECB = CryptoJS.lib.BlockCipherMode.extend(); ECB.Encryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.encryptBlock(words, offset); } }); ECB.Decryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.decryptBlock(words, offset); } }); return ECB; }()); return CryptoJS.mode.ECB; })); },{"./cipher-core":51,"./core":52}],65:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Output Feedback block mode. */ CryptoJS.mode.OFB = (function () { var OFB = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = OFB.Encryptor = OFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var keystream = this._keystream; // Generate keystream if (iv) { keystream = this._keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); OFB.Decryptor = Encryptor; return OFB; }()); return CryptoJS.mode.OFB; })); },{"./cipher-core":51,"./core":52}],66:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ANSI X.923 padding strategy. */ CryptoJS.pad.AnsiX923 = { pad: function (data, blockSize) { // Shortcuts var dataSigBytes = data.sigBytes; var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; // Compute last byte position var lastBytePos = dataSigBytes + nPaddingBytes - 1; // Pad data.clamp(); data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); data.sigBytes += nPaddingBytes; }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Ansix923; })); },{"./cipher-core":51,"./core":52}],67:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO 10126 padding strategy. */ CryptoJS.pad.Iso10126 = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Pad data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Iso10126; })); },{"./cipher-core":51,"./core":52}],68:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO/IEC 9797-1 Padding Method 2. */ CryptoJS.pad.Iso97971 = { pad: function (data, blockSize) { // Add 0x80 byte data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); // Zero pad the rest CryptoJS.pad.ZeroPadding.pad(data, blockSize); }, unpad: function (data) { // Remove zero padding CryptoJS.pad.ZeroPadding.unpad(data); // Remove one more byte -- the 0x80 byte data.sigBytes--; } }; return CryptoJS.pad.Iso97971; })); },{"./cipher-core":51,"./core":52}],69:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * A noop padding strategy. */ CryptoJS.pad.NoPadding = { pad: function () { }, unpad: function () { } }; return CryptoJS.pad.NoPadding; })); },{"./cipher-core":51,"./core":52}],70:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Zero padding strategy. */ CryptoJS.pad.ZeroPadding = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Pad data.clamp(); data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); }, unpad: function (data) { // Shortcut var dataWords = data.words; // Unpad var i = data.sigBytes - 1; while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { i--; } data.sigBytes = i + 1; } }; return CryptoJS.pad.ZeroPadding; })); },{"./cipher-core":51,"./core":52}],71:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA1 = C_algo.SHA1; var HMAC = C_algo.HMAC; /** * Password-Based Key Derivation Function 2 algorithm. */ var PBKDF2 = C_algo.PBKDF2 = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hasher to use. Default: SHA1 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: SHA1, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.PBKDF2.create(); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init HMAC var hmac = HMAC.create(cfg.hasher, password); // Initial values var derivedKey = WordArray.create(); var blockIndex = WordArray.create([0x00000001]); // Shortcuts var derivedKeyWords = derivedKey.words; var blockIndexWords = blockIndex.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { var block = hmac.update(salt).finalize(blockIndex); hmac.reset(); // Shortcuts var blockWords = block.words; var blockWordsLength = blockWords.length; // Iterations var intermediate = block; for (var i = 1; i < iterations; i++) { intermediate = hmac.finalize(intermediate); hmac.reset(); // Shortcut var intermediateWords = intermediate.words; // XOR intermediate with block for (var j = 0; j < blockWordsLength; j++) { blockWords[j] ^= intermediateWords[j]; } } derivedKey.concat(block); blockIndexWords[0]++; } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.PBKDF2(password, salt); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); */ C.PBKDF2 = function (password, salt, cfg) { return PBKDF2.create(cfg).compute(password, salt); }; }()); return CryptoJS.PBKDF2; })); },{"./core":52,"./hmac":57,"./sha1":76}],72:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm. * * This is a legacy version that neglected to convert the key to little-endian. * This error doesn't affect the cipher's security, * but it does affect its compatibility with other implementations. */ var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); */ C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); }()); return CryptoJS.RabbitLegacy; })); },{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],73:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm */ var Rabbit = C_algo.Rabbit = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Swap endian for (var i = 0; i < 4; i++) { K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); } // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this);<|fim▁hole|> // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); */ C.Rabbit = StreamCipher._createHelper(Rabbit); }()); return CryptoJS.Rabbit; })); },{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],74:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; /** * RC4 stream cipher algorithm. */ var RC4 = C_algo.RC4 = StreamCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySigBytes = key.sigBytes; // Init sbox var S = this._S = []; for (var i = 0; i < 256; i++) { S[i] = i; } // Key setup for (var i = 0, j = 0; i < 256; i++) { var keyByteIndex = i % keySigBytes; var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; j = (j + S[i] + keyByte) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; } // Counters this._i = this._j = 0; }, _doProcessBlock: function (M, offset) { M[offset] ^= generateKeystreamWord.call(this); }, keySize: 256/32, ivSize: 0 }); function generateKeystreamWord() { // Shortcuts var S = this._S; var i = this._i; var j = this._j; // Generate keystream word var keystreamWord = 0; for (var n = 0; n < 4; n++) { i = (i + 1) % 256; j = (j + S[i]) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); } // Update counters this._i = i; this._j = j; return keystreamWord; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); */ C.RC4 = StreamCipher._createHelper(RC4); /** * Modified RC4 stream cipher algorithm. */ var RC4Drop = C_algo.RC4Drop = RC4.extend({ /** * Configuration options. * * @property {number} drop The number of keystream words to drop. Default 192 */ cfg: RC4.cfg.extend({ drop: 192 }), _doReset: function () { RC4._doReset.call(this); // Drop for (var i = this.cfg.drop; i > 0; i--) { generateKeystreamWord.call(this); } } }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); */ C.RC4Drop = StreamCipher._createHelper(RC4Drop); }()); return CryptoJS.RC4; })); },{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],75:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve (c) 2012 by Cédric Mesnil. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - 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. */ (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var _zl = WordArray.create([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]); var _zr = WordArray.create([ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]); var _sl = WordArray.create([ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); var _sr = WordArray.create([ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); /** * RIPEMD160 hash algorithm. */ var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ _doReset: function () { this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; // Swap M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcut var H = this._hash.words; var hl = _hl.words; var hr = _hr.words; var zl = _zl.words; var zr = _zr.words; var sl = _sl.words; var sr = _sr.words; // Working variables var al, bl, cl, dl, el; var ar, br, cr, dr, er; ar = al = H[0]; br = bl = H[1]; cr = cl = H[2]; dr = dl = H[3]; er = el = H[4]; // Computation var t; for (var i = 0; i < 80; i += 1) { t = (al + M[offset+zl[i]])|0; if (i<16){ t += f1(bl,cl,dl) + hl[0]; } else if (i<32) { t += f2(bl,cl,dl) + hl[1]; } else if (i<48) { t += f3(bl,cl,dl) + hl[2]; } else if (i<64) { t += f4(bl,cl,dl) + hl[3]; } else {// if (i<80) { t += f5(bl,cl,dl) + hl[4]; } t = t|0; t = rotl(t,sl[i]); t = (t+el)|0; al = el; el = dl; dl = rotl(cl, 10); cl = bl; bl = t; t = (ar + M[offset+zr[i]])|0; if (i<16){ t += f5(br,cr,dr) + hr[0]; } else if (i<32) { t += f4(br,cr,dr) + hr[1]; } else if (i<48) { t += f3(br,cr,dr) + hr[2]; } else if (i<64) { t += f2(br,cr,dr) + hr[3]; } else {// if (i<80) { t += f1(br,cr,dr) + hr[4]; } t = t|0; t = rotl(t,sr[i]) ; t = (t+er)|0; ar = er; er = dr; dr = rotl(cr, 10); cr = br; br = t; } // Intermediate hash value t = (H[1] + cl + dr)|0; H[1] = (H[2] + dl + er)|0; H[2] = (H[3] + el + ar)|0; H[3] = (H[4] + al + br)|0; H[4] = (H[0] + bl + cr)|0; H[0] = t; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 5; i++) { // Shortcut var H_i = H[i]; // Swap H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function f1(x, y, z) { return ((x) ^ (y) ^ (z)); } function f2(x, y, z) { return (((x)&(y)) | ((~x)&(z))); } function f3(x, y, z) { return (((x) | (~(y))) ^ (z)); } function f4(x, y, z) { return (((x) & (z)) | ((y)&(~(z)))); } function f5(x, y, z) { return ((x) ^ ((y) |(~(z)))); } function rotl(x,n) { return (x<<n) | (x>>>(32-n)); } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.RIPEMD160('message'); * var hash = CryptoJS.RIPEMD160(wordArray); */ C.RIPEMD160 = Hasher._createHelper(RIPEMD160); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacRIPEMD160(message, key); */ C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); }(Math)); return CryptoJS.RIPEMD160; })); },{"./core":52}],76:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Reusable object var W = []; /** * SHA-1 hash algorithm. */ var SHA1 = C_algo.SHA1 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; // Computation for (var i = 0; i < 80; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; W[i] = (n << 1) | (n >>> 31); } var t = ((a << 5) | (a >>> 27)) + e + W[i]; if (i < 20) { t += ((b & c) | (~b & d)) + 0x5a827999; } else if (i < 40) { t += (b ^ c ^ d) + 0x6ed9eba1; } else if (i < 60) { t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; } else /* if (i < 80) */ { t += (b ^ c ^ d) - 0x359d3e2a; } e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA1('message'); * var hash = CryptoJS.SHA1(wordArray); */ C.SHA1 = Hasher._createHelper(SHA1); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA1(message, key); */ C.HmacSHA1 = Hasher._createHmacHelper(SHA1); }()); return CryptoJS.SHA1; })); },{"./core":52}],77:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./sha256")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha256"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA256 = C_algo.SHA256; /** * SHA-224 hash algorithm. */ var SHA224 = C_algo.SHA224 = SHA256.extend({ _doReset: function () { this._hash = new WordArray.init([ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]); }, _doFinalize: function () { var hash = SHA256._doFinalize.call(this); hash.sigBytes -= 4; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA224('message'); * var hash = CryptoJS.SHA224(wordArray); */ C.SHA224 = SHA256._createHelper(SHA224); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA224(message, key); */ C.HmacSHA224 = SHA256._createHmacHelper(SHA224); }()); return CryptoJS.SHA224; })); },{"./core":52,"./sha256":78}],78:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Initialization and round constants tables var H = []; var K = []; // Compute constants (function () { function isPrime(n) { var sqrtN = Math.sqrt(n); for (var factor = 2; factor <= sqrtN; factor++) { if (!(n % factor)) { return false; } } return true; } function getFractionalBits(n) { return ((n - (n | 0)) * 0x100000000) | 0; } var n = 2; var nPrime = 0; while (nPrime < 64) { if (isPrime(n)) { if (nPrime < 8) { H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); } K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); nPrime++; } n++; } }()); // Reusable object var W = []; /** * SHA-256 hash algorithm. */ var SHA256 = C_algo.SHA256 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init(H.slice(0)); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; var f = H[5]; var g = H[6]; var h = H[7]; // Computation for (var i = 0; i < 64; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var gamma0x = W[i - 15]; var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ ((gamma0x << 14) | (gamma0x >>> 18)) ^ (gamma0x >>> 3); var gamma1x = W[i - 2]; var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ ((gamma1x << 13) | (gamma1x >>> 19)) ^ (gamma1x >>> 10); W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; } var ch = (e & f) ^ (~e & g); var maj = (a & b) ^ (a & c) ^ (b & c); var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); var t1 = h + sigma1 + ch + K[i] + W[i]; var t2 = sigma0 + maj; h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA256('message'); * var hash = CryptoJS.SHA256(wordArray); */ C.SHA256 = Hasher._createHelper(SHA256); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA256(message, key); */ C.HmacSHA256 = Hasher._createHmacHelper(SHA256); }(Math)); return CryptoJS.SHA256; })); },{"./core":52}],79:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var C_algo = C.algo; // Constants tables var RHO_OFFSETS = []; var PI_INDEXES = []; var ROUND_CONSTANTS = []; // Compute Constants (function () { // Compute rho offset constants var x = 1, y = 0; for (var t = 0; t < 24; t++) { RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; var newX = y % 5; var newY = (2 * x + 3 * y) % 5; x = newX; y = newY; } // Compute pi index constants for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; } } // Compute round constants var LFSR = 0x01; for (var i = 0; i < 24; i++) { var roundConstantMsw = 0; var roundConstantLsw = 0; for (var j = 0; j < 7; j++) { if (LFSR & 0x01) { var bitPosition = (1 << j) - 1; if (bitPosition < 32) { roundConstantLsw ^= 1 << bitPosition; } else /* if (bitPosition >= 32) */ { roundConstantMsw ^= 1 << (bitPosition - 32); } } // Compute next LFSR if (LFSR & 0x80) { // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 LFSR = (LFSR << 1) ^ 0x71; } else { LFSR <<= 1; } } ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); } }()); // Reusable objects for temporary values var T = []; (function () { for (var i = 0; i < 25; i++) { T[i] = X64Word.create(); } }()); /** * SHA-3 hash algorithm. */ var SHA3 = C_algo.SHA3 = Hasher.extend({ /** * Configuration options. * * @property {number} outputLength * The desired number of bits in the output hash. * Only values permitted are: 224, 256, 384, 512. * Default: 512 */ cfg: Hasher.cfg.extend({ outputLength: 512 }), _doReset: function () { var state = this._state = [] for (var i = 0; i < 25; i++) { state[i] = new X64Word.init(); } this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; }, _doProcessBlock: function (M, offset) { // Shortcuts var state = this._state; var nBlockSizeLanes = this.blockSize / 2; // Absorb for (var i = 0; i < nBlockSizeLanes; i++) { // Shortcuts var M2i = M[offset + 2 * i]; var M2i1 = M[offset + 2 * i + 1]; // Swap endian M2i = ( (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) ); M2i1 = ( (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) ); // Absorb message into state var lane = state[i]; lane.high ^= M2i1; lane.low ^= M2i; } // Rounds for (var round = 0; round < 24; round++) { // Theta for (var x = 0; x < 5; x++) { // Mix column lanes var tMsw = 0, tLsw = 0; for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; tMsw ^= lane.high; tLsw ^= lane.low; } // Temporary values var Tx = T[x]; Tx.high = tMsw; Tx.low = tLsw; } for (var x = 0; x < 5; x++) { // Shortcuts var Tx4 = T[(x + 4) % 5]; var Tx1 = T[(x + 1) % 5]; var Tx1Msw = Tx1.high; var Tx1Lsw = Tx1.low; // Mix surrounding columns var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; lane.high ^= tMsw; lane.low ^= tLsw; } } // Rho Pi for (var laneIndex = 1; laneIndex < 25; laneIndex++) { // Shortcuts var lane = state[laneIndex]; var laneMsw = lane.high; var laneLsw = lane.low; var rhoOffset = RHO_OFFSETS[laneIndex]; // Rotate lanes if (rhoOffset < 32) { var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); } else /* if (rhoOffset >= 32) */ { var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); } // Transpose lanes var TPiLane = T[PI_INDEXES[laneIndex]]; TPiLane.high = tMsw; TPiLane.low = tLsw; } // Rho pi at x = y = 0 var T0 = T[0]; var state0 = state[0]; T0.high = state0.high; T0.low = state0.low; // Chi for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { // Shortcuts var laneIndex = x + 5 * y; var lane = state[laneIndex]; var TLane = T[laneIndex]; var Tx1Lane = T[((x + 1) % 5) + 5 * y]; var Tx2Lane = T[((x + 2) % 5) + 5 * y]; // Mix rows lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); } } // Iota var lane = state[0]; var roundConstant = ROUND_CONSTANTS[round]; lane.high ^= roundConstant.high; lane.low ^= roundConstant.low;; } }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; var blockSizeBits = this.blockSize * 32; // Add padding dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Shortcuts var state = this._state; var outputLengthBytes = this.cfg.outputLength / 8; var outputLengthLanes = outputLengthBytes / 8; // Squeeze var hashWords = []; for (var i = 0; i < outputLengthLanes; i++) { // Shortcuts var lane = state[i]; var laneMsw = lane.high; var laneLsw = lane.low; // Swap endian laneMsw = ( (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) ); laneLsw = ( (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) ); // Squeeze state to retrieve hash hashWords.push(laneLsw); hashWords.push(laneMsw); } // Return final computed hash return new WordArray.init(hashWords, outputLengthBytes); }, clone: function () { var clone = Hasher.clone.call(this); var state = clone._state = this._state.slice(0); for (var i = 0; i < 25; i++) { state[i] = state[i].clone(); } return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA3('message'); * var hash = CryptoJS.SHA3(wordArray); */ C.SHA3 = Hasher._createHelper(SHA3); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA3(message, key); */ C.HmacSHA3 = Hasher._createHmacHelper(SHA3); }(Math)); return CryptoJS.SHA3; })); },{"./core":52,"./x64-core":83}],80:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./x64-core"), require("./sha512")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./sha512"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; var SHA512 = C_algo.SHA512; /** * SHA-384 hash algorithm. */ var SHA384 = C_algo.SHA384 = SHA512.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) ]); }, _doFinalize: function () { var hash = SHA512._doFinalize.call(this); hash.sigBytes -= 16; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA384('message'); * var hash = CryptoJS.SHA384(wordArray); */ C.SHA384 = SHA512._createHelper(SHA384); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA384(message, key); */ C.HmacSHA384 = SHA512._createHmacHelper(SHA384); }()); return CryptoJS.SHA384; })); },{"./core":52,"./sha512":81,"./x64-core":83}],81:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; function X64Word_create() { return X64Word.create.apply(X64Word, arguments); } // Constants var K = [ X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) ]; // Reusable objects var W = []; (function () { for (var i = 0; i < 80; i++) { W[i] = X64Word_create(); } }()); /** * SHA-512 hash algorithm. */ var SHA512 = C_algo.SHA512 = Hasher.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) ]); }, _doProcessBlock: function (M, offset) { // Shortcuts var H = this._hash.words; var H0 = H[0]; var H1 = H[1]; var H2 = H[2]; var H3 = H[3]; var H4 = H[4]; var H5 = H[5]; var H6 = H[6]; var H7 = H[7]; var H0h = H0.high; var H0l = H0.low; var H1h = H1.high; var H1l = H1.low; var H2h = H2.high; var H2l = H2.low; var H3h = H3.high; var H3l = H3.low; var H4h = H4.high; var H4l = H4.low; var H5h = H5.high; var H5l = H5.low; var H6h = H6.high; var H6l = H6.low; var H7h = H7.high; var H7l = H7.low; // Working variables var ah = H0h; var al = H0l; var bh = H1h; var bl = H1l; var ch = H2h; var cl = H2l; var dh = H3h; var dl = H3l; var eh = H4h; var el = H4l; var fh = H5h; var fl = H5l; var gh = H6h; var gl = H6l; var hh = H7h; var hl = H7l; // Rounds for (var i = 0; i < 80; i++) { // Shortcut var Wi = W[i]; // Extend message if (i < 16) { var Wih = Wi.high = M[offset + i * 2] | 0; var Wil = Wi.low = M[offset + i * 2 + 1] | 0; } else { // Gamma0 var gamma0x = W[i - 15]; var gamma0xh = gamma0x.high; var gamma0xl = gamma0x.low; var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); // Gamma1 var gamma1x = W[i - 2]; var gamma1xh = gamma1x.high; var gamma1xl = gamma1x.low; var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] var Wi7 = W[i - 7]; var Wi7h = Wi7.high; var Wi7l = Wi7.low; var Wi16 = W[i - 16]; var Wi16h = Wi16.high; var Wi16l = Wi16.low; var Wil = gamma0l + Wi7l; var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); var Wil = Wil + gamma1l; var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); var Wil = Wil + Wi16l; var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); Wi.high = Wih; Wi.low = Wil; } var chh = (eh & fh) ^ (~eh & gh); var chl = (el & fl) ^ (~el & gl); var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); var majl = (al & bl) ^ (al & cl) ^ (bl & cl); var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); // t1 = h + sigma1 + ch + K[i] + W[i] var Ki = K[i]; var Kih = Ki.high; var Kil = Ki.low; var t1l = hl + sigma1l; var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); var t1l = t1l + chl; var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); var t1l = t1l + Kil; var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); var t1l = t1l + Wil; var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); // t2 = sigma0 + maj var t2l = sigma0l + majl; var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); // Update working variables hh = gh; hl = gl; gh = fh; gl = fl; fh = eh; fl = el; el = (dl + t1l) | 0; eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; dh = ch; dl = cl; ch = bh; cl = bl; bh = ah; bl = al; al = (t1l + t2l) | 0; ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; } // Intermediate hash value H0l = H0.low = (H0l + al); H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); H1l = H1.low = (H1l + bl); H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); H2l = H2.low = (H2l + cl); H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); H3l = H3.low = (H3l + dl); H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); H4l = H4.low = (H4l + el); H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); H5l = H5.low = (H5l + fl); H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); H6l = H6.low = (H6l + gl); H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); H7l = H7.low = (H7l + hl); H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Convert hash to 32-bit word array before returning var hash = this._hash.toX32(); // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; }, blockSize: 1024/32 }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA512('message'); * var hash = CryptoJS.SHA512(wordArray); */ C.SHA512 = Hasher._createHelper(SHA512); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA512(message, key); */ C.HmacSHA512 = Hasher._createHmacHelper(SHA512); }()); return CryptoJS.SHA512; })); },{"./core":52,"./x64-core":83}],82:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Permuted Choice 1 constants var PC1 = [ 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 ]; // Permuted Choice 2 constants var PC2 = [ 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 ]; // Cumulative bit shift constants var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; // SBOXes and round permutation constants var SBOX_P = [ { 0x0: 0x808200, 0x10000000: 0x8000, 0x20000000: 0x808002, 0x30000000: 0x2, 0x40000000: 0x200, 0x50000000: 0x808202, 0x60000000: 0x800202, 0x70000000: 0x800000, 0x80000000: 0x202, 0x90000000: 0x800200, 0xa0000000: 0x8200, 0xb0000000: 0x808000, 0xc0000000: 0x8002, 0xd0000000: 0x800002, 0xe0000000: 0x0, 0xf0000000: 0x8202, 0x8000000: 0x0, 0x18000000: 0x808202, 0x28000000: 0x8202, 0x38000000: 0x8000, 0x48000000: 0x808200, 0x58000000: 0x200, 0x68000000: 0x808002, 0x78000000: 0x2, 0x88000000: 0x800200, 0x98000000: 0x8200, 0xa8000000: 0x808000, 0xb8000000: 0x800202, 0xc8000000: 0x800002, 0xd8000000: 0x8002, 0xe8000000: 0x202, 0xf8000000: 0x800000, 0x1: 0x8000, 0x10000001: 0x2, 0x20000001: 0x808200, 0x30000001: 0x800000, 0x40000001: 0x808002, 0x50000001: 0x8200, 0x60000001: 0x200, 0x70000001: 0x800202, 0x80000001: 0x808202, 0x90000001: 0x808000, 0xa0000001: 0x800002, 0xb0000001: 0x8202, 0xc0000001: 0x202, 0xd0000001: 0x800200, 0xe0000001: 0x8002, 0xf0000001: 0x0, 0x8000001: 0x808202, 0x18000001: 0x808000, 0x28000001: 0x800000, 0x38000001: 0x200, 0x48000001: 0x8000, 0x58000001: 0x800002, 0x68000001: 0x2, 0x78000001: 0x8202, 0x88000001: 0x8002, 0x98000001: 0x800202, 0xa8000001: 0x202, 0xb8000001: 0x808200, 0xc8000001: 0x800200, 0xd8000001: 0x0, 0xe8000001: 0x8200, 0xf8000001: 0x808002 }, { 0x0: 0x40084010, 0x1000000: 0x4000, 0x2000000: 0x80000, 0x3000000: 0x40080010, 0x4000000: 0x40000010, 0x5000000: 0x40084000, 0x6000000: 0x40004000, 0x7000000: 0x10, 0x8000000: 0x84000, 0x9000000: 0x40004010, 0xa000000: 0x40000000, 0xb000000: 0x84010, 0xc000000: 0x80010, 0xd000000: 0x0, 0xe000000: 0x4010, 0xf000000: 0x40080000, 0x800000: 0x40004000, 0x1800000: 0x84010, 0x2800000: 0x10, 0x3800000: 0x40004010, 0x4800000: 0x40084010, 0x5800000: 0x40000000, 0x6800000: 0x80000, 0x7800000: 0x40080010, 0x8800000: 0x80010, 0x9800000: 0x0, 0xa800000: 0x4000, 0xb800000: 0x40080000, 0xc800000: 0x40000010, 0xd800000: 0x84000, 0xe800000: 0x40084000, 0xf800000: 0x4010, 0x10000000: 0x0, 0x11000000: 0x40080010, 0x12000000: 0x40004010, 0x13000000: 0x40084000, 0x14000000: 0x40080000, 0x15000000: 0x10, 0x16000000: 0x84010, 0x17000000: 0x4000, 0x18000000: 0x4010, 0x19000000: 0x80000, 0x1a000000: 0x80010, 0x1b000000: 0x40000010, 0x1c000000: 0x84000, 0x1d000000: 0x40004000, 0x1e000000: 0x40000000, 0x1f000000: 0x40084010, 0x10800000: 0x84010, 0x11800000: 0x80000, 0x12800000: 0x40080000, 0x13800000: 0x4000, 0x14800000: 0x40004000, 0x15800000: 0x40084010, 0x16800000: 0x10, 0x17800000: 0x40000000, 0x18800000: 0x40084000, 0x19800000: 0x40000010, 0x1a800000: 0x40004010, 0x1b800000: 0x80010, 0x1c800000: 0x0, 0x1d800000: 0x4010, 0x1e800000: 0x40080010, 0x1f800000: 0x84000 }, { 0x0: 0x104, 0x100000: 0x0, 0x200000: 0x4000100, 0x300000: 0x10104, 0x400000: 0x10004, 0x500000: 0x4000004, 0x600000: 0x4010104, 0x700000: 0x4010000, 0x800000: 0x4000000, 0x900000: 0x4010100, 0xa00000: 0x10100, 0xb00000: 0x4010004, 0xc00000: 0x4000104, 0xd00000: 0x10000, 0xe00000: 0x4, 0xf00000: 0x100, 0x80000: 0x4010100, 0x180000: 0x4010004, 0x280000: 0x0, 0x380000: 0x4000100, 0x480000: 0x4000004, 0x580000: 0x10000, 0x680000: 0x10004, 0x780000: 0x104, 0x880000: 0x4, 0x980000: 0x100, 0xa80000: 0x4010000, 0xb80000: 0x10104, 0xc80000: 0x10100, 0xd80000: 0x4000104, 0xe80000: 0x4010104, 0xf80000: 0x4000000, 0x1000000: 0x4010100, 0x1100000: 0x10004, 0x1200000: 0x10000, 0x1300000: 0x4000100, 0x1400000: 0x100, 0x1500000: 0x4010104, 0x1600000: 0x4000004, 0x1700000: 0x0, 0x1800000: 0x4000104, 0x1900000: 0x4000000, 0x1a00000: 0x4, 0x1b00000: 0x10100, 0x1c00000: 0x4010000, 0x1d00000: 0x104, 0x1e00000: 0x10104, 0x1f00000: 0x4010004, 0x1080000: 0x4000000, 0x1180000: 0x104, 0x1280000: 0x4010100, 0x1380000: 0x0, 0x1480000: 0x10004, 0x1580000: 0x4000100, 0x1680000: 0x100, 0x1780000: 0x4010004, 0x1880000: 0x10000, 0x1980000: 0x4010104, 0x1a80000: 0x10104, 0x1b80000: 0x4000004, 0x1c80000: 0x4000104, 0x1d80000: 0x4010000, 0x1e80000: 0x4, 0x1f80000: 0x10100 }, { 0x0: 0x80401000, 0x10000: 0x80001040, 0x20000: 0x401040, 0x30000: 0x80400000, 0x40000: 0x0, 0x50000: 0x401000, 0x60000: 0x80000040, 0x70000: 0x400040, 0x80000: 0x80000000, 0x90000: 0x400000, 0xa0000: 0x40, 0xb0000: 0x80001000, 0xc0000: 0x80400040, 0xd0000: 0x1040, 0xe0000: 0x1000, 0xf0000: 0x80401040, 0x8000: 0x80001040, 0x18000: 0x40, 0x28000: 0x80400040, 0x38000: 0x80001000, 0x48000: 0x401000, 0x58000: 0x80401040, 0x68000: 0x0, 0x78000: 0x80400000, 0x88000: 0x1000, 0x98000: 0x80401000, 0xa8000: 0x400000, 0xb8000: 0x1040, 0xc8000: 0x80000000, 0xd8000: 0x400040, 0xe8000: 0x401040, 0xf8000: 0x80000040, 0x100000: 0x400040, 0x110000: 0x401000, 0x120000: 0x80000040, 0x130000: 0x0, 0x140000: 0x1040, 0x150000: 0x80400040, 0x160000: 0x80401000, 0x170000: 0x80001040, 0x180000: 0x80401040, 0x190000: 0x80000000, 0x1a0000: 0x80400000, 0x1b0000: 0x401040, 0x1c0000: 0x80001000, 0x1d0000: 0x400000, 0x1e0000: 0x40, 0x1f0000: 0x1000, 0x108000: 0x80400000, 0x118000: 0x80401040, 0x128000: 0x0, 0x138000: 0x401000, 0x148000: 0x400040, 0x158000: 0x80000000, 0x168000: 0x80001040, 0x178000: 0x40, 0x188000: 0x80000040, 0x198000: 0x1000, 0x1a8000: 0x80001000, 0x1b8000: 0x80400040, 0x1c8000: 0x1040, 0x1d8000: 0x80401000, 0x1e8000: 0x400000, 0x1f8000: 0x401040 }, { 0x0: 0x80, 0x1000: 0x1040000, 0x2000: 0x40000, 0x3000: 0x20000000, 0x4000: 0x20040080, 0x5000: 0x1000080, 0x6000: 0x21000080, 0x7000: 0x40080, 0x8000: 0x1000000, 0x9000: 0x20040000, 0xa000: 0x20000080, 0xb000: 0x21040080, 0xc000: 0x21040000, 0xd000: 0x0, 0xe000: 0x1040080, 0xf000: 0x21000000, 0x800: 0x1040080, 0x1800: 0x21000080, 0x2800: 0x80, 0x3800: 0x1040000, 0x4800: 0x40000, 0x5800: 0x20040080, 0x6800: 0x21040000, 0x7800: 0x20000000, 0x8800: 0x20040000, 0x9800: 0x0, 0xa800: 0x21040080, 0xb800: 0x1000080, 0xc800: 0x20000080, 0xd800: 0x21000000, 0xe800: 0x1000000, 0xf800: 0x40080, 0x10000: 0x40000, 0x11000: 0x80, 0x12000: 0x20000000, 0x13000: 0x21000080, 0x14000: 0x1000080, 0x15000: 0x21040000, 0x16000: 0x20040080, 0x17000: 0x1000000, 0x18000: 0x21040080, 0x19000: 0x21000000, 0x1a000: 0x1040000, 0x1b000: 0x20040000, 0x1c000: 0x40080, 0x1d000: 0x20000080, 0x1e000: 0x0, 0x1f000: 0x1040080, 0x10800: 0x21000080, 0x11800: 0x1000000, 0x12800: 0x1040000, 0x13800: 0x20040080, 0x14800: 0x20000000, 0x15800: 0x1040080, 0x16800: 0x80, 0x17800: 0x21040000, 0x18800: 0x40080, 0x19800: 0x21040080, 0x1a800: 0x0, 0x1b800: 0x21000000, 0x1c800: 0x1000080, 0x1d800: 0x40000, 0x1e800: 0x20040000, 0x1f800: 0x20000080 }, { 0x0: 0x10000008, 0x100: 0x2000, 0x200: 0x10200000, 0x300: 0x10202008, 0x400: 0x10002000, 0x500: 0x200000, 0x600: 0x200008, 0x700: 0x10000000, 0x800: 0x0, 0x900: 0x10002008, 0xa00: 0x202000, 0xb00: 0x8, 0xc00: 0x10200008, 0xd00: 0x202008, 0xe00: 0x2008, 0xf00: 0x10202000, 0x80: 0x10200000, 0x180: 0x10202008, 0x280: 0x8, 0x380: 0x200000, 0x480: 0x202008, 0x580: 0x10000008, 0x680: 0x10002000, 0x780: 0x2008, 0x880: 0x200008, 0x980: 0x2000, 0xa80: 0x10002008, 0xb80: 0x10200008, 0xc80: 0x0, 0xd80: 0x10202000, 0xe80: 0x202000, 0xf80: 0x10000000, 0x1000: 0x10002000, 0x1100: 0x10200008, 0x1200: 0x10202008, 0x1300: 0x2008, 0x1400: 0x200000, 0x1500: 0x10000000, 0x1600: 0x10000008, 0x1700: 0x202000, 0x1800: 0x202008, 0x1900: 0x0, 0x1a00: 0x8, 0x1b00: 0x10200000, 0x1c00: 0x2000, 0x1d00: 0x10002008, 0x1e00: 0x10202000, 0x1f00: 0x200008, 0x1080: 0x8, 0x1180: 0x202000, 0x1280: 0x200000, 0x1380: 0x10000008, 0x1480: 0x10002000, 0x1580: 0x2008, 0x1680: 0x10202008, 0x1780: 0x10200000, 0x1880: 0x10202000, 0x1980: 0x10200008, 0x1a80: 0x2000, 0x1b80: 0x202008, 0x1c80: 0x200008, 0x1d80: 0x0, 0x1e80: 0x10000000, 0x1f80: 0x10002008 }, { 0x0: 0x100000, 0x10: 0x2000401, 0x20: 0x400, 0x30: 0x100401, 0x40: 0x2100401, 0x50: 0x0, 0x60: 0x1, 0x70: 0x2100001, 0x80: 0x2000400, 0x90: 0x100001, 0xa0: 0x2000001, 0xb0: 0x2100400, 0xc0: 0x2100000, 0xd0: 0x401, 0xe0: 0x100400, 0xf0: 0x2000000, 0x8: 0x2100001, 0x18: 0x0, 0x28: 0x2000401, 0x38: 0x2100400, 0x48: 0x100000, 0x58: 0x2000001, 0x68: 0x2000000, 0x78: 0x401, 0x88: 0x100401, 0x98: 0x2000400, 0xa8: 0x2100000, 0xb8: 0x100001, 0xc8: 0x400, 0xd8: 0x2100401, 0xe8: 0x1, 0xf8: 0x100400, 0x100: 0x2000000, 0x110: 0x100000, 0x120: 0x2000401, 0x130: 0x2100001, 0x140: 0x100001, 0x150: 0x2000400, 0x160: 0x2100400, 0x170: 0x100401, 0x180: 0x401, 0x190: 0x2100401, 0x1a0: 0x100400, 0x1b0: 0x1, 0x1c0: 0x0, 0x1d0: 0x2100000, 0x1e0: 0x2000001, 0x1f0: 0x400, 0x108: 0x100400, 0x118: 0x2000401, 0x128: 0x2100001, 0x138: 0x1, 0x148: 0x2000000, 0x158: 0x100000, 0x168: 0x401, 0x178: 0x2100400, 0x188: 0x2000001, 0x198: 0x2100000, 0x1a8: 0x0, 0x1b8: 0x2100401, 0x1c8: 0x100401, 0x1d8: 0x400, 0x1e8: 0x2000400, 0x1f8: 0x100001 }, { 0x0: 0x8000820, 0x1: 0x20000, 0x2: 0x8000000, 0x3: 0x20, 0x4: 0x20020, 0x5: 0x8020820, 0x6: 0x8020800, 0x7: 0x800, 0x8: 0x8020000, 0x9: 0x8000800, 0xa: 0x20800, 0xb: 0x8020020, 0xc: 0x820, 0xd: 0x0, 0xe: 0x8000020, 0xf: 0x20820, 0x80000000: 0x800, 0x80000001: 0x8020820, 0x80000002: 0x8000820, 0x80000003: 0x8000000, 0x80000004: 0x8020000, 0x80000005: 0x20800, 0x80000006: 0x20820, 0x80000007: 0x20, 0x80000008: 0x8000020, 0x80000009: 0x820, 0x8000000a: 0x20020, 0x8000000b: 0x8020800, 0x8000000c: 0x0, 0x8000000d: 0x8020020, 0x8000000e: 0x8000800, 0x8000000f: 0x20000, 0x10: 0x20820, 0x11: 0x8020800, 0x12: 0x20, 0x13: 0x800, 0x14: 0x8000800, 0x15: 0x8000020, 0x16: 0x8020020, 0x17: 0x20000, 0x18: 0x0, 0x19: 0x20020, 0x1a: 0x8020000, 0x1b: 0x8000820, 0x1c: 0x8020820, 0x1d: 0x20800, 0x1e: 0x820, 0x1f: 0x8000000, 0x80000010: 0x20000, 0x80000011: 0x800, 0x80000012: 0x8020020, 0x80000013: 0x20820, 0x80000014: 0x20, 0x80000015: 0x8020000, 0x80000016: 0x8000000, 0x80000017: 0x8000820, 0x80000018: 0x8020820, 0x80000019: 0x8000020, 0x8000001a: 0x8000800, 0x8000001b: 0x0, 0x8000001c: 0x20800, 0x8000001d: 0x820, 0x8000001e: 0x20020, 0x8000001f: 0x8020800 } ]; // Masks that select the SBOX input var SBOX_MASK = [ 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f ]; /** * DES block cipher algorithm. */ var DES = C_algo.DES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Select 56 bits according to PC1 var keyBits = []; for (var i = 0; i < 56; i++) { var keyBitPos = PC1[i] - 1; keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; } // Assemble 16 subkeys var subKeys = this._subKeys = []; for (var nSubKey = 0; nSubKey < 16; nSubKey++) { // Create subkey var subKey = subKeys[nSubKey] = []; // Shortcut var bitShift = BIT_SHIFTS[nSubKey]; // Select 48 bits according to PC2 for (var i = 0; i < 24; i++) { // Select from the left 28 key bits subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); // Select from the right 28 key bits subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); } // Since each subkey is applied to an expanded 32-bit input, // the subkey can be broken into 8 values scaled to 32-bits, // which allows the key to be used without expansion subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); for (var i = 1; i < 7; i++) { subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); } subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); } // Compute inverse subkeys var invSubKeys = this._invSubKeys = []; for (var i = 0; i < 16; i++) { invSubKeys[i] = subKeys[15 - i]; } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._subKeys); }, decryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._invSubKeys); }, _doCryptBlock: function (M, offset, subKeys) { // Get input this._lBlock = M[offset]; this._rBlock = M[offset + 1]; // Initial permutation exchangeLR.call(this, 4, 0x0f0f0f0f); exchangeLR.call(this, 16, 0x0000ffff); exchangeRL.call(this, 2, 0x33333333); exchangeRL.call(this, 8, 0x00ff00ff); exchangeLR.call(this, 1, 0x55555555); // Rounds for (var round = 0; round < 16; round++) { // Shortcuts var subKey = subKeys[round]; var lBlock = this._lBlock; var rBlock = this._rBlock; // Feistel function var f = 0; for (var i = 0; i < 8; i++) { f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; } this._lBlock = rBlock; this._rBlock = lBlock ^ f; } // Undo swap from last round var t = this._lBlock; this._lBlock = this._rBlock; this._rBlock = t; // Final permutation exchangeLR.call(this, 1, 0x55555555); exchangeRL.call(this, 8, 0x00ff00ff); exchangeRL.call(this, 2, 0x33333333); exchangeLR.call(this, 16, 0x0000ffff); exchangeLR.call(this, 4, 0x0f0f0f0f); // Set output M[offset] = this._lBlock; M[offset + 1] = this._rBlock; }, keySize: 64/32, ivSize: 64/32, blockSize: 64/32 }); // Swap bits across the left and right words function exchangeLR(offset, mask) { var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; this._rBlock ^= t; this._lBlock ^= t << offset; } function exchangeRL(offset, mask) { var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; this._lBlock ^= t; this._rBlock ^= t << offset; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); */ C.DES = BlockCipher._createHelper(DES); /** * Triple-DES block cipher algorithm. */ var TripleDES = C_algo.TripleDES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Create DES instances this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2))); this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4))); this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6))); }, encryptBlock: function (M, offset) { this._des1.encryptBlock(M, offset); this._des2.decryptBlock(M, offset); this._des3.encryptBlock(M, offset); }, decryptBlock: function (M, offset) { this._des3.decryptBlock(M, offset); this._des2.encryptBlock(M, offset); this._des1.decryptBlock(M, offset); }, keySize: 192/32, ivSize: 64/32, blockSize: 64/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); */ C.TripleDES = BlockCipher._createHelper(TripleDES); }()); return CryptoJS.TripleDES; })); },{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],83:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var X32WordArray = C_lib.WordArray; /** * x64 namespace. */ var C_x64 = C.x64 = {}; /** * A 64-bit word. */ var X64Word = C_x64.Word = Base.extend({ /** * Initializes a newly created 64-bit word. * * @param {number} high The high 32 bits. * @param {number} low The low 32 bits. * * @example * * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); */ init: function (high, low) { this.high = high; this.low = low; } /** * Bitwise NOTs this word. * * @return {X64Word} A new x64-Word object after negating. * * @example * * var negated = x64Word.not(); */ // not: function () { // var high = ~this.high; // var low = ~this.low; // return X64Word.create(high, low); // }, /** * Bitwise ANDs this word with the passed word. * * @param {X64Word} word The x64-Word to AND with this word. * * @return {X64Word} A new x64-Word object after ANDing. * * @example * * var anded = x64Word.and(anotherX64Word); */ // and: function (word) { // var high = this.high & word.high; // var low = this.low & word.low; // return X64Word.create(high, low); // }, /** * Bitwise ORs this word with the passed word. * * @param {X64Word} word The x64-Word to OR with this word. * * @return {X64Word} A new x64-Word object after ORing. * * @example * * var ored = x64Word.or(anotherX64Word); */ // or: function (word) { // var high = this.high | word.high; // var low = this.low | word.low; // return X64Word.create(high, low); // }, /** * Bitwise XORs this word with the passed word. * * @param {X64Word} word The x64-Word to XOR with this word. * * @return {X64Word} A new x64-Word object after XORing. * * @example * * var xored = x64Word.xor(anotherX64Word); */ // xor: function (word) { // var high = this.high ^ word.high; // var low = this.low ^ word.low; // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the left. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftL(25); */ // shiftL: function (n) { // if (n < 32) { // var high = (this.high << n) | (this.low >>> (32 - n)); // var low = this.low << n; // } else { // var high = this.low << (n - 32); // var low = 0; // } // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the right. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftR(7); */ // shiftR: function (n) { // if (n < 32) { // var low = (this.low >>> n) | (this.high << (32 - n)); // var high = this.high >>> n; // } else { // var low = this.high >>> (n - 32); // var high = 0; // } // return X64Word.create(high, low); // }, /** * Rotates this word n bits to the left. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotL(25); */ // rotL: function (n) { // return this.shiftL(n).or(this.shiftR(64 - n)); // }, /** * Rotates this word n bits to the right. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotR(7); */ // rotR: function (n) { // return this.shiftR(n).or(this.shiftL(64 - n)); // }, /** * Adds this word with the passed word. * * @param {X64Word} word The x64-Word to add with this word. * * @return {X64Word} A new x64-Word object after adding. * * @example * * var added = x64Word.add(anotherX64Word); */ // add: function (word) { // var low = (this.low + word.low) | 0; // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; // var high = (this.high + word.high + carry) | 0; // return X64Word.create(high, low); // } }); /** * An array of 64-bit words. * * @property {Array} words The array of CryptoJS.x64.Word objects. * @property {number} sigBytes The number of significant bytes in this word array. */ var X64WordArray = C_x64.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.x64.WordArray.create(); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ]); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ], 10); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 8; } }, /** * Converts this 64-bit word array to a 32-bit word array. * * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. * * @example * * var x32WordArray = x64WordArray.toX32(); */ toX32: function () { // Shortcuts var x64Words = this.words; var x64WordsLength = x64Words.length; // Convert var x32Words = []; for (var i = 0; i < x64WordsLength; i++) { var x64Word = x64Words[i]; x32Words.push(x64Word.high); x32Words.push(x64Word.low); } return X32WordArray.create(x32Words, this.sigBytes); }, /** * Creates a copy of this word array. * * @return {X64WordArray} The clone. * * @example * * var clone = x64WordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); // Clone "words" array var words = clone.words = this.words.slice(0); // Clone each X64Word object var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { words[i] = words[i].clone(); } return clone; } }); }()); return CryptoJS; })); },{"./core":52}],84:[function(require,module,exports){ /*! https://mths.be/utf8js v2.1.2 by @mathias */ ;(function(root) { // Detect free variables `exports` var freeExports = typeof exports == 'object' && exports; // Detect free variable `module` var freeModule = typeof module == 'object' && module && module.exports == freeExports && module; // Detect free variable `global`, from Node.js or Browserified code, // and use it as `root` var freeGlobal = typeof global == 'object' && global; if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { root = freeGlobal; } /*--------------------------------------------------------------------------*/ var stringFromCharCode = String.fromCharCode; // Taken from https://mths.be/punycode function ucs2decode(string) { var output = []; var counter = 0; var length = string.length; var value; var extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; } // Taken from https://mths.be/punycode function ucs2encode(array) { var length = array.length; var index = -1; var value; var output = ''; while (++index < length) { value = array[index]; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); } return output; } function checkScalarValue(codePoint) { if (codePoint >= 0xD800 && codePoint <= 0xDFFF) { throw Error( 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() + ' is not a scalar value' ); } } /*--------------------------------------------------------------------------*/ function createByte(codePoint, shift) { return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80); } function encodeCodePoint(codePoint) { if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence return stringFromCharCode(codePoint); } var symbol = ''; if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0); } else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence checkScalarValue(codePoint); symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0); symbol += createByte(codePoint, 6); } else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0); symbol += createByte(codePoint, 12); symbol += createByte(codePoint, 6); } symbol += stringFromCharCode((codePoint & 0x3F) | 0x80); return symbol; } function utf8encode(string) { var codePoints = ucs2decode(string); var length = codePoints.length; var index = -1; var codePoint; var byteString = ''; while (++index < length) { codePoint = codePoints[index]; byteString += encodeCodePoint(codePoint); } return byteString; } /*--------------------------------------------------------------------------*/ function readContinuationByte() { if (byteIndex >= byteCount) { throw Error('Invalid byte index'); } var continuationByte = byteArray[byteIndex] & 0xFF; byteIndex++; if ((continuationByte & 0xC0) == 0x80) { return continuationByte & 0x3F; } // If we end up here, it’s not a continuation byte throw Error('Invalid continuation byte'); } function decodeSymbol() { var byte1; var byte2; var byte3; var byte4; var codePoint; if (byteIndex > byteCount) { throw Error('Invalid byte index'); } if (byteIndex == byteCount) { return false; } // Read first byte byte1 = byteArray[byteIndex] & 0xFF; byteIndex++; // 1-byte sequence (no continuation bytes) if ((byte1 & 0x80) == 0) { return byte1; } // 2-byte sequence if ((byte1 & 0xE0) == 0xC0) { byte2 = readContinuationByte(); codePoint = ((byte1 & 0x1F) << 6) | byte2; if (codePoint >= 0x80) { return codePoint; } else { throw Error('Invalid continuation byte'); } } // 3-byte sequence (may include unpaired surrogates) if ((byte1 & 0xF0) == 0xE0) { byte2 = readContinuationByte(); byte3 = readContinuationByte(); codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3; if (codePoint >= 0x0800) { checkScalarValue(codePoint); return codePoint; } else { throw Error('Invalid continuation byte'); } } // 4-byte sequence if ((byte1 & 0xF8) == 0xF0) { byte2 = readContinuationByte(); byte3 = readContinuationByte(); byte4 = readContinuationByte(); codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) | (byte3 << 0x06) | byte4; if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) { return codePoint; } } throw Error('Invalid UTF-8 detected'); } var byteArray; var byteCount; var byteIndex; function utf8decode(byteString) { byteArray = ucs2decode(byteString); byteCount = byteArray.length; byteIndex = 0; var codePoints = []; var tmp; while ((tmp = decodeSymbol()) !== false) { codePoints.push(tmp); } return ucs2encode(codePoints); } /*--------------------------------------------------------------------------*/ var utf8 = { 'version': '2.1.2', 'encode': utf8encode, 'decode': utf8decode }; // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( typeof define == 'function' && typeof define.amd == 'object' && define.amd ) { define(function() { return utf8; }); } else if (freeExports && !freeExports.nodeType) { if (freeModule) { // in Node.js or RingoJS v0.8.0+ freeModule.exports = utf8; } else { // in Narwhal or RingoJS v0.7.0- var object = {}; var hasOwnProperty = object.hasOwnProperty; for (var key in utf8) { hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]); } } } else { // in Rhino or a web browser root.utf8 = utf8; } }(this)); },{}],85:[function(require,module,exports){ module.exports = XMLHttpRequest; },{}],"bignumber.js":[function(require,module,exports){ /*! bignumber.js v4.0.0 https://github.com/MikeMcl/bignumber.js/LICENCE */ ;(function (globalObj) { 'use strict'; /* bignumber.js v4.0.0 A JavaScript library for arbitrary-precision arithmetic. https://github.com/MikeMcl/bignumber.js Copyright (c) 2017 Michael Mclaughlin <[email protected]> MIT Expat Licence */ var BigNumber, isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, mathceil = Math.ceil, mathfloor = Math.floor, notBool = ' not a boolean or binary digit', roundingMode = 'rounding mode', tooManyDigits = 'number type has more than 15 significant digits', ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_', BASE = 1e14, LOG_BASE = 14, MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 // MAX_INT32 = 0x7fffffff, // 2^31 - 1 POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], SQRT_BASE = 1e7, /* * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an * exception is thrown (if ERRORS is true). */ MAX = 1E9; // 0 to MAX_INT32 /* * Create and return a BigNumber constructor. */ function constructorFactory(config) { var div, parseNumeric, // id tracks the caller function, so its name can be included in error messages. id = 0, P = BigNumber.prototype, ONE = new BigNumber(1), /********************************* EDITABLE DEFAULTS **********************************/ /* * The default values below must be integers within the inclusive ranges stated. * The values can also be changed at run-time using BigNumber.config. */ // The maximum number of decimal places for operations involving division. DECIMAL_PLACES = 20, // 0 to MAX /* * The rounding mode used when rounding to the above decimal places, and when using * toExponential, toFixed, toFormat and toPrecision, and round (default value). * UP 0 Away from zero. * DOWN 1 Towards zero. * CEIL 2 Towards +Infinity. * FLOOR 3 Towards -Infinity. * HALF_UP 4 Towards nearest neighbour. If equidistant, up. * HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. * HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. * HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. */ ROUNDING_MODE = 4, // 0 to 8 // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] // The exponent value at and beneath which toString returns exponential notation. // Number type: -7 TO_EXP_NEG = -7, // 0 to -MAX // The exponent value at and above which toString returns exponential notation. // Number type: 21 TO_EXP_POS = 21, // 0 to MAX // RANGE : [MIN_EXP, MAX_EXP] // The minimum exponent value, beneath which underflow to zero occurs. // Number type: -324 (5e-324) MIN_EXP = -1e7, // -1 to -MAX // The maximum exponent value, above which overflow to Infinity occurs. // Number type: 308 (1.7976931348623157e+308) // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. MAX_EXP = 1e7, // 1 to MAX // Whether BigNumber Errors are ever thrown. ERRORS = true, // true or false // Change to intValidatorNoErrors if ERRORS is false. isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors // Whether to use cryptographically-secure random number generation, if available. CRYPTO = false, // true or false /* * The modulo mode used when calculating the modulus: a mod n. * The quotient (q = a / n) is calculated according to the corresponding rounding mode. * The remainder (r) is calculated as: r = a - n * q. * * UP 0 The remainder is positive if the dividend is negative, else is negative. * DOWN 1 The remainder has the same sign as the dividend. * This modulo mode is commonly known as 'truncated division' and is * equivalent to (a % n) in JavaScript. * FLOOR 3 The remainder has the same sign as the divisor (Python %). * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. * EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). * The remainder is always positive. * * The truncated division, floored division, Euclidian division and IEEE 754 remainder * modes are commonly used for the modulus operation. * Although the other rounding modes can also be used, they may not give useful results. */ MODULO_MODE = 1, // 0 to 9 // The maximum number of significant digits of the result of the toPower operation. // If POW_PRECISION is 0, there will be unlimited significant digits. POW_PRECISION = 0, // 0 to MAX // The format specification used by the BigNumber.prototype.toFormat method. FORMAT = { decimalSeparator: '.', groupSeparator: ',', groupSize: 3, secondaryGroupSize: 0, fractionGroupSeparator: '\xA0', // non-breaking space fractionGroupSize: 0 }; /******************************************************************************************/ // CONSTRUCTOR /* * The BigNumber constructor and exported function. * Create and return a new instance of a BigNumber object. * * n {number|string|BigNumber} A numeric value. * [b] {number} The base of n. Integer, 2 to 64 inclusive. */ function BigNumber( n, b ) { var c, e, i, num, len, str, x = this; // Enable constructor usage without new. if ( !( x instanceof BigNumber ) ) { // 'BigNumber() constructor call without new: {n}' if (ERRORS) raise( 26, 'constructor call without new', n ); return new BigNumber( n, b ); } // 'new BigNumber() base not an integer: {b}' // 'new BigNumber() base out of range: {b}' if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) { // Duplicate. if ( n instanceof BigNumber ) { x.s = n.s; x.e = n.e; x.c = ( n = n.c ) ? n.slice() : n; id = 0; return; } if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) { x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1; // Fast path for integers. if ( n === ~~n ) { for ( e = 0, i = n; i >= 10; i /= 10, e++ ); x.e = e; x.c = [n]; id = 0; return; } str = n + ''; } else { if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num ); x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; } } else { b = b | 0; str = n + ''; // Ensure return value is rounded to DECIMAL_PLACES as with other bases. // Allow exponential notation to be used with base 10 argument. if ( b == 10 ) { x = new BigNumber( n instanceof BigNumber ? n : str ); return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE ); } // Avoid potential interpretation of Infinity and NaN as base 44+ values. // Any number in exponential form will fail due to the [Ee][+-]. if ( ( num = typeof n == 'number' ) && n * 0 != 0 || !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) + '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) { return parseNumeric( x, str, num, b ); } if (num) { x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1; if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) { // 'new BigNumber() number type has more than 15 significant digits: {n}' raise( id, tooManyDigits, n ); } // Prevent later check for length on converted number. num = false; } else { x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; } str = convertBase( str, 10, b, x.s ); } // Decimal point? if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' ); // Exponential form? if ( ( i = str.search( /e/i ) ) > 0 ) { // Determine exponent. if ( e < 0 ) e = i; e += +str.slice( i + 1 ); str = str.substring( 0, i ); } else if ( e < 0 ) { // Integer. e = str.length; } // Determine leading zeros. for ( i = 0; str.charCodeAt(i) === 48; i++ ); // Determine trailing zeros. for ( len = str.length; str.charCodeAt(--len) === 48; ); str = str.slice( i, len + 1 ); if (str) { len = str.length; // Disallow numbers with over 15 significant digits if number type. // 'new BigNumber() number type has more than 15 significant digits: {n}' if ( num && ERRORS && len > 15 && ( n > MAX_SAFE_INTEGER || n !== mathfloor(n) ) ) { raise( id, tooManyDigits, x.s * n ); } e = e - i - 1; // Overflow? if ( e > MAX_EXP ) { // Infinity. x.c = x.e = null; // Underflow? } else if ( e < MIN_EXP ) { // Zero. x.c = [ x.e = 0 ]; } else { x.e = e; x.c = []; // Transform base // e is the base 10 exponent. // i is where to slice str to get the first element of the coefficient array. i = ( e + 1 ) % LOG_BASE; if ( e < 0 ) i += LOG_BASE; if ( i < len ) { if (i) x.c.push( +str.slice( 0, i ) ); for ( len -= LOG_BASE; i < len; ) { x.c.push( +str.slice( i, i += LOG_BASE ) ); } str = str.slice(i); i = LOG_BASE - str.length; } else { i -= len; } for ( ; i--; str += '0' ); x.c.push( +str ); } } else { // Zero. x.c = [ x.e = 0 ]; } id = 0; } // CONSTRUCTOR PROPERTIES BigNumber.another = constructorFactory; BigNumber.ROUND_UP = 0; BigNumber.ROUND_DOWN = 1; BigNumber.ROUND_CEIL = 2; BigNumber.ROUND_FLOOR = 3; BigNumber.ROUND_HALF_UP = 4; BigNumber.ROUND_HALF_DOWN = 5; BigNumber.ROUND_HALF_EVEN = 6; BigNumber.ROUND_HALF_CEIL = 7; BigNumber.ROUND_HALF_FLOOR = 8; BigNumber.EUCLID = 9; /* * Configure infrequently-changing library-wide settings. * * Accept an object or an argument list, with one or many of the following properties or * parameters respectively: * * DECIMAL_PLACES {number} Integer, 0 to MAX inclusive * ROUNDING_MODE {number} Integer, 0 to 8 inclusive * EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or * [integer -MAX to 0 incl., 0 to MAX incl.] * RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or * [integer -MAX to -1 incl., integer 1 to MAX incl.] * ERRORS {boolean|number} true, false, 1 or 0 * CRYPTO {boolean|number} true, false, 1 or 0 * MODULO_MODE {number} 0 to 9 inclusive * POW_PRECISION {number} 0 to MAX inclusive * FORMAT {object} See BigNumber.prototype.toFormat * decimalSeparator {string} * groupSeparator {string} * groupSize {number} * secondaryGroupSize {number} * fractionGroupSeparator {string} * fractionGroupSize {number} * * (The values assigned to the above FORMAT object properties are not checked for validity.) * * E.g. * BigNumber.config(20, 4) is equivalent to * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) * * Ignore properties/parameters set to null or undefined. * Return an object with the properties current values. */ BigNumber.config = BigNumber.set = function () { var v, p, i = 0, r = {}, a = arguments, o = a[0], has = o && typeof o == 'object' ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; } : function () { if ( a.length > i ) return ( v = a[i++] ) != null; }; // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. // 'config() DECIMAL_PLACES not an integer: {v}' // 'config() DECIMAL_PLACES out of range: {v}' if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) { DECIMAL_PLACES = v | 0; } r[p] = DECIMAL_PLACES; // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. // 'config() ROUNDING_MODE not an integer: {v}' // 'config() ROUNDING_MODE out of range: {v}' if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) { ROUNDING_MODE = v | 0; } r[p] = ROUNDING_MODE; // EXPONENTIAL_AT {number|number[]} // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive]. // 'config() EXPONENTIAL_AT not an integer: {v}' // 'config() EXPONENTIAL_AT out of range: {v}' if ( has( p = 'EXPONENTIAL_AT' ) ) { if ( isArray(v) ) { if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) { TO_EXP_NEG = v[0] | 0; TO_EXP_POS = v[1] | 0; } } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) { TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 ); } } r[p] = [ TO_EXP_NEG, TO_EXP_POS ]; // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. // 'config() RANGE not an integer: {v}' // 'config() RANGE cannot be zero: {v}' // 'config() RANGE out of range: {v}' if ( has( p = 'RANGE' ) ) { if ( isArray(v) ) { if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) { MIN_EXP = v[0] | 0; MAX_EXP = v[1] | 0; } } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) { if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 ); else if (ERRORS) raise( 2, p + ' cannot be zero', v ); } } r[p] = [ MIN_EXP, MAX_EXP ]; // ERRORS {boolean|number} true, false, 1 or 0. // 'config() ERRORS not a boolean or binary digit: {v}' if ( has( p = 'ERRORS' ) ) { if ( v === !!v || v === 1 || v === 0 ) { id = 0; isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors; } else if (ERRORS) { raise( 2, p + notBool, v ); } } r[p] = ERRORS; // CRYPTO {boolean|number} true, false, 1 or 0. // 'config() CRYPTO not a boolean or binary digit: {v}' // 'config() crypto unavailable: {crypto}' if ( has( p = 'CRYPTO' ) ) { if ( v === true || v === false || v === 1 || v === 0 ) { if (v) { v = typeof crypto == 'undefined'; if ( !v && crypto && (crypto.getRandomValues || crypto.randomBytes)) { CRYPTO = true; } else if (ERRORS) { raise( 2, 'crypto unavailable', v ? void 0 : crypto ); } else { CRYPTO = false; } } else { CRYPTO = false; } } else if (ERRORS) { raise( 2, p + notBool, v ); } } r[p] = CRYPTO; // MODULO_MODE {number} Integer, 0 to 9 inclusive. // 'config() MODULO_MODE not an integer: {v}' // 'config() MODULO_MODE out of range: {v}' if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) { MODULO_MODE = v | 0; } r[p] = MODULO_MODE; // POW_PRECISION {number} Integer, 0 to MAX inclusive. // 'config() POW_PRECISION not an integer: {v}' // 'config() POW_PRECISION out of range: {v}' if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) { POW_PRECISION = v | 0; } r[p] = POW_PRECISION; // FORMAT {object} // 'config() FORMAT not an object: {v}' if ( has( p = 'FORMAT' ) ) { if ( typeof v == 'object' ) { FORMAT = v; } else if (ERRORS) { raise( 2, p + ' not an object', v ); } } r[p] = FORMAT; return r; }; /* * Return a new BigNumber whose value is the maximum of the arguments. * * arguments {number|string|BigNumber} */ BigNumber.max = function () { return maxOrMin( arguments, P.lt ); }; /* * Return a new BigNumber whose value is the minimum of the arguments. * * arguments {number|string|BigNumber} */ BigNumber.min = function () { return maxOrMin( arguments, P.gt ); }; /* * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing * zeros are produced). * * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. * * 'random() decimal places not an integer: {dp}' * 'random() decimal places out of range: {dp}' * 'random() crypto unavailable: {crypto}' */ BigNumber.random = (function () { var pow2_53 = 0x20000000000000; // Return a 53 bit integer n, where 0 <= n < 9007199254740992. // Check if Math.random() produces more than 32 bits of randomness. // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. var random53bitInt = (Math.random() * pow2_53) & 0x1fffff ? function () { return mathfloor( Math.random() * pow2_53 ); } : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + (Math.random() * 0x800000 | 0); }; return function (dp) { var a, b, e, k, v, i = 0, c = [], rand = new BigNumber(ONE); dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0; k = mathceil( dp / LOG_BASE ); if (CRYPTO) { // Browsers supporting crypto.getRandomValues. if (crypto.getRandomValues) { a = crypto.getRandomValues( new Uint32Array( k *= 2 ) ); for ( ; i < k; ) { // 53 bits: // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) // 11111 11111111 11111111 11111111 11100000 00000000 00000000 // ((Math.pow(2, 32) - 1) >>> 11).toString(2) // 11111 11111111 11111111 // 0x20000 is 2^21. v = a[i] * 0x20000 + (a[i + 1] >>> 11); // Rejection sampling: // 0 <= v < 9007199254740992 // Probability that v >= 9e15, is // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 if ( v >= 9e15 ) { b = crypto.getRandomValues( new Uint32Array(2) ); a[i] = b[0]; a[i + 1] = b[1]; } else { // 0 <= v <= 8999999999999999 // 0 <= (v % 1e14) <= 99999999999999 c.push( v % 1e14 ); i += 2; } } i = k / 2; // Node.js supporting crypto.randomBytes. } else if (crypto.randomBytes) { // buffer a = crypto.randomBytes( k *= 7 ); for ( ; i < k; ) { // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 // 0x100000000 is 2^32, 0x1000000 is 2^24 // 11111 11111111 11111111 11111111 11111111 11111111 11111111 // 0 <= v < 9007199254740992 v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) + ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) + ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6]; if ( v >= 9e15 ) { crypto.randomBytes(7).copy( a, i ); } else { // 0 <= (v % 1e14) <= 99999999999999 c.push( v % 1e14 ); i += 7; } } i = k / 7; } else { CRYPTO = false; if (ERRORS) raise( 14, 'crypto unavailable', crypto ); } } // Use Math.random. if (!CRYPTO) { for ( ; i < k; ) { v = random53bitInt(); if ( v < 9e15 ) c[i++] = v % 1e14; } } k = c[--i]; dp %= LOG_BASE; // Convert trailing digits to zeros according to dp. if ( k && dp ) { v = POWS_TEN[LOG_BASE - dp]; c[i] = mathfloor( k / v ) * v; } // Remove trailing elements which are zero. for ( ; c[i] === 0; c.pop(), i-- ); // Zero? if ( i < 0 ) { c = [ e = 0 ]; } else { // Remove leading elements which are zero and adjust exponent accordingly. for ( e = -1 ; c[0] === 0; c.shift(), e -= LOG_BASE); // Count the digits of the first element of c to determine leading zeros, and... for ( i = 1, v = c[0]; v >= 10; v /= 10, i++); // adjust the exponent accordingly. if ( i < LOG_BASE ) e -= LOG_BASE - i; } rand.e = e; rand.c = c; return rand; }; })(); // PRIVATE FUNCTIONS // Convert a numeric string of baseIn to a numeric string of baseOut. function convertBase( str, baseOut, baseIn, sign ) { var d, e, k, r, x, xc, y, i = str.indexOf( '.' ), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; if ( baseIn < 37 ) str = str.toLowerCase(); // Non-integer. if ( i >= 0 ) { k = POW_PRECISION; // Unlimited precision. POW_PRECISION = 0; str = str.replace( '.', '' ); y = new BigNumber(baseIn); x = y.pow( str.length - i ); POW_PRECISION = k; // Convert str as if an integer, then restore the fraction part by dividing the // result by its base raised to a power. y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut ); y.e = y.c.length; } // Convert the number as integer. xc = toBaseOut( str, baseIn, baseOut ); e = k = xc.length; // Remove trailing zeros. for ( ; xc[--k] == 0; xc.pop() ); if ( !xc[0] ) return '0'; if ( i < 0 ) { --e; } else { x.c = xc; x.e = e; // sign is needed for correct rounding. x.s = sign; x = div( x, y, dp, rm, baseOut ); xc = x.c; r = x.r; e = x.e; } d = e + dp + 1; // The rounding digit, i.e. the digit to the right of the digit that may be rounded up. i = xc[d]; k = baseOut / 2; r = r || d < 0 || xc[d + 1] != null; r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) ) : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 || rm == ( x.s < 0 ? 8 : 7 ) ); if ( d < 1 || !xc[0] ) { // 1^-dp or 0. str = r ? toFixedPoint( '1', -dp ) : '0'; } else { xc.length = d; if (r) { // Rounding up may mean the previous digit has to be rounded up and so on. for ( --baseOut; ++xc[--d] > baseOut; ) { xc[d] = 0; if ( !d ) { ++e; xc.unshift(1); } } } // Determine trailing zeros. for ( k = xc.length; !xc[--k]; ); // E.g. [4, 11, 15] becomes 4bf. for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) ); str = toFixedPoint( str, e ); } // The caller will add the sign. return str; } // Perform division in the specified base. Called by div and convertBase. div = (function () { // Assume non-zero x and k. function multiply( x, k, base ) { var m, temp, xlo, xhi, carry = 0, i = x.length, klo = k % SQRT_BASE, khi = k / SQRT_BASE | 0; for ( x = x.slice(); i--; ) { xlo = x[i] % SQRT_BASE; xhi = x[i] / SQRT_BASE | 0; m = khi * xlo + xhi * klo; temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry; carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi; x[i] = temp % base; } if (carry) x.unshift(carry); return x; } function compare( a, b, aL, bL ) { var i, cmp; if ( aL != bL ) { cmp = aL > bL ? 1 : -1; } else { for ( i = cmp = 0; i < aL; i++ ) { if ( a[i] != b[i] ) { cmp = a[i] > b[i] ? 1 : -1; break; } } } return cmp; } function subtract( a, b, aL, base ) { var i = 0; // Subtract b from a. for ( ; aL--; ) { a[aL] -= i; i = a[aL] < b[aL] ? 1 : 0; a[aL] = i * base + a[aL] - b[aL]; } // Remove leading zeros. for ( ; !a[0] && a.length > 1; a.shift() ); } // x: dividend, y: divisor. return function ( x, y, dp, rm, base ) { var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s = x.s == y.s ? 1 : -1, xc = x.c, yc = y.c; // Either NaN, Infinity or 0? if ( !xc || !xc[0] || !yc || !yc[0] ) { return new BigNumber( // Return NaN if either NaN, or both Infinity or 0. !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN : // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. xc && xc[0] == 0 || !yc ? s * 0 : s / 0 ); } q = new BigNumber(s); qc = q.c = []; e = x.e - y.e; s = dp + e + 1; if ( !base ) { base = BASE; e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE ); s = s / LOG_BASE | 0; } // Result exponent may be one less then the current value of e. // The coefficients of the BigNumbers from convertBase may have trailing zeros. for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ ); if ( yc[i] > ( xc[i] || 0 ) ) e--; if ( s < 0 ) { qc.push(1); more = true; } else { xL = xc.length; yL = yc.length; i = 0; s += 2; // Normalise xc and yc so highest order digit of yc is >= base / 2. n = mathfloor( base / ( yc[0] + 1 ) ); // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1. // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) { if ( n > 1 ) { yc = multiply( yc, n, base ); xc = multiply( xc, n, base ); yL = yc.length; xL = xc.length; } xi = yL; rem = xc.slice( 0, yL ); remL = rem.length; // Add zeros to make remainder as long as divisor. for ( ; remL < yL; rem[remL++] = 0 ); yz = yc.slice(); yz.unshift(0); yc0 = yc[0]; if ( yc[1] >= base / 2 ) yc0++; // Not necessary, but to prevent trial digit n > base, when using base 3. // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15; do { n = 0; // Compare divisor and remainder. cmp = compare( yc, rem, yL, remL ); // If divisor < remainder. if ( cmp < 0 ) { // Calculate trial digit, n. rem0 = rem[0]; if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 ); // n is how many times the divisor goes into the current remainder. n = mathfloor( rem0 / yc0 ); // Algorithm: // 1. product = divisor * trial digit (n) // 2. if product > remainder: product -= divisor, n-- // 3. remainder -= product // 4. if product was < remainder at 2: // 5. compare new remainder and divisor // 6. If remainder > divisor: remainder -= divisor, n++ if ( n > 1 ) { // n may be > base only when base is 3. if (n >= base) n = base - 1; // product = divisor * trial digit. prod = multiply( yc, n, base ); prodL = prod.length; remL = rem.length; // Compare product and remainder. // If product > remainder. // Trial digit n too high. // n is 1 too high about 5% of the time, and is not known to have // ever been more than 1 too high. while ( compare( prod, rem, prodL, remL ) == 1 ) { n--; // Subtract divisor from product. subtract( prod, yL < prodL ? yz : yc, prodL, base ); prodL = prod.length; cmp = 1; } } else { // n is 0 or 1, cmp is -1. // If n is 0, there is no need to compare yc and rem again below, // so change cmp to 1 to avoid it. // If n is 1, leave cmp as -1, so yc and rem are compared again. if ( n == 0 ) { // divisor < remainder, so n must be at least 1. cmp = n = 1; } // product = divisor prod = yc.slice(); prodL = prod.length; } if ( prodL < remL ) prod.unshift(0); // Subtract product from remainder. subtract( rem, prod, remL, base ); remL = rem.length; // If product was < remainder. if ( cmp == -1 ) { // Compare divisor and new remainder. // If divisor < new remainder, subtract divisor from remainder. // Trial digit n too low. // n is 1 too low about 5% of the time, and very rarely 2 too low. while ( compare( yc, rem, yL, remL ) < 1 ) { n++; // Subtract divisor from remainder. subtract( rem, yL < remL ? yz : yc, remL, base ); remL = rem.length; } } } else if ( cmp === 0 ) { n++; rem = [0]; } // else cmp === 1 and n will be 0 // Add the next digit, n, to the result array. qc[i++] = n; // Update the remainder. if ( rem[0] ) { rem[remL++] = xc[xi] || 0; } else { rem = [ xc[xi] ]; remL = 1; } } while ( ( xi++ < xL || rem[0] != null ) && s-- ); more = rem[0] != null; // Leading zero? if ( !qc[0] ) qc.shift(); } if ( base == BASE ) { // To calculate q.e, first get the number of digits of qc[0]. for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ ); round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more ); // Caller is convertBase. } else { q.e = e; q.r = +more; } return q; }; })(); /* * Return a string representing the value of BigNumber n in fixed-point or exponential * notation rounded to the specified decimal places or significant digits. * * n is a BigNumber. * i is the index of the last digit required (i.e. the digit that may be rounded up). * rm is the rounding mode. * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24. */ function format( n, i, rm, caller ) { var c0, e, ne, len, str; rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode ) ? rm | 0 : ROUNDING_MODE; if ( !n.c ) return n.toString(); c0 = n.c[0]; ne = n.e; if ( i == null ) { str = coeffToString( n.c ); str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG ? toExponential( str, ne ) : toFixedPoint( str, ne ); } else { n = round( new BigNumber(n), i, rm ); // n.e may have changed if the value was rounded up. e = n.e; str = coeffToString( n.c ); len = str.length; // toPrecision returns exponential notation if the number of significant digits // specified is less than the number of digits necessary to represent the integer // part of the value in fixed-point notation. // Exponential notation. if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) { // Append zeros? for ( ; len < i; str += '0', len++ ); str = toExponential( str, e ); // Fixed-point notation. } else { i -= ne; str = toFixedPoint( str, e ); // Append zeros? if ( e + 1 > len ) { if ( --i > 0 ) for ( str += '.'; i--; str += '0' ); } else { i += e - len; if ( i > 0 ) { if ( e + 1 == len ) str += '.'; for ( ; i--; str += '0' ); } } } } return n.s < 0 && c0 ? '-' + str : str; } // Handle BigNumber.max and BigNumber.min. function maxOrMin( args, method ) { var m, n, i = 0; if ( isArray( args[0] ) ) args = args[0]; m = new BigNumber( args[0] ); for ( ; ++i < args.length; ) { n = new BigNumber( args[i] ); // If any number is NaN, return NaN. if ( !n.s ) { m = n; break; } else if ( method.call( m, n ) ) { m = n; } } return m; } /* * Return true if n is an integer in range, otherwise throw. * Use for argument validation when ERRORS is true. */ function intValidatorWithErrors( n, min, max, caller, name ) { if ( n < min || n > max || n != truncate(n) ) { raise( caller, ( name || 'decimal places' ) + ( n < min || n > max ? ' out of range' : ' not an integer' ), n ); } return true; } /* * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. * Called by minus, plus and times. */ function normalise( n, c, e ) { var i = 1, j = c.length; // Remove trailing zeros. for ( ; !c[--j]; c.pop() ); // Calculate the base 10 exponent. First get the number of digits of c[0]. for ( j = c[0]; j >= 10; j /= 10, i++ ); // Overflow? if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) { // Infinity. n.c = n.e = null; // Underflow? } else if ( e < MIN_EXP ) { // Zero. n.c = [ n.e = 0 ]; } else { n.e = e; n.c = c; } return n; } // Handle values that fail the validity test in BigNumber. parseNumeric = (function () { var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; return function ( x, str, num, b ) { var base, s = num ? str : str.replace( whitespaceOrPlus, '' ); // No exception on ±Infinity or NaN. if ( isInfinityOrNaN.test(s) ) { x.s = isNaN(s) ? null : s < 0 ? -1 : 1; } else { if ( !num ) { // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i s = s.replace( basePrefix, function ( m, p1, p2 ) { base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8; return !b || b == base ? p1 : m; }); if (b) { base = b; // E.g. '1.' to '1', '.1' to '0.1' s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' ); } if ( str != s ) return new BigNumber( s, base ); } // 'new BigNumber() not a number: {n}' // 'new BigNumber() not a base {b} number: {n}' if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str ); x.s = null; } x.c = x.e = null; id = 0; } })(); // Throw a BigNumber Error. function raise( caller, msg, val ) { var error = new Error( [ 'new BigNumber', // 0 'cmp', // 1 'config', // 2 'div', // 3 'divToInt', // 4 'eq', // 5 'gt', // 6 'gte', // 7 'lt', // 8 'lte', // 9 'minus', // 10 'mod', // 11 'plus', // 12 'precision', // 13 'random', // 14 'round', // 15 'shift', // 16 'times', // 17 'toDigits', // 18 'toExponential', // 19 'toFixed', // 20 'toFormat', // 21 'toFraction', // 22 'pow', // 23 'toPrecision', // 24 'toString', // 25 'BigNumber' // 26 ][caller] + '() ' + msg + ': ' + val ); error.name = 'BigNumber Error'; id = 0; throw error; } /* * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. * If r is truthy, it is known that there are more digits after the rounding digit. */ function round( x, sd, rm, r ) { var d, i, j, k, n, ni, rd, xc = x.c, pows10 = POWS_TEN; // if x is not Infinity or NaN... if (xc) { // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. // n is a base 1e14 number, the value of the element of array x.c containing rd. // ni is the index of n within x.c. // d is the number of digits of n. // i is the index of rd within n including leading zeros. // j is the actual index of rd within n (if < 0, rd is a leading zero). out: { // Get the number of digits of the first element of xc. for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ ); i = sd - d; // If the rounding digit is in the first element of xc... if ( i < 0 ) { i += LOG_BASE; j = sd; n = xc[ ni = 0 ]; // Get the rounding digit at index j of n. rd = n / pows10[ d - j - 1 ] % 10 | 0; } else { ni = mathceil( ( i + 1 ) / LOG_BASE ); if ( ni >= xc.length ) { if (r) { // Needed by sqrt. for ( ; xc.length <= ni; xc.push(0) ); n = rd = 0; d = 1; i %= LOG_BASE; j = i - LOG_BASE + 1; } else { break out; } } else { n = k = xc[ni]; // Get the number of digits of n. for ( d = 1; k >= 10; k /= 10, d++ ); // Get the index of rd within n. i %= LOG_BASE; // Get the index of rd within n, adjusted for leading zeros. // The number of leading zeros of n is given by LOG_BASE - d. j = i - LOG_BASE + d; // Get the rounding digit at index j of n. rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0; } } r = r || sd < 0 || // Are there any non-zero digits after the rounding digit? // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] ); r = rm < 4 ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) ) : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd. ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 || rm == ( x.s < 0 ? 8 : 7 ) ); if ( sd < 1 || !xc[0] ) { xc.length = 0; if (r) { // Convert sd to decimal places. sd -= x.e + 1; // 1, 0.1, 0.01, 0.001, 0.0001 etc. xc[0] = pows10[ ( LOG_BASE - sd % LOG_BASE ) % LOG_BASE ]; x.e = -sd || 0; } else { // Zero. xc[0] = x.e = 0; } return x; } // Remove excess digits. if ( i == 0 ) { xc.length = ni; k = 1; ni--; } else { xc.length = ni + 1; k = pows10[ LOG_BASE - i ]; // E.g. 56700 becomes 56000 if 7 is the rounding digit. // j > 0 means i > number of leading zeros of n. xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0; } // Round up? if (r) { for ( ; ; ) { // If the digit to be rounded up is in the first element of xc... if ( ni == 0 ) { // i will be the length of xc[0] before k is added. for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ ); j = xc[0] += k; for ( k = 1; j >= 10; j /= 10, k++ ); // if i != k the length has increased. if ( i != k ) { x.e++; if ( xc[0] == BASE ) xc[0] = 1; } break; } else { xc[ni] += k; if ( xc[ni] != BASE ) break; xc[ni--] = 0; k = 1; } } } // Remove trailing zeros. for ( i = xc.length; xc[--i] === 0; xc.pop() ); } // Overflow? Infinity. if ( x.e > MAX_EXP ) { x.c = x.e = null; // Underflow? Zero. } else if ( x.e < MIN_EXP ) { x.c = [ x.e = 0 ]; } } return x; } // PROTOTYPE/INSTANCE METHODS /* * Return a new BigNumber whose value is the absolute value of this BigNumber. */ P.absoluteValue = P.abs = function () { var x = new BigNumber(this); if ( x.s < 0 ) x.s = 1; return x; }; /* * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole * number in the direction of Infinity. */ P.ceil = function () { return round( new BigNumber(this), this.e + 1, 2 ); }; /* * Return * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), * 0 if they have the same value, * or null if the value of either is NaN. */ P.comparedTo = P.cmp = function ( y, b ) { id = 1; return compare( this, new BigNumber( y, b ) ); }; /* * Return the number of decimal places of the value of this BigNumber, or null if the value * of this BigNumber is ±Infinity or NaN. */ P.decimalPlaces = P.dp = function () { var n, v, c = this.c; if ( !c ) return null; n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE; // Subtract the number of trailing zeros of the last number. if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- ); if ( n < 0 ) n = 0; return n; }; /* * n / 0 = I * n / N = N * n / I = 0 * 0 / n = 0 * 0 / 0 = N * 0 / N = N * 0 / I = 0 * N / n = N * N / 0 = N * N / N = N * N / I = N * I / n = I * I / 0 = I * I / N = N * I / I = N * * Return a new BigNumber whose value is the value of this BigNumber divided by the value of * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. */ P.dividedBy = P.div = function ( y, b ) { id = 3; return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE ); }; /* * Return a new BigNumber whose value is the integer part of dividing the value of this * BigNumber by the value of BigNumber(y, b). */ P.dividedToIntegerBy = P.divToInt = function ( y, b ) { id = 4; return div( this, new BigNumber( y, b ), 0, 1 ); }; /* * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), * otherwise returns false. */ P.equals = P.eq = function ( y, b ) { id = 5; return compare( this, new BigNumber( y, b ) ) === 0; }; /* * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole * number in the direction of -Infinity. */ P.floor = function () { return round( new BigNumber(this), this.e + 1, 3 ); }; /* * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), * otherwise returns false. */ P.greaterThan = P.gt = function ( y, b ) { id = 6; return compare( this, new BigNumber( y, b ) ) > 0; }; /* * Return true if the value of this BigNumber is greater than or equal to the value of * BigNumber(y, b), otherwise returns false. */ P.greaterThanOrEqualTo = P.gte = function ( y, b ) { id = 7; return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0; }; /* * Return true if the value of this BigNumber is a finite number, otherwise returns false. */ P.isFinite = function () { return !!this.c; }; /* * Return true if the value of this BigNumber is an integer, otherwise return false. */ P.isInteger = P.isInt = function () { return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2; }; /* * Return true if the value of this BigNumber is NaN, otherwise returns false. */ P.isNaN = function () { return !this.s; }; /* * Return true if the value of this BigNumber is negative, otherwise returns false. */ P.isNegative = P.isNeg = function () { return this.s < 0; }; /* * Return true if the value of this BigNumber is 0 or -0, otherwise returns false. */ P.isZero = function () { return !!this.c && this.c[0] == 0; }; /* * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), * otherwise returns false. */ P.lessThan = P.lt = function ( y, b ) { id = 8; return compare( this, new BigNumber( y, b ) ) < 0; }; /* * Return true if the value of this BigNumber is less than or equal to the value of * BigNumber(y, b), otherwise returns false. */ P.lessThanOrEqualTo = P.lte = function ( y, b ) { id = 9; return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0; }; /* * n - 0 = n * n - N = N * n - I = -I * 0 - n = -n * 0 - 0 = 0 * 0 - N = N * 0 - I = -I * N - n = N * N - 0 = N * N - N = N * N - I = N * I - n = I * I - 0 = I * I - N = N * I - I = N * * Return a new BigNumber whose value is the value of this BigNumber minus the value of * BigNumber(y, b). */ P.minus = P.sub = function ( y, b ) { var i, j, t, xLTy, x = this, a = x.s; id = 10; y = new BigNumber( y, b ); b = y.s; // Either NaN? if ( !a || !b ) return new BigNumber(NaN); // Signs differ? if ( a != b ) { y.s = -b; return x.plus(y); } var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c; if ( !xe || !ye ) { // Either Infinity? if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN ); // Either zero? if ( !xc[0] || !yc[0] ) { // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x : // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity ROUNDING_MODE == 3 ? -0 : 0 ); } } xe = bitFloor(xe); ye = bitFloor(ye); xc = xc.slice(); // Determine which is the bigger number. if ( a = xe - ye ) { if ( xLTy = a < 0 ) { a = -a; t = xc; } else { ye = xe; t = yc; } t.reverse(); // Prepend zeros to equalise exponents. for ( b = a; b--; t.push(0) ); t.reverse(); } else { // Exponents equal. Check digit by digit. j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b; for ( a = b = 0; b < j; b++ ) { if ( xc[b] != yc[b] ) { xLTy = xc[b] < yc[b]; break; } } } // x < y? Point xc to the array of the bigger number. if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s; b = ( j = yc.length ) - ( i = xc.length ); // Append zeros to xc if shorter. // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. if ( b > 0 ) for ( ; b--; xc[i++] = 0 ); b = BASE - 1; // Subtract yc from xc. for ( ; j > a; ) { if ( xc[--j] < yc[j] ) { for ( i = j; i && !xc[--i]; xc[i] = b ); --xc[i]; xc[j] += BASE; } xc[j] -= yc[j]; } // Remove leading zeros and adjust exponent accordingly. for ( ; xc[0] == 0; xc.shift(), --ye ); // Zero? if ( !xc[0] ) { // Following IEEE 754 (2008) 6.3, // n - n = +0 but n - n = -0 when rounding towards -Infinity. y.s = ROUNDING_MODE == 3 ? -1 : 1; y.c = [ y.e = 0 ]; return y; } // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity // for finite x and y. return normalise( y, xc, ye ); }; /* * n % 0 = N * n % N = N * n % I = n * 0 % n = 0 * -0 % n = -0 * 0 % 0 = N * 0 % N = N * 0 % I = 0 * N % n = N * N % 0 = N * N % N = N * N % I = N * I % n = N * I % 0 = N * I % N = N * I % I = N * * Return a new BigNumber whose value is the value of this BigNumber modulo the value of * BigNumber(y, b). The result depends on the value of MODULO_MODE. */ P.modulo = P.mod = function ( y, b ) { var q, s, x = this; id = 11; y = new BigNumber( y, b ); // Return NaN if x is Infinity or NaN, or y is NaN or zero. if ( !x.c || !y.s || y.c && !y.c[0] ) { return new BigNumber(NaN); // Return x if y is Infinity or x is zero. } else if ( !y.c || x.c && !x.c[0] ) { return new BigNumber(x); } if ( MODULO_MODE == 9 ) { // Euclidian division: q = sign(y) * floor(x / abs(y)) // r = x - qy where 0 <= r < abs(y) s = y.s; y.s = 1; q = div( x, y, 0, 3 ); y.s = s; q.s *= s; } else { q = div( x, y, 0, MODULO_MODE ); } return x.minus( q.times(y) ); }; /* * Return a new BigNumber whose value is the value of this BigNumber negated, * i.e. multiplied by -1. */ P.negated = P.neg = function () { var x = new BigNumber(this); x.s = -x.s || null; return x; }; /* * n + 0 = n * n + N = N * n + I = I * 0 + n = n * 0 + 0 = 0 * 0 + N = N * 0 + I = I * N + n = N * N + 0 = N * N + N = N * N + I = N * I + n = I * I + 0 = I * I + N = N * I + I = I * * Return a new BigNumber whose value is the value of this BigNumber plus the value of * BigNumber(y, b). */ P.plus = P.add = function ( y, b ) { var t, x = this, a = x.s; id = 12; y = new BigNumber( y, b ); b = y.s; // Either NaN? if ( !a || !b ) return new BigNumber(NaN); // Signs differ? if ( a != b ) { y.s = -b; return x.minus(y); } var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c; if ( !xe || !ye ) { // Return ±Infinity if either ±Infinity. if ( !xc || !yc ) return new BigNumber( a / 0 ); // Either zero? // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 ); } xe = bitFloor(xe); ye = bitFloor(ye); xc = xc.slice(); // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. if ( a = xe - ye ) { if ( a > 0 ) { ye = xe; t = yc; } else { a = -a; t = xc; } t.reverse(); for ( ; a--; t.push(0) ); t.reverse(); } a = xc.length; b = yc.length; // Point xc to the longer array, and b to the shorter length. if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a; // Only start adding at yc.length - 1 as the further digits of xc can be ignored. for ( a = 0; b; ) { a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0; xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; } if (a) { xc.unshift(a); ++ye; } // No need to check for zero, as +x + +y != 0 && -x + -y != 0 // ye = MAX_EXP + 1 possible return normalise( y, xc, ye ); }; /* * Return the number of significant digits of the value of this BigNumber. * * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. */ P.precision = P.sd = function (z) { var n, v, x = this, c = x.c; // 'precision() argument not a boolean or binary digit: {z}' if ( z != null && z !== !!z && z !== 1 && z !== 0 ) { if (ERRORS) raise( 13, 'argument' + notBool, z ); if ( z != !!z ) z = null; } if ( !c ) return null; v = c.length - 1; n = v * LOG_BASE + 1; if ( v = c[v] ) { // Subtract the number of trailing zeros of the last element. for ( ; v % 10 == 0; v /= 10, n-- ); // Add the number of digits of the first element. for ( v = c[0]; v >= 10; v /= 10, n++ ); } if ( z && x.e + 1 > n ) n = x.e + 1; return n; }; /* * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if * omitted. * * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * * 'round() decimal places out of range: {dp}' * 'round() decimal places not an integer: {dp}' * 'round() rounding mode not an integer: {rm}' * 'round() rounding mode out of range: {rm}' */ P.round = function ( dp, rm ) { var n = new BigNumber(this); if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) { round( n, ~~dp + this.e + 1, rm == null || !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 ); } return n; }; /* * Return a new BigNumber whose value is the value of this BigNumber shifted by k places * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. * * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. * * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity * otherwise. * * 'shift() argument not an integer: {k}' * 'shift() argument out of range: {k}' */ P.shift = function (k) { var n = this; return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' ) // k < 1e+21, or truncate(k) will produce exponential notation. ? n.times( '1e' + truncate(k) ) : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER ) ? n.s * ( k < 0 ? 0 : 1 / 0 ) : n ); }; /* * sqrt(-n) = N * sqrt( N) = N * sqrt(-I) = N * sqrt( I) = I * sqrt( 0) = 0 * sqrt(-0) = -0 * * Return a new BigNumber whose value is the square root of the value of this BigNumber, * rounded according to DECIMAL_PLACES and ROUNDING_MODE. */ P.squareRoot = P.sqrt = function () { var m, n, r, rep, t, x = this, c = x.c, s = x.s, e = x.e, dp = DECIMAL_PLACES + 4, half = new BigNumber('0.5'); // Negative/NaN/Infinity/zero? if ( s !== 1 || !c || !c[0] ) { return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 ); } // Initial estimate. s = Math.sqrt( +x ); // Math.sqrt underflow/overflow? // Pass x to Math.sqrt as integer, then adjust the exponent of the result. if ( s == 0 || s == 1 / 0 ) { n = coeffToString(c); if ( ( n.length + e ) % 2 == 0 ) n += '0'; s = Math.sqrt(n); e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 ); if ( s == 1 / 0 ) { n = '1e' + e; } else { n = s.toExponential(); n = n.slice( 0, n.indexOf('e') + 1 ) + e; } r = new BigNumber(n); } else { r = new BigNumber( s + '' ); } // Check for zero. // r could be zero if MIN_EXP is changed after the this value was created. // This would cause a division by zero (x/t) and hence Infinity below, which would cause // coeffToString to throw. if ( r.c[0] ) { e = r.e; s = e + dp; if ( s < 3 ) s = 0; // Newton-Raphson iteration. for ( ; ; ) { t = r; r = half.times( t.plus( div( x, t, dp, 1 ) ) ); if ( coeffToString( t.c ).slice( 0, s ) === ( n = coeffToString( r.c ) ).slice( 0, s ) ) { // The exponent of r may here be one less than the final result exponent, // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits // are indexed correctly. if ( r.e < e ) --s; n = n.slice( s - 3, s + 1 ); // The 4th rounding digit may be in error by -1 so if the 4 rounding digits // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the // iteration. if ( n == '9999' || !rep && n == '4999' ) { // On the first iteration only, check to see if rounding up gives the // exact result as the nines may infinitely repeat. if ( !rep ) { round( t, t.e + DECIMAL_PLACES + 2, 0 ); if ( t.times(t).eq(x) ) { r = t; break; } } dp += 4; s += 4; rep = 1; } else { // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact // result. If not, then there are further digits and m will be truthy. if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) { // Truncate to the first rounding digit. round( r, r.e + DECIMAL_PLACES + 2, 1 ); m = !r.times(r).eq(x); } break; } } } } return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m ); }; /* * n * 0 = 0 * n * N = N * n * I = I * 0 * n = 0 * 0 * 0 = 0 * 0 * N = N * 0 * I = N * N * n = N * N * 0 = N * N * N = N * N * I = N * I * n = I * I * 0 = N * I * N = N * I * I = I * * Return a new BigNumber whose value is the value of this BigNumber times the value of * BigNumber(y, b). */ P.times = P.mul = function ( y, b ) { var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x = this, xc = x.c, yc = ( id = 17, y = new BigNumber( y, b ) ).c; // Either NaN, ±Infinity or ±0? if ( !xc || !yc || !xc[0] || !yc[0] ) { // Return NaN if either is NaN, or one is 0 and the other is Infinity. if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) { y.c = y.e = y.s = null; } else { y.s *= x.s; // Return ±Infinity if either is ±Infinity. if ( !xc || !yc ) { y.c = y.e = null; // Return ±0 if either is ±0. } else { y.c = [0]; y.e = 0; } } return y; } e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE ); y.s *= x.s; xcL = xc.length; ycL = yc.length; // Ensure xc points to longer array and xcL to its length. if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; // Initialise the result array with zeros. for ( i = xcL + ycL, zc = []; i--; zc.push(0) ); base = BASE; sqrtBase = SQRT_BASE; for ( i = ycL; --i >= 0; ) { c = 0; ylo = yc[i] % sqrtBase; yhi = yc[i] / sqrtBase | 0; for ( k = xcL, j = i + k; j > i; ) { xlo = xc[--k] % sqrtBase; xhi = xc[k] / sqrtBase | 0; m = yhi * xlo + xhi * ylo; xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c; c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi; zc[j--] = xlo % base; } zc[j] = c; } if (c) { ++e; } else { zc.shift(); } return normalise( y, zc, e ); }; /* * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted. * * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * * 'toDigits() precision out of range: {sd}' * 'toDigits() precision not an integer: {sd}' * 'toDigits() rounding mode not an integer: {rm}' * 'toDigits() rounding mode out of range: {rm}' */ P.toDigits = function ( sd, rm ) { var n = new BigNumber(this); sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0; rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0; return sd ? round( n, sd, rm ) : n; }; /* * Return a string representing the value of this BigNumber in exponential notation and * rounded using ROUNDING_MODE to dp fixed decimal places. * * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * * 'toExponential() decimal places not an integer: {dp}' * 'toExponential() decimal places out of range: {dp}' * 'toExponential() rounding mode not an integer: {rm}' * 'toExponential() rounding mode out of range: {rm}' */ P.toExponential = function ( dp, rm ) { return format( this, dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 ); }; /* * Return a string representing the value of this BigNumber in fixed-point notation rounding * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. * * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', * but e.g. (-0.00001).toFixed(0) is '-0'. * * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * * 'toFixed() decimal places not an integer: {dp}' * 'toFixed() decimal places out of range: {dp}' * 'toFixed() rounding mode not an integer: {rm}' * 'toFixed() rounding mode out of range: {rm}' */ P.toFixed = function ( dp, rm ) { return format( this, dp != null && isValidInt( dp, 0, MAX, 20 ) ? ~~dp + this.e + 1 : null, rm, 20 ); }; /* * Return a string representing the value of this BigNumber in fixed-point notation rounded * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties * of the FORMAT object (see BigNumber.config). * * FORMAT = { * decimalSeparator : '.', * groupSeparator : ',', * groupSize : 3, * secondaryGroupSize : 0, * fractionGroupSeparator : '\xA0', // non-breaking space * fractionGroupSize : 0 * }; * * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * * 'toFormat() decimal places not an integer: {dp}' * 'toFormat() decimal places out of range: {dp}' * 'toFormat() rounding mode not an integer: {rm}' * 'toFormat() rounding mode out of range: {rm}' */ P.toFormat = function ( dp, rm ) { var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 ) ? ~~dp + this.e + 1 : null, rm, 21 ); if ( this.c ) { var i, arr = str.split('.'), g1 = +FORMAT.groupSize, g2 = +FORMAT.secondaryGroupSize, groupSeparator = FORMAT.groupSeparator, intPart = arr[0], fractionPart = arr[1], isNeg = this.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; if (g2) i = g1, g1 = g2, g2 = i, len -= i; if ( g1 > 0 && len > 0 ) { i = len % g1 || g1; intPart = intDigits.substr( 0, i ); for ( ; i < len; i += g1 ) { intPart += groupSeparator + intDigits.substr( i, g1 ); } if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i); if (isNeg) intPart = '-' + intPart; } str = fractionPart ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize ) ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ), '$&' + FORMAT.fractionGroupSeparator ) : fractionPart ) : intPart; } return str; }; /* * Return a string array representing the value of this BigNumber as a simple fraction with * an integer numerator and an integer denominator. The denominator will be a positive * non-zero value less than or equal to the specified maximum denominator. If a maximum * denominator is not specified, the denominator will be the lowest value necessary to * represent the number exactly. * * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator. * * 'toFraction() max denominator not an integer: {md}' * 'toFraction() max denominator out of range: {md}' */ P.toFraction = function (md) { var arr, d0, d2, e, exp, n, n0, q, s, k = ERRORS, x = this, xc = x.c, d = new BigNumber(ONE), n1 = d0 = new BigNumber(ONE), d1 = n0 = new BigNumber(ONE); if ( md != null ) { ERRORS = false; n = new BigNumber(md); ERRORS = k; if ( !( k = n.isInt() ) || n.lt(ONE) ) { if (ERRORS) { raise( 22, 'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md ); } // ERRORS is false: // If md is a finite non-integer >= 1, round it to an integer and use it. md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null; } } if ( !xc ) return x.toString(); s = coeffToString(xc); // Determine initial denominator. // d is a power of 10 and the minimum max denominator that specifies the value exactly. e = d.e = s.length - x.e - 1; d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ]; md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n; exp = MAX_EXP; MAX_EXP = 1 / 0; n = new BigNumber(s); // n0 = d1 = 0 n0.c[0] = 0; for ( ; ; ) { q = div( n, d, 0, 1 ); d2 = d0.plus( q.times(d1) ); if ( d2.cmp(md) == 1 ) break; d0 = d1; d1 = d2; n1 = n0.plus( q.times( d2 = n1 ) ); n0 = d2; d = n.minus( q.times( d2 = d ) ); n = d2; } d2 = div( md.minus(d0), d1, 0, 1 ); n0 = n0.plus( d2.times(n1) ); d0 = d0.plus( d2.times(d1) ); n0.s = n1.s = x.s; e *= 2; // Determine which fraction is closer to x, n0/d0 or n1/d1 arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp( div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1 ? [ n1.toString(), d1.toString() ] : [ n0.toString(), d0.toString() ]; MAX_EXP = exp; return arr; }; /* * Return the value of this BigNumber converted to a number primitive. */ P.toNumber = function () { return +this; }; /* * Return a BigNumber whose value is the value of this BigNumber raised to the power n. * If m is present, return the result modulo m. * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using * ROUNDING_MODE. * * The modular power operation works efficiently when x, n, and m are positive integers, * otherwise it is equivalent to calculating x.toPower(n).modulo(m) (with POW_PRECISION 0). * * n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. * [m] {number|string|BigNumber} The modulus. * * 'pow() exponent not an integer: {n}' * 'pow() exponent out of range: {n}' * * Performs 54 loop iterations for n of 9007199254740991. */ P.toPower = P.pow = function ( n, m ) { var k, y, z, i = mathfloor( n < 0 ? -n : +n ), x = this; if ( m != null ) { id = 23; m = new BigNumber(m); } // Pass ±Infinity to Math.pow if exponent is out of range. if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) && ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) || parseFloat(n) != n && !( n = NaN ) ) || n == 0 ) { k = Math.pow( +x, n ); return new BigNumber( m ? k % m : k ); } if (m) { if ( n > 1 && x.gt(ONE) && x.isInt() && m.gt(ONE) && m.isInt() ) { x = x.mod(m); } else { z = m; // Nullify m so only a single mod operation is performed at the end. m = null; } } else if (POW_PRECISION) { // Truncating each coefficient array to a length of k after each multiplication // equates to truncating significant digits to POW_PRECISION + [28, 41], // i.e. there will be a minimum of 28 guard digits retained. // (Using + 1.5 would give [9, 21] guard digits.) k = mathceil( POW_PRECISION / LOG_BASE + 2 ); } y = new BigNumber(ONE); for ( ; ; ) { if ( i % 2 ) { y = y.times(x); if ( !y.c ) break; if (k) { if ( y.c.length > k ) y.c.length = k; } else if (m) { y = y.mod(m); } } i = mathfloor( i / 2 ); if ( !i ) break; x = x.times(x); if (k) { if ( x.c && x.c.length > k ) x.c.length = k; } else if (m) { x = x.mod(m); } } if (m) return y; if ( n < 0 ) y = ONE.div(y); return z ? y.mod(z) : k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y; }; /* * Return a string representing the value of this BigNumber rounded to sd significant digits * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits * necessary to represent the integer part of the value in fixed-point notation, then use * exponential notation. * * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. * * 'toPrecision() precision not an integer: {sd}' * 'toPrecision() precision out of range: {sd}' * 'toPrecision() rounding mode not an integer: {rm}' * 'toPrecision() rounding mode out of range: {rm}' */ P.toPrecision = function ( sd, rm ) { return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' ) ? sd | 0 : null, rm, 24 ); }; /* * Return a string representing the value of this BigNumber in base b, or base 10 if b is * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than * TO_EXP_NEG, return exponential notation. * * [b] {number} Integer, 2 to 64 inclusive. * * 'toString() base not an integer: {b}' * 'toString() base out of range: {b}' */ P.toString = function (b) { var str, n = this, s = n.s, e = n.e; // Infinity or NaN? if ( e === null ) { if (s) { str = 'Infinity'; if ( s < 0 ) str = '-' + str; } else { str = 'NaN'; } } else { str = coeffToString( n.c ); if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) { str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential( str, e ) : toFixedPoint( str, e ); } else { str = convertBase( toFixedPoint( str, e ), b | 0, 10, s ); } if ( s < 0 && n.c[0] ) str = '-' + str; } return str; }; /* * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole * number. */ P.truncated = P.trunc = function () { return round( new BigNumber(this), this.e + 1, 1 ); }; /* * Return as toString, but do not accept a base argument, and include the minus sign for * negative zero. */ P.valueOf = P.toJSON = function () { var str, n = this, e = n.e; if ( e === null ) return n.toString(); str = coeffToString( n.c ); str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential( str, e ) : toFixedPoint( str, e ); return n.s < 0 ? '-' + str : str; }; P.isBigNumber = true; if ( config != null ) BigNumber.config(config); return BigNumber; } // PRIVATE HELPER FUNCTIONS function bitFloor(n) { var i = n | 0; return n > 0 || n === i ? i : i - 1; } // Return a coefficient array as a string of base 10 digits. function coeffToString(a) { var s, z, i = 1, j = a.length, r = a[0] + ''; for ( ; i < j; ) { s = a[i++] + ''; z = LOG_BASE - s.length; for ( ; z--; s = '0' + s ); r += s; } // Determine trailing zeros. for ( j = r.length; r.charCodeAt(--j) === 48; ); return r.slice( 0, j + 1 || 1 ); } // Compare the value of BigNumbers x and y. function compare( x, y ) { var a, b, xc = x.c, yc = y.c, i = x.s, j = y.s, k = x.e, l = y.e; // Either NaN? if ( !i || !j ) return null; a = xc && !xc[0]; b = yc && !yc[0]; // Either zero? if ( a || b ) return a ? b ? 0 : -j : i; // Signs differ? if ( i != j ) return i; a = i < 0; b = k == l; // Either Infinity? if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1; // Compare exponents. if ( !b ) return k > l ^ a ? 1 : -1; j = ( k = xc.length ) < ( l = yc.length ) ? k : l; // Compare digit by digit. for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1; // Compare lengths. return k == l ? 0 : k > l ^ a ? 1 : -1; } /* * Return true if n is a valid number in range, otherwise false. * Use for argument validation when ERRORS is false. * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10. */ function intValidatorNoErrors( n, min, max ) { return ( n = truncate(n) ) >= min && n <= max; } function isArray(obj) { return Object.prototype.toString.call(obj) == '[object Array]'; } /* * Convert string of baseIn to an array of numbers of baseOut. * Eg. convertBase('255', 10, 16) returns [15, 15]. * Eg. convertBase('ff', 16, 10) returns [2, 5, 5]. */ function toBaseOut( str, baseIn, baseOut ) { var j, arr = [0], arrL, i = 0, len = str.length; for ( ; i < len; ) { for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn ); arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) ); for ( ; j < arr.length; j++ ) { if ( arr[j] > baseOut - 1 ) { if ( arr[j + 1] == null ) arr[j + 1] = 0; arr[j + 1] += arr[j] / baseOut | 0; arr[j] %= baseOut; } } } return arr.reverse(); } function toExponential( str, e ) { return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) + ( e < 0 ? 'e' : 'e+' ) + e; } function toFixedPoint( str, e ) { var len, z; // Negative exponent? if ( e < 0 ) { // Prepend zeros. for ( z = '0.'; ++e; z += '0' ); str = z + str; // Positive exponent } else { len = str.length; // Append zeros. if ( ++e > len ) { for ( z = '0', e -= len; --e; z += '0' ); str += z; } else if ( e < len ) { str = str.slice( 0, e ) + '.' + str.slice(e); } } return str; } function truncate(n) { n = parseFloat(n); return n < 0 ? mathceil(n) : mathfloor(n); } // EXPORT BigNumber = constructorFactory(); BigNumber.default = BigNumber.BigNumber = BigNumber; // AMD. if ( typeof define == 'function' && define.amd ) { define( function () { return BigNumber; } ); // Node.js and other environments that support module.exports. } else if ( typeof module != 'undefined' && module.exports ) { module.exports = BigNumber; // Browser. } else { if ( !globalObj ) globalObj = typeof self != 'undefined' ? self : Function('return this')(); globalObj.BigNumber = BigNumber; } })(this); },{}],"web3":[function(require,module,exports){ var Web3 = require('./lib/web3'); // dont override global variable if (typeof window !== 'undefined' && typeof window.Web3 === 'undefined') { window.Web3 = Web3; } module.exports = Web3; },{"./lib/web3":22}]},{},["web3"]) //# sourceMappingURL=web3.js.map<|fim▁end|>
}
<|file_name|>testmagicmethods.py<|end_file_name|><|fim▁begin|># Copyright (C) 2007-2011 Michael Foord & the mock team # E-mail: fuzzyman AT voidspace DOT org DOT uk # http://www.voidspace.org.uk/python/mock/ from tests.support import unittest2, inPy3k try: unicode except NameError: # Python 3 unicode = str long = int import inspect from mock import Mock, MagicMock, _magics class TestMockingMagicMethods(unittest2.TestCase): def testDeletingMagicMethods(self): mock = Mock() self.assertFalse(hasattr(mock, '__getitem__')) mock.__getitem__ = Mock() self.assertTrue(hasattr(mock, '__getitem__')) del mock.__getitem__ self.assertFalse(hasattr(mock, '__getitem__')) def testMagicMethodWrapping(self): mock = Mock() def f(self, name): return self, 'fish' mock.__getitem__ = f self.assertFalse(mock.__getitem__ is f) self.assertEqual(mock['foo'], (mock, 'fish')) # When you pull the function back of the *instance* # the first argument (self) is removed def instance_f(name): pass self.assertEqual(inspect.getargspec(mock.__getitem__), inspect.getargspec(instance_f)) mock.__getitem__ = mock self.assertTrue(mock.__getitem__ is mock) def testMagicMethodsIsolatedBetweenMocks(self): mock1 = Mock() mock2 = Mock() mock1.__iter__ = Mock(return_value=iter([])) self.assertEqual(list(mock1), []) self.assertRaises(TypeError, lambda: list(mock2)) def testRepr(self): mock = Mock() self.assertEqual(repr(mock), object.__repr__(mock)) mock.__repr__ = lambda s: 'foo' self.assertEqual(repr(mock), 'foo') def testStr(self): mock = Mock() self.assertEqual(str(mock), object.__str__(mock)) mock.__str__ = lambda s: 'foo' self.assertEqual(str(mock), 'foo') @unittest2.skipIf(inPy3k, "no unicode in Python 3") def testUnicode(self): mock = Mock() self.assertEqual(unicode(mock), unicode(str(mock))) mock.__unicode__ = lambda s: unicode('foo') self.assertEqual(unicode(mock), unicode('foo')) def testDictMethods(self): mock = Mock() self.assertRaises(TypeError, lambda: mock['foo']) def _del(): del mock['foo'] def _set(): mock['foo'] = 3 self.assertRaises(TypeError, _del) self.assertRaises(TypeError, _set) _dict = {} def getitem(s, name): return _dict[name] def setitem(s, name, value): _dict[name] = value def delitem(s, name): del _dict[name] mock.__setitem__ = setitem mock.__getitem__ = getitem mock.__delitem__ = delitem self.assertRaises(KeyError, lambda: mock['foo']) mock['foo'] = 'bar' self.assertEqual(_dict, {'foo': 'bar'}) self.assertEqual(mock['foo'], 'bar') del mock['foo'] self.assertEqual(_dict, {}) def testNumeric(self): original = mock = Mock() mock.value = 0 self.assertRaises(TypeError, lambda: mock + 3) def add(self, other): mock.value += other return self mock.__add__ = add self.assertEqual(mock + 3, mock) self.assertEqual(mock.value, 3) del mock.__add__ def iadd(mock): mock += 3 self.assertRaises(TypeError, iadd, mock) mock.__iadd__ = add mock += 6 self.assertEqual(mock, original) self.assertEqual(mock.value, 9) self.assertRaises(TypeError, lambda: 3 + mock) mock.__radd__ = add self.assertEqual(7 + mock, mock) self.assertEqual(mock.value, 16) def testHash(self): mock = Mock() # test delegation self.assertEqual(hash(mock), Mock.__hash__(mock)) def _hash(s): return 3 mock.__hash__ = _hash self.assertEqual(hash(mock), 3) def testNonZero(self): m = Mock() self.assertTrue(bool(m)) nonzero = lambda s: False if not inPy3k: m.__nonzero__ = nonzero else: m.__bool__ = nonzero self.assertFalse(bool(m)) def testComparison(self): if not inPy3k: # incomparable in Python 3 self. assertEqual(Mock() < 3, object() < 3) self. assertEqual(Mock() > 3, object() > 3) self. assertEqual(Mock() <= 3, object() <= 3) self. assertEqual(Mock() >= 3, object() >= 3) mock = Mock() def comp(s, o): return True mock.__lt__ = mock.__gt__ = mock.__le__ = mock.__ge__ = comp self. assertTrue(mock < 3) self. assertTrue(mock > 3) self. assertTrue(mock <= 3) self. assertTrue(mock >= 3) def test_equality(self): for mock in Mock(), MagicMock(): self.assertEqual(mock == mock, True) self.assertEqual(mock != mock, False) self.assertEqual(mock == object(), False) self.assertEqual(mock != object(), True) def eq(self, other): return other == 3 mock.__eq__ = eq self.assertTrue(mock == 3) self.assertFalse(mock == 4) def ne(self, other): return other == 3 mock.__ne__ = ne self.assertTrue(mock != 3) self.assertFalse(mock != 4) mock = MagicMock() mock.__eq__.return_value = True self.assertEqual(mock == 3, True) mock.__ne__.return_value = False self.assertEqual(mock != 3, False) def testLenContainsIter(self): mock = Mock() self.assertRaises(TypeError, len, mock) self.assertRaises(TypeError, iter, mock) self.assertRaises(TypeError, lambda: 'foo' in mock) mock.__len__ = lambda s: 6 self.assertEqual(len(mock), 6) mock.__contains__ = lambda s, o: o == 3 self.assertTrue(3 in mock) self.assertFalse(6 in mock) mock.__iter__ = lambda s: iter('foobarbaz') self.assertEqual(list(mock), list('foobarbaz')) def testMagicMock(self): mock = MagicMock() mock.__iter__.return_value = iter([1, 2, 3]) self.assertEqual(list(mock), [1, 2, 3]) if inPy3k: mock.__bool__.return_value = False self.assertFalse(hasattr(mock, '__nonzero__')) else: mock.__nonzero__.return_value = False self.assertFalse(hasattr(mock, '__bool__')) self.assertFalse(bool(mock)) for entry in _magics: self.assertTrue(hasattr(mock, entry)) self.assertFalse(hasattr(mock, '__imaginery__')) def testMagicMockDefaults(self): mock = MagicMock() self.assertEqual(int(mock), 1) self.assertEqual(complex(mock), 1j)<|fim▁hole|> self.assertEqual(long(mock), long(1)) self.assertNotIn(object(), mock) self.assertEqual(len(mock), 0) self.assertEqual(list(mock), []) self.assertEqual(hash(mock), object.__hash__(mock)) self.assertEqual(str(mock), object.__str__(mock)) self.assertEqual(unicode(mock), object.__str__(mock)) self.assertIsInstance(unicode(mock), unicode) self.assertTrue(bool(mock)) if not inPy3k: self.assertEqual(oct(mock), '1') else: # in Python 3 oct and hex use __index__ # so these tests are for __index__ in py3k self.assertEqual(oct(mock), '0o1') self.assertEqual(hex(mock), '0x1') # how to test __sizeof__ ? @unittest2.skipIf(inPy3k, "no __cmp__ in Python 3") def testNonDefaultMagicMethods(self): mock = MagicMock() self.assertRaises(AttributeError, lambda: mock.__cmp__) mock = Mock() mock.__cmp__ = lambda s, o: 0 self.assertEqual(mock, object()) def testMagicMethodsAndSpec(self): class Iterable(object): def __iter__(self): pass mock = Mock(spec=Iterable) self.assertRaises(AttributeError, lambda: mock.__iter__) mock.__iter__ = Mock(return_value=iter([])) self.assertEqual(list(mock), []) class NonIterable(object): pass mock = Mock(spec=NonIterable) self.assertRaises(AttributeError, lambda: mock.__iter__) def set_int(): mock.__int__ = Mock(return_value=iter([])) self.assertRaises(AttributeError, set_int) mock = MagicMock(spec=Iterable) self.assertEqual(list(mock), []) self.assertRaises(AttributeError, set_int) def testMagicMethodsAndSpecSet(self): class Iterable(object): def __iter__(self): pass mock = Mock(spec_set=Iterable) self.assertRaises(AttributeError, lambda: mock.__iter__) mock.__iter__ = Mock(return_value=iter([])) self.assertEqual(list(mock), []) class NonIterable(object): pass mock = Mock(spec_set=NonIterable) self.assertRaises(AttributeError, lambda: mock.__iter__) def set_int(): mock.__int__ = Mock(return_value=iter([])) self.assertRaises(AttributeError, set_int) mock = MagicMock(spec_set=Iterable) self.assertEqual(list(mock), []) self.assertRaises(AttributeError, set_int) def testSettingUnsupportedMagicMethod(self): mock = MagicMock() def set_setattr(): mock.__setattr__ = lambda self, name: None self.assertRaisesRegexp(AttributeError, "Attempting to set unsupported magic method '__setattr__'.", set_setattr ) def testAttributesAndReturnValue(self): mock = MagicMock() attr = mock.foo def _get_type(obj): # the type of every mock (or magicmock) is a custom subclass # so the real type is the second in the mro return type(obj).__mro__[1] self.assertEqual(_get_type(attr), MagicMock) returned = mock() self.assertEqual(_get_type(returned), MagicMock) if __name__ == '__main__': unittest2.main()<|fim▁end|>
self.assertEqual(float(mock), 1.0)
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>""" Django settings for urlscript project. Generated by 'django-admin startproject' using Django 1.9.7. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '+^d@j=txhj+yu39&c(!^#w177dj$-si2*lhtho-53)g-5l(w%p' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'core', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'urlscript.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'urlscript.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',<|fim▁hole|> { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True SITE_ID = 1 # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # The path where the bwrap executable is located BUBBLEWRAP_PATH = "" # Custom args that can be sent to the bwrap executable e.g --dir /abc /abc etc BWRAP_CUSTOM_OPTIONS = "" # Preferably make the below a RAMfs to make it faster SCRIPTS_TMP_DIR = "" # The max time for the scripts to run SCRIPT_TIMEOUT = 30 # A dictionary mappying the language extension with the executable LANGUAGE_EXECUTABLE = { 'py': 'python3', 'js': 'node', } try: from .local import * except ImportError: pass<|fim▁end|>
},
<|file_name|>Resources.py<|end_file_name|><|fim▁begin|>__author__ = 'mpetyx' from tastypie.authorization import DjangoAuthorization from .models import OpeniQuestion from OPENiapp.APIS.OpeniGenericResource import GenericResource from OPENiapp.APIS.OPENiAuthorization import Authorization from OPENiapp.APIS.OPENiAuthentication import Authentication class QuestionResource(GenericResource): class Meta: queryset = OpeniQuestion.objects.all() list_allowed_methods = ['get', 'post'] detail_allowed_methods = ['get', 'post', 'put', 'delete'] resource_name = 'question' authentication = Authentication() authorization = Authorization() # filtering = { # 'slug': ALL, # 'user': ALL_WITH_RELATIONS, # 'created': ['exact', 'range', 'gt', 'gte', 'lt', 'lte'], # } extra_actions = [ { "name": "comments", "http_method": "GET", "resource_type": "list", "description": "comments from CBS", "fields": { "cbs": { "type": "string", "required": True, "description": "list of selected CBS" } } }, { "name": "likes", "http_method": "GET", "resource_type": "list", "description": "likes from CBS", "fields": { "cbs": { "type": "string", "required": True, "description": "list of selected CBS" } } }, { "name": "dislikes", "http_method": "GET", "resource_type": "list", "description": "dislikes from CBS", "fields": { "cbs": { "type": "string", "required": True, "description": "list of selected CBS"<|fim▁hole|> } } } ]<|fim▁end|>
<|file_name|>time_linux.go<|end_file_name|><|fim▁begin|>package archive // import "github.com/ory/dockertest/v3/docker/pkg/archive" import (<|fim▁hole|>func timeToTimespec(time time.Time) (ts syscall.Timespec) { if time.IsZero() { // Return UTIME_OMIT special value ts.Sec = 0 ts.Nsec = ((1 << 30) - 2) return } return syscall.NsecToTimespec(time.UnixNano()) }<|fim▁end|>
"syscall" "time" )
<|file_name|>mongo.rs<|end_file_name|><|fim▁begin|>extern crate bson; extern crate mongo_driver; use bson::Bson; use mongo_driver::CommandAndFindOptions; use mongo_driver::client::{ClientPool, Uri}; use mongo_driver::collection::UpdateOptions; use mongo_driver::flags::UpdateFlag;<|fim▁hole|>use storage::error::{StoreError, StoreResult}; use storage::storage::{Storage, StorageStatus}; pub struct MongoStore { config: DBConfig, pool: ClientPool, } impl MongoStore { pub fn new(config: &DBConfig) -> StoreResult<MongoStore> { let conn = MongoStore::conn( config.username.as_str(), config.password.as_str(), config.host.as_str(), config.port, ); let uri = Uri::new(conn.clone()).ok_or(StoreError::UriParseError(conn))?; let pool = ClientPool::new(uri, None); Ok(MongoStore { config: config.clone(), pool: pool, }) } fn conn(user: &str, pass: &str, host: &str, port: u16) -> String { format!("mongodb://{}:{}@{}:{}", user, pass, host, port) } } impl Storage<Object> for MongoStore { fn get(&self, id: &str, obj_type: &str) -> Option<StoreResult<Object>> { let query = doc!{ "_id" => id }; let client = self.pool.pop(); let coll = client.get_collection(self.config.name.as_str(), obj_type); let res = coll.find(&query, None).ok().and_then(|mut cursor| { cursor.next().map(|res| { res.or_else(|err| { error!("Failed to get {} from the Mongo store due to {}", id, err); Err(StoreError::StorageFindError) }).and_then(|doc| { Object::from_bson(utils::map_bson_dates_to_string(Bson::Document(doc))) .map_err(StoreError::InvalidItemError) }) }) }); res } fn put(&self, item: &Object) -> StoreResult<StorageStatus> { item.as_document() .map_err(StoreError::InvalidItemError) .and_then(|doc| { let client = self.pool.pop(); let coll = client.get_collection(self.config.name.as_str(), item.object_type.as_str()); let id = item.id.as_str(); let filter = doc! { "_id" => id }; let mut opts = UpdateOptions::default(); opts.update_flags.add(UpdateFlag::Upsert); coll.update(&filter, &doc, Some(&opts)) .map(|_| StorageStatus::Available) .or_else(|_| Err(StoreError::StorageWriteError)) }) } fn updated_at(&self) -> Option<i64> { let collections = vec!["asset", "episode", "season", "show", "special"]; let mut opts = CommandAndFindOptions::default(); opts.limit = 1; let client = self.pool.pop(); collections .iter() .filter_map(|coll_name| { let coll = client.get_collection(self.config.name.as_str(), *coll_name); let query = doc! { "$query" => {}, "$orderby" => { "attributes.updated_at" => -1 } }; let res = coll.find(&query, Some(&opts)) .ok() .and_then(|mut cursor| cursor.next()) .and_then(|result| result.ok()) .and_then(|mut document| { document .remove("attributes") .and_then(|attributes| match attributes { bson::Bson::Document(mut attr) => match attr.remove("updated_at") { Some(bson::Bson::UtcDatetime(datetime)) => { Some(datetime.timestamp()) } _ => None, }, _ => None, }) }); res }) .fold(None, |max, cur| match max { Some(val) => Some(::std::cmp::max(val, cur)), None => Some(cur), }) } }<|fim▁end|>
use config::DBConfig; use objects::{utils, Object};
<|file_name|>stat.js<|end_file_name|><|fim▁begin|>'use strict' const utils = require('../../utils')<|fim▁hole|> module.exports = { command: 'stat <key>', describe: 'Get stats for the DAG node named by <key>', builder: {}, handler (argv) { utils.getIPFS((err, ipfs) => { if (err) { throw err } ipfs.object.stat(argv.key, {enc: 'base58'}, (err, stats) => { if (err) { throw err } delete stats.Hash // only for js-ipfs-api output Object.keys(stats).forEach((key) => { console.log(`${key}: ${stats[key]}`) }) }) }) } }<|fim▁end|>
const debug = require('debug') const log = debug('cli:object') log.error = debug('cli:object:error')
<|file_name|>factories.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import factory from data.tests.factories import DepartmentFactory from ..models import Tourist, TouristCard class TouristFactory(factory.DjangoModelFactory):<|fim▁hole|> class Meta: model = Tourist first_name = 'Dave' last_name = 'Greel' email = '[email protected]' class TouristCardFactory(factory.DjangoModelFactory): class Meta: model = TouristCard tourist = factory.SubFactory(TouristFactory) current_department = factory.SubFactory(DepartmentFactory)<|fim▁end|>
<|file_name|>database.rs<|end_file_name|><|fim▁begin|>// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Ethcore rocksdb ipc service use traits::*; use rocksdb::{DB, Writable, WriteBatch, IteratorMode, DBIterator, IndexType, Options, DBCompactionStyle, BlockBasedOptions, Direction}; use std::sync::{RwLock, Arc}; use std::convert::From; use ipc::IpcConfig; use std::mem; use ipc::binary::BinaryConvertError; use std::collections::{VecDeque, HashMap, BTreeMap}; enum WriteCacheEntry { Remove, Write(Vec<u8>), } pub struct WriteCache { entries: HashMap<Vec<u8>, WriteCacheEntry>, preferred_len: usize, } const FLUSH_BATCH_SIZE: usize = 4096; impl WriteCache { fn new(cache_len: usize) -> WriteCache { WriteCache { entries: HashMap::new(), preferred_len: cache_len, } } fn write(&mut self, key: Vec<u8>, val: Vec<u8>) { self.entries.insert(key, WriteCacheEntry::Write(val)); } fn remove(&mut self, key: Vec<u8>) { self.entries.insert(key, WriteCacheEntry::Remove); } fn get(&self, key: &[u8]) -> Option<Vec<u8>> { self.entries.get(key).and_then( |vec_ref| match vec_ref { &WriteCacheEntry::Write(ref val) => Some(val.clone()), &WriteCacheEntry::Remove => None }) } /// WriteCache should be locked for this fn flush(&mut self, db: &DB, amount: usize) -> Result<(), Error> { let batch = WriteBatch::new(); let mut removed_so_far = 0; while removed_so_far < amount { if self.entries.len() == 0 { break; } let removed_key = { let (key, cache_entry) = self.entries.iter().nth(0) .expect("if entries.len == 0, we should have break in the loop, still we got here somehow"); match *cache_entry { WriteCacheEntry::Write(ref val) => { try!(batch.put(&key, val)); }, WriteCacheEntry::Remove => { try!(batch.delete(&key)); }, } key.clone() }; self.entries.remove(&removed_key); removed_so_far = removed_so_far + 1; } if removed_so_far > 0 { try!(db.write(batch)); } Ok(()) } /// flushes until cache is empty fn flush_all(&mut self, db: &DB) -> Result<(), Error> { while !self.is_empty() { try!(self.flush(db, FLUSH_BATCH_SIZE)); } Ok(()) } fn is_empty(&self) -> bool { self.entries.is_empty() } fn try_shrink(&mut self, db: &DB) -> Result<(), Error> { if self.entries.len() > self.preferred_len { try!(self.flush(db, FLUSH_BATCH_SIZE)); } Ok(()) } } pub struct Database { db: RwLock<Option<DB>>, /// Iterators - dont't use between threads! iterators: RwLock<BTreeMap<IteratorHandle, DBIterator>>, write_cache: RwLock<WriteCache>, } unsafe impl Send for Database {} unsafe impl Sync for Database {} impl Database { pub fn new() -> Database { Database { db: RwLock::new(None), iterators: RwLock::new(BTreeMap::new()), write_cache: RwLock::new(WriteCache::new(DEFAULT_CACHE_LEN)), } } pub fn flush(&self) -> Result<(), Error> { let mut cache_lock = self.write_cache.write(); let db_lock = self.db.read(); if db_lock.is_none() { return Ok(()); } let db = db_lock.as_ref().unwrap(); try!(cache_lock.try_shrink(&db)); Ok(()) } pub fn flush_all(&self) -> Result<(), Error> { let mut cache_lock = self.write_cache.write(); let db_lock = self.db.read(); if db_lock.is_none() { return Ok(()); } let db = db_lock.as_ref().expect("we should have exited with Ok(()) on the previous step"); try!(cache_lock.flush_all(&db)); Ok(()) } } impl Drop for Database { fn drop(&mut self) { self.flush().unwrap(); } } #[ipc] impl DatabaseService for Database { fn open(&self, config: DatabaseConfig, path: String) -> Result<(), Error> { let mut db = self.db.write(); if db.is_some() { return Err(Error::AlreadyOpen); } let mut opts = Options::new(); opts.set_max_open_files(256); opts.create_if_missing(true); opts.set_use_fsync(false); opts.set_compaction_style(DBCompactionStyle::DBUniversalCompaction); if let Some(size) = config.prefix_size { let mut block_opts = BlockBasedOptions::new(); block_opts.set_index_type(IndexType::HashSearch); opts.set_block_based_table_factory(&block_opts); opts.set_prefix_extractor_fixed_size(size); } *db = Some(try!(DB::open(&opts, &path))); Ok(()) } /// Opens database in the specified path with the default config fn open_default(&self, path: String) -> Result<(), Error> { self.open(DatabaseConfig::default(), path) } fn close(&self) -> Result<(), Error> { try!(self.flush_all()); let mut db = self.db.write(); if db.is_none() { return Err(Error::IsClosed); } *db = None; Ok(()) } fn put(&self, key: &[u8], value: &[u8]) -> Result<(), Error> { let mut cache_lock = self.write_cache.write(); cache_lock.write(key.to_vec(), value.to_vec()); Ok(()) } fn delete(&self, key: &[u8]) -> Result<(), Error> { let mut cache_lock = self.write_cache.write(); cache_lock.remove(key.to_vec()); Ok(()) } fn write(&self, transaction: DBTransaction) -> Result<(), Error> { let mut cache_lock = self.write_cache.write(); let mut writes = transaction.writes.borrow_mut(); for kv in writes.drain(..) { cache_lock.write(kv.key, kv.value); } let mut removes = transaction.removes.borrow_mut(); for k in removes.drain(..) { cache_lock.remove(k); } Ok(()) } fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Error> { { let key_vec = key.to_vec(); let cache_hit = self.write_cache.read().get(&key_vec); if cache_hit.is_some() { return Ok(Some(cache_hit.expect("cache_hit.is_some() = true, still there is none somehow here"))) } } let db_lock = self.db.read(); let db = try!(db_lock.as_ref().ok_or(Error::IsClosed)); match try!(db.get(key)) { Some(db_vec) => { Ok(Some(db_vec.to_vec())) }, None => Ok(None), } } fn get_by_prefix(&self, prefix: &[u8]) -> Result<Option<Vec<u8>>, Error> { let db_lock = self.db.read(); let db = try!(db_lock.as_ref().ok_or(Error::IsClosed)); let mut iter = db.iterator(IteratorMode::From(prefix, Direction::Forward)); match iter.next() { // TODO: use prefix_same_as_start read option (not availabele in C API currently) Some((k, v)) => if k[0 .. prefix.len()] == prefix[..] { Ok(Some(v.to_vec())) } else { Ok(None) }, _ => Ok(None) } } fn is_empty(&self) -> Result<bool, Error> { let db_lock = self.db.read(); let db = try!(db_lock.as_ref().ok_or(Error::IsClosed)); Ok(db.iterator(IteratorMode::Start).next().is_none()) } fn iter(&self) -> Result<IteratorHandle, Error> { let db_lock = self.db.read(); let db = try!(db_lock.as_ref().ok_or(Error::IsClosed)); let mut iterators = self.iterators.write(); let next_iterator = iterators.keys().last().unwrap_or(&0) + 1; iterators.insert(next_iterator, db.iterator(IteratorMode::Start)); Ok(next_iterator) } fn iter_next(&self, handle: IteratorHandle) -> Option<KeyValue> { let mut iterators = self.iterators.write(); let mut iterator = match iterators.get_mut(&handle) { Some(some_iterator) => some_iterator, None => { return None; }, }; iterator.next().and_then(|(some_key, some_val)| { Some(KeyValue { key: some_key.to_vec(), value: some_val.to_vec(), }) }) } fn dispose_iter(&self, handle: IteratorHandle) -> Result<(), Error> { let mut iterators = self.iterators.write(); iterators.remove(&handle); Ok(()) } } // TODO : put proper at compile-time impl IpcConfig for Database {} /// Database iterator pub struct DatabaseIterator { client: Arc<DatabaseClient<::nanomsg::Socket>>, handle: IteratorHandle, } impl Iterator for DatabaseIterator { type Item = (Vec<u8>, Vec<u8>); fn next(&mut self) -> Option<Self::Item> { self.client.iter_next(self.handle).and_then(|kv| Some((kv.key, kv.value))) } } impl Drop for DatabaseIterator { fn drop(&mut self) { self.client.dispose_iter(self.handle).unwrap(); } } #[cfg(test)] mod test { use super::Database; use traits::*; use devtools::*; #[test] fn can_be_created() { let db = Database::new(); assert!(db.is_empty().is_err()); } #[test] fn can_be_open_empty() { let db = Database::new(); let path = RandomTempPath::create_dir(); db.open_default(path.as_str().to_owned()).unwrap(); assert!(db.is_empty().is_ok()); } #[test] fn can_store_key() { let db = Database::new(); let path = RandomTempPath::create_dir(); db.open_default(path.as_str().to_owned()).unwrap(); db.put("xxx".as_bytes(), "1".as_bytes()).unwrap(); db.flush_all().unwrap(); assert!(!db.is_empty().unwrap()); } #[test] fn can_retrieve() { let db = Database::new(); let path = RandomTempPath::create_dir(); db.open_default(path.as_str().to_owned()).unwrap(); db.put("xxx".as_bytes(), "1".as_bytes()).unwrap(); db.close().unwrap(); db.open_default(path.as_str().to_owned()).unwrap(); assert_eq!(db.get("xxx".as_bytes()).unwrap().unwrap(), "1".as_bytes().to_vec()); } } #[cfg(test)] mod write_cache_tests { use super::Database; use traits::*; use devtools::*; #[test] fn cache_write_flush() { let db = Database::new(); let path = RandomTempPath::create_dir(); db.open_default(path.as_str().to_owned()).unwrap(); db.put("100500".as_bytes(), "1".as_bytes()).unwrap(); db.delete("100500".as_bytes()).unwrap(); db.flush_all().unwrap(); let val = db.get("100500".as_bytes()).unwrap(); assert!(val.is_none()); } }<|fim▁hole|> use super::{DatabaseClient, Database}; use traits::*; use devtools::*; use nanoipc; use std::sync::Arc; use std::sync::atomic::{Ordering, AtomicBool}; use crossbeam; use run_worker; fn init_worker(addr: &str) -> nanoipc::Worker<Database> { let mut worker = nanoipc::Worker::<Database>::new(&Arc::new(Database::new())); worker.add_duplex(addr).unwrap(); worker } #[test] fn can_call_handshake() { let url = "ipc:///tmp/parity-db-ipc-test-10.ipc"; let worker_should_exit = Arc::new(AtomicBool::new(false)); let worker_is_ready = Arc::new(AtomicBool::new(false)); let c_worker_should_exit = worker_should_exit.clone(); let c_worker_is_ready = worker_is_ready.clone(); ::std::thread::spawn(move || { let mut worker = init_worker(url); while !c_worker_should_exit.load(Ordering::Relaxed) { worker.poll(); c_worker_is_ready.store(true, Ordering::Relaxed); } }); while !worker_is_ready.load(Ordering::Relaxed) { } let client = nanoipc::init_duplex_client::<DatabaseClient<_>>(url).unwrap(); let hs = client.handshake(); worker_should_exit.store(true, Ordering::Relaxed); assert!(hs.is_ok()); } #[test] fn can_open_db() { let url = "ipc:///tmp/parity-db-ipc-test-20.ipc"; let path = RandomTempPath::create_dir(); let worker_should_exit = Arc::new(AtomicBool::new(false)); let worker_is_ready = Arc::new(AtomicBool::new(false)); let c_worker_should_exit = worker_should_exit.clone(); let c_worker_is_ready = worker_is_ready.clone(); ::std::thread::spawn(move || { let mut worker = init_worker(url); while !c_worker_should_exit.load(Ordering::Relaxed) { worker.poll(); c_worker_is_ready.store(true, Ordering::Relaxed); } }); while !worker_is_ready.load(Ordering::Relaxed) { } let client = nanoipc::init_duplex_client::<DatabaseClient<_>>(url).unwrap(); client.open_default(path.as_str().to_owned()).unwrap(); assert!(client.is_empty().unwrap()); worker_should_exit.store(true, Ordering::Relaxed); } #[test] fn can_put() { let url = "ipc:///tmp/parity-db-ipc-test-30.ipc"; let path = RandomTempPath::create_dir(); crossbeam::scope(move |scope| { let stop = Arc::new(AtomicBool::new(false)); run_worker(scope, stop.clone(), url); let client = nanoipc::generic_client::<DatabaseClient<_>>(url).unwrap(); client.open_default(path.as_str().to_owned()).unwrap(); client.put("xxx".as_bytes(), "1".as_bytes()).unwrap(); client.close().unwrap(); stop.store(true, Ordering::Relaxed); }); } #[test] fn can_put_and_read() { let url = "ipc:///tmp/parity-db-ipc-test-40.ipc"; let path = RandomTempPath::create_dir(); crossbeam::scope(move |scope| { let stop = Arc::new(AtomicBool::new(false)); run_worker(scope, stop.clone(), url); let client = nanoipc::generic_client::<DatabaseClient<_>>(url).unwrap(); client.open_default(path.as_str().to_owned()).unwrap(); client.put("xxx".as_bytes(), "1".as_bytes()).unwrap(); client.close().unwrap(); client.open_default(path.as_str().to_owned()).unwrap(); assert_eq!(client.get("xxx".as_bytes()).unwrap().unwrap(), "1".as_bytes().to_vec()); stop.store(true, Ordering::Relaxed); }); } #[test] fn can_read_empty() { let url = "ipc:///tmp/parity-db-ipc-test-45.ipc"; let path = RandomTempPath::create_dir(); crossbeam::scope(move |scope| { let stop = Arc::new(AtomicBool::new(false)); run_worker(scope, stop.clone(), url); let client = nanoipc::generic_client::<DatabaseClient<_>>(url).unwrap(); client.open_default(path.as_str().to_owned()).unwrap(); assert!(client.get("xxx".as_bytes()).unwrap().is_none()); stop.store(true, Ordering::Relaxed); }); } #[test] fn can_commit_client_transaction() { let url = "ipc:///tmp/parity-db-ipc-test-60.ipc"; let path = RandomTempPath::create_dir(); crossbeam::scope(move |scope| { let stop = Arc::new(AtomicBool::new(false)); run_worker(scope, stop.clone(), url); let client = nanoipc::generic_client::<DatabaseClient<_>>(url).unwrap(); client.open_default(path.as_str().to_owned()).unwrap(); let transaction = DBTransaction::new(); transaction.put("xxx".as_bytes(), "1".as_bytes()); client.write(transaction).unwrap(); client.close().unwrap(); client.open_default(path.as_str().to_owned()).unwrap(); assert_eq!(client.get("xxx".as_bytes()).unwrap().unwrap(), "1".as_bytes().to_vec()); stop.store(true, Ordering::Relaxed); }); } #[test] fn key_write_read_ipc() { let url = "ipc:///tmp/parity-db-ipc-test-70.ipc"; let path = RandomTempPath::create_dir(); crossbeam::scope(|scope| { let stop = StopGuard::new(); run_worker(&scope, stop.share(), url); let client = nanoipc::generic_client::<DatabaseClient<_>>(url).unwrap(); client.open_default(path.as_str().to_owned()).unwrap(); let mut batch = Vec::new(); for _ in 0..100 { batch.push((random_str(256).as_bytes().to_vec(), random_str(256).as_bytes().to_vec())); batch.push((random_str(256).as_bytes().to_vec(), random_str(2048).as_bytes().to_vec())); batch.push((random_str(2048).as_bytes().to_vec(), random_str(2048).as_bytes().to_vec())); batch.push((random_str(2048).as_bytes().to_vec(), random_str(256).as_bytes().to_vec())); } for &(ref k, ref v) in batch.iter() { client.put(k, v).unwrap(); } client.close().unwrap(); client.open_default(path.as_str().to_owned()).unwrap(); for &(ref k, ref v) in batch.iter() { assert_eq!(v, &client.get(k).unwrap().unwrap()); } }); } }<|fim▁end|>
#[cfg(test)] mod client_tests {
<|file_name|>alarm_control_panel.py<|end_file_name|><|fim▁begin|>"""Support for SimpliSafe alarm control panels.""" import logging import re from simplipy.entity import EntityTypes from simplipy.system import SystemStates from homeassistant.components.alarm_control_panel import ( FORMAT_NUMBER, FORMAT_TEXT, AlarmControlPanel, ) from homeassistant.components.alarm_control_panel.const import ( SUPPORT_ALARM_ARM_AWAY, SUPPORT_ALARM_ARM_HOME, ) from homeassistant.const import ( CONF_CODE, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED, ) from homeassistant.util.dt import utc_from_timestamp from . import SimpliSafeEntity from .const import DATA_CLIENT, DOMAIN _LOGGER = logging.getLogger(__name__) ATTR_ALARM_ACTIVE = "alarm_active" ATTR_BATTERY_BACKUP_POWER_LEVEL = "battery_backup_power_level" ATTR_GSM_STRENGTH = "gsm_strength" ATTR_LAST_EVENT_INFO = "last_event_info" ATTR_LAST_EVENT_SENSOR_NAME = "last_event_sensor_name" ATTR_LAST_EVENT_SENSOR_TYPE = "last_event_sensor_type" ATTR_LAST_EVENT_TIMESTAMP = "last_event_timestamp" ATTR_LAST_EVENT_TYPE = "last_event_type" ATTR_RF_JAMMING = "rf_jamming" ATTR_WALL_POWER_LEVEL = "wall_power_level" ATTR_WIFI_STRENGTH = "wifi_strength" async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up a SimpliSafe alarm control panel based on existing config.""" pass async def async_setup_entry(hass, entry, async_add_entities): """Set up a SimpliSafe alarm control panel based on a config entry.""" simplisafe = hass.data[DOMAIN][DATA_CLIENT][entry.entry_id] async_add_entities( [ SimpliSafeAlarm(simplisafe, system, entry.data.get(CONF_CODE)) for system in simplisafe.systems.values() ], True, ) class SimpliSafeAlarm(SimpliSafeEntity, AlarmControlPanel): """Representation of a SimpliSafe alarm.""" def __init__(self, simplisafe, system, code): """Initialize the SimpliSafe alarm.""" super().__init__(system, "Alarm Control Panel") self._changed_by = None self._code = code self._simplisafe = simplisafe self._state = None # Some properties only exist for V2 or V3 systems: for prop in ( ATTR_BATTERY_BACKUP_POWER_LEVEL, ATTR_GSM_STRENGTH, ATTR_RF_JAMMING, ATTR_WALL_POWER_LEVEL, ATTR_WIFI_STRENGTH, ): if hasattr(system, prop): self._attrs[prop] = getattr(system, prop) @property def changed_by(self): """Return info about who changed the alarm last.""" return self._changed_by @property def code_format(self): """Return one or more digits/characters.""" if not self._code: return None if isinstance(self._code, str) and re.search("^\\d+$", self._code): return FORMAT_NUMBER return FORMAT_TEXT @property def state(self): """Return the state of the entity.""" return self._state @property def supported_features(self) -> int: """Return the list of supported features.""" return SUPPORT_ALARM_ARM_HOME | SUPPORT_ALARM_ARM_AWAY def _validate_code(self, code, state): """Validate given code.""" check = self._code is None or code == self._code if not check: _LOGGER.warning("Wrong code entered for %s", state) return check async def async_alarm_disarm(self, code=None): """Send disarm command.""" if not self._validate_code(code, "disarming"): return await self._system.set_off() async def async_alarm_arm_home(self, code=None): """Send arm home command.""" if not self._validate_code(code, "arming home"): return await self._system.set_home() async def async_alarm_arm_away(self, code=None): """Send arm away command.""" if not self._validate_code(code, "arming away"): return await self._system.set_away()<|fim▁hole|> async def async_update(self): """Update alarm status.""" event_data = self._simplisafe.last_event_data[self._system.system_id] if event_data.get("pinName"): self._changed_by = event_data["pinName"] if self._system.state == SystemStates.error: self._online = False return self._online = True if self._system.state == SystemStates.off: self._state = STATE_ALARM_DISARMED elif self._system.state in (SystemStates.home, SystemStates.home_count): self._state = STATE_ALARM_ARMED_HOME elif self._system.state in ( SystemStates.away, SystemStates.away_count, SystemStates.exit_delay, ): self._state = STATE_ALARM_ARMED_AWAY else: self._state = None last_event = self._simplisafe.last_event_data[self._system.system_id] self._attrs.update( { ATTR_ALARM_ACTIVE: self._system.alarm_going_off, ATTR_LAST_EVENT_INFO: last_event["info"], ATTR_LAST_EVENT_SENSOR_NAME: last_event["sensorName"], ATTR_LAST_EVENT_SENSOR_TYPE: EntityTypes(last_event["sensorType"]).name, ATTR_LAST_EVENT_TIMESTAMP: utc_from_timestamp( last_event["eventTimestamp"] ), ATTR_LAST_EVENT_TYPE: last_event["eventType"], } )<|fim▁end|>
<|file_name|>server.py<|end_file_name|><|fim▁begin|>import threading import time from . import _impl from .common import * from .connection import * from .networktablenode import NetworkTableNode from .type import NetworkTableEntryTypeManager import logging logger = logging.getLogger('nt') __all__ = ["NetworkTableServer"] class ServerConnectionState: """Represents the state of a connection to the server """ def __init__(self, name): self.name = name def __str__(self): return self.name # represents that the server has received the connection from the client but # has not yet received the client hello GOT_CONNECTION_FROM_CLIENT = ServerConnectionState("GOT_CONNECTION_FROM_CLIENT") # represents that the client is in a connected non-error state CONNECTED_TO_CLIENT = ServerConnectionState("CONNECTED_TO_CLIENT") # represents that the client has disconnected from the server CLIENT_DISCONNECTED = ServerConnectionState("CLIENT_DISCONNECTED") class ServerError(ServerConnectionState): """Represents that the client is in an error state """ def __init__(self, e): """Create a new error state :param e: """ ServerConnectionState.__init__(self, "SERVER_ERROR") self.e = e def getException(self): """:returns: the exception that caused the client connection to enter an error state """ return self.e def __str__(self): return "SERVER_ERROR: %s" % self.e class ServerConnectionAdapter: """Object that adapts messages from a client to the server """ def gotoState(self, newState): if self.connectionState != newState: logger.info("%s entered connection state: %s", self, newState) self.connectionState = newState def __init__(self, stream, entryStore, adapterListener, typeManager): """Create a server connection adapter for a given stream :param stream: :param entryStore: :param adapterListener: """ self.connection = NetworkTableConnection(stream, typeManager) self.entryStore = entryStore self.adapterListener = adapterListener self.connectionState = None self.gotoState(GOT_CONNECTION_FROM_CLIENT) self.readManager = ReadManager(self, self.connection, name="Server Connection Reader Thread") self.readManager.start() def __str__(self): return 'Server 0x%08x' % id(self) def badMessage(self, e): self.gotoState(ServerError(e)) self.adapterListener.close(self, True) def ioError(self, e): if isinstance(e, StreamEOF): self.gotoState(CLIENT_DISCONNECTED) else: self.gotoState(ServerError(e)) self.adapterListener.close(self, False) def shutdown(self, closeStream): """stop the read thread and close the stream """ self.readManager.stop() if closeStream: self.connection.close() def keepAlive(self): pass # just let it happen def clientHello(self, protocolRevision): if self.connectionState != GOT_CONNECTION_FROM_CLIENT: raise BadMessageError("A server should not receive a client hello after it has already connected/entered an error state") if protocolRevision != PROTOCOL_REVISION: self.connection.sendProtocolVersionUnsupported() raise BadMessageError("Client Connected with bad protocol revision: 0x%x" % protocolRevision) else: self.entryStore.sendServerHello(self.connection) self.gotoState(CONNECTED_TO_CLIENT) def protocolVersionUnsupported(self, protocolRevision): raise BadMessageError("A server should not receive a protocol version unsupported message") def serverHelloComplete(self): raise BadMessageError("A server should not receive a server hello complete message") def offerIncomingAssignment(self, entry): self.entryStore.offerIncomingAssignment(entry) def offerIncomingUpdate(self, entry, sequenceNumber, value): self.entryStore.offerIncomingUpdate(entry, sequenceNumber, value) def getEntry(self, id): return self.entryStore.getEntry(id) def sendEntry(self, entryBytes): try: if self.connectionState == CONNECTED_TO_CLIENT: self.connection.sendEntry(entryBytes) except IOError as e: self.ioError(e) def flush(self): try: self.connection.flush() except IOError as e: self.ioError(e) def getConnectionState(self): """:returns: the state of the connection """ return self.connectionState def ensureAlive(self): try: self.connection.sendKeepAlive() except IOError as e: self.ioError(e) class ServerNetworkTableEntryStore(AbstractNetworkTableEntryStore): """The entry store for a {@link NetworkTableServer} """ def __init__(self, listenerManager): """Create a new Server entry store :param listenerManager: the listener manager that fires events from this entry store """ AbstractNetworkTableEntryStore.__init__(self, listenerManager) self.nextId = 0 def addEntry(self, newEntry): with self.entry_lock: entry = self.namedEntries.get(newEntry.name) if entry is None: newEntry.setId(self.nextId) self.nextId += 1 self.idEntries[newEntry.getId()] = newEntry self.namedEntries[newEntry.name] = newEntry return True return False<|fim▁hole|> return True return False def sendServerHello(self, connection): """Send all entries in the entry store as entry assignments in a single transaction :param connection: """ transaction = [] with self.entry_lock: # Cannot use sendEntry while holding entry lock! for entry in self.namedEntries.values(): transaction.append(entry.getAssignmentBytes()) for entry in transaction: connection.sendEntry(entry) connection.sendServerHelloComplete() connection.flush() class ServerConnectionList: """A list of connections that the server currently has """ def __init__(self): self.connections = [] self.connectionsLock = _impl.create_rlock('server_conn_lock') def add(self, connection): """Add a connection to the list :param connection: """ with self.connectionsLock: self.connections.append(connection) def close(self, connectionAdapter, closeStream): with self.connectionsLock: try: self.connections.remove(connectionAdapter) except ValueError: return logger.info("Close: %s", connectionAdapter) connectionAdapter.shutdown(closeStream) def closeAll(self): """close all connections and remove them """ with self.connectionsLock: for connection in self.connections: logger.info("Close: %s", connection) connection.shutdown(True) del self.connections[:] def sendEntry(self, entryBytes): with self.connectionsLock: for connection in self.connections: connection.sendEntry(entryBytes) def flush(self): with self.connectionsLock: for connection in self.connections: connection.flush() def ensureAlive(self): with self.connectionsLock: for connection in self.connections: connection.ensureAlive() class NetworkTableServer(NetworkTableNode): """A server node in NetworkTables 2.0 """ def __init__(self, streamProvider): """Create a NetworkTable Server :param streamProvider: """ NetworkTableNode.__init__(self, ServerNetworkTableEntryStore(self)) self.typeManager = NetworkTableEntryTypeManager() self.streamProvider = streamProvider self.connectionList = ServerConnectionList() self.writeManager = WriteManager(self.connectionList, self.entryStore, None) self.entryStore.setIncomingReceiver(self.writeManager) self.entryStore.setOutgoingReceiver(self.writeManager) # start incoming stream monitor self.running = True self.monitorThread = threading.Thread(target=self._incomingMonitor, name="Server Incoming Stream Monitor Thread") self.monitorThread.daemon = True self.monitorThread.start() # start write manager self.writeManager.start() def close(self): try: self.running = False self.monitorThread.join() self.writeManager.stop() self.connectionList.closeAll() time.sleep(1) #To get around bug where an error will occur in select if the socket server is closed before all sockets finish closing self.streamProvider.close() time.sleep(1) except IOError as e: logger.error("Error during close: %s", e) def isConnected(self): return True def isServer(self): return True def _incomingMonitor(self): while self.running: try: newStream = self.streamProvider.accept() if newStream is not None: connectionAdapter = ServerConnectionAdapter(newStream, self.entryStore, self.connectionList, self.typeManager) self.connectionList.add(connectionAdapter) except IOError: pass #could not get a new stream for some reason. ignore and continue<|fim▁end|>
def updateEntry(self, entry, sequenceNumber, value): with self.entry_lock: if entry.putValue(sequenceNumber, value):
<|file_name|>flush.rs<|end_file_name|><|fim▁begin|>// This file is part of rust-web/twig<|fim▁hole|>use extension::api::TokenParser; use engine::Node; use engine::parser::{Job, ParserError}; use engine::parser::token::stream::Item; use api::error::Traced; #[derive(Debug, Default)] pub struct Flush; impl TokenParser for Flush { fn tag(&self) -> &'static str { "flush" } fn parse(&self, _job: &mut Job, _item: &Item) -> Result<Box<Node>, Traced<ParserError>> { unimplemented!() } }<|fim▁end|>
// // For the copyright and license information, please view the LICENSE // file that was distributed with this source code.
<|file_name|>libnpmsearch-tests.ts<|end_file_name|><|fim▁begin|>import search = require('libnpmsearch'); const opts: search.Options = { limit: 20, from: 0, detailed: false, sortBy: 'optimal', registry: 'https://registry.npmjs.org', token: 'token', }; <|fim▁hole|>search.stream('libnpm'); // $ExpectType ReadWriteStream search.stream('libnpm', opts); // $ExpectType ReadWriteStream<|fim▁end|>
search('libnpm'); // $ExpectType Promise<Result[]> search('libnpm', opts); // $ExpectType Promise<Result[]> search('libnpm', { detailed: true }); // $ExpectType Promise<DetailedResult[]>
<|file_name|>haversine.py<|end_file_name|><|fim▁begin|>from math import radians, cos, sin, asin, sqrt def haversine(lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])<|fim▁hole|> # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) # 6367 km is the radius of the Earth km = 6367 * c return km<|fim▁end|>
<|file_name|>bosun.js<|end_file_name|><|fim▁begin|>/// <reference path="angular.d.ts" /> /// <reference path="angular-route.d.ts" /> /// <reference path="angular-sanitize.d.ts" /> /// <reference path="bootstrap.d.ts" /> /// <reference path="moment.d.ts" /> /// <reference path="moment-duration-format.d.ts" /> /// <reference path="d3.d.ts" /> /// <reference path="underscore.d.ts" /> var bosunApp = angular.module('bosunApp', [ 'ngRoute', 'bosunControllers', 'mgcrea.ngStrap', 'ngSanitize', 'ui.ace', ]); bosunApp.config(['$routeProvider', '$locationProvider', '$httpProvider', function ($routeProvider, $locationProvider, $httpProvider) { $locationProvider.html5Mode(true); $routeProvider. when('/', { title: 'Dashboard', templateUrl: 'partials/dashboard.html', controller: 'DashboardCtrl' }). when('/items', { title: 'Items', templateUrl: 'partials/items.html', controller: 'ItemsCtrl' }). when('/expr', { title: 'Expression', templateUrl: 'partials/expr.html', controller: 'ExprCtrl' }). when('/graph', { title: 'Graph', templateUrl: 'partials/graph.html', controller: 'GraphCtrl' }). when('/host', { title: 'Host View', templateUrl: 'partials/host.html', controller: 'HostCtrl', reloadOnSearch: false }). when('/silence', { title: 'Silence', templateUrl: 'partials/silence.html', controller: 'SilenceCtrl' }). when('/config', { title: 'Configuration', templateUrl: 'partials/config.html', controller: 'ConfigCtrl', reloadOnSearch: false }). when('/action', { title: 'Action', templateUrl: 'partials/action.html', controller: 'ActionCtrl' }). when('/history', { title: 'Alert History', templateUrl: 'partials/history.html', controller: 'HistoryCtrl' }). when('/put', { title: 'Data Entry', templateUrl: 'partials/put.html', controller: 'PutCtrl' }). when('/incident', { title: 'Incident', templateUrl: 'partials/incident.html', controller: 'IncidentCtrl' }). otherwise({ redirectTo: '/' }); $httpProvider.interceptors.push(function ($q) { return { 'request': function (config) { config.headers['X-Miniprofiler'] = 'true'; return config; } }; }); }]); bosunApp.run(['$location', '$rootScope', function ($location, $rootScope) { $rootScope.$on('$routeChangeSuccess', function (event, current, previous) { $rootScope.title = current.$$route.title; $rootScope.shortlink = false; }); }]); var bosunControllers = angular.module('bosunControllers', []); bosunControllers.controller('BosunCtrl', ['$scope', '$route', '$http', '$q', '$rootScope', function ($scope, $route, $http, $q, $rootScope) { $scope.$on('$routeChangeSuccess', function (event, current, previous) { $scope.stop(true); }); $scope.active = function (v) { if (!$route.current) { return null; } if ($route.current.loadedTemplateUrl == 'partials/' + v + '.html') { return { active: true }; } return null; }; $scope.json = function (v) { return JSON.stringify(v, null, ' '); }; $scope.btoa = function (v) { return encodeURIComponent(btoa(v)); }; $scope.encode = function (v) { return encodeURIComponent(v); }; $scope.req_from_m = function (m) { var r = new Request(); var q = new Query(); q.metric = m; r.queries.push(q); return r; }; $scope.panelClass = function (status, prefix) { if (prefix === void 0) { prefix = "panel-"; } switch (status) { case "critical": return prefix + "danger"; case "unknown": return prefix + "info"; case "warning": return prefix + "warning"; case "normal": return prefix + "success"; case "error": return prefix + "danger"; default: return prefix + "default"; } }; $scope.values = {}; $scope.setKey = function (key, value) { if (value === undefined) { delete $scope.values[key]; } else { $scope.values[key] = value; } }; $scope.getKey = function (key) { return $scope.values[key]; }; var scheduleFilter; $scope.refresh = function (filter) { var d = $q.defer(); scheduleFilter = filter; $scope.animate(); var p = $http.get('/api/alerts?filter=' + encodeURIComponent(filter || "")) .success(function (data) { $scope.schedule = data; $scope.timeanddate = data.TimeAndDate; d.resolve(); }) .error(function (err) { d.reject(err); }); p.finally($scope.stop); return d.promise; }; var sz = 30; var orig = 700; var light = '#4ba2d9'; var dark = '#1f5296'; var med = '#356eb6'; var mult = sz / orig; var bgrad = 25 * mult; var circles = [ [150, 150, dark], [550, 150, dark], [150, 550, light], [550, 550, light], ]; var svg = d3.select('#logo') .append('svg') .attr('height', sz) .attr('width', sz); svg.selectAll('rect.bg') .data([[0, light], [sz / 2, dark]]) .enter() .append('rect') .attr('class', 'bg') .attr('width', sz) .attr('height', sz / 2) .attr('rx', bgrad) .attr('ry', bgrad) .attr('fill', function (d) { return d[1]; }) .attr('y', function (d) { return d[0]; }); svg.selectAll('path.diamond') .data([150, 550]) .enter() .append('path') .attr('d', function (d) { var s = 'M ' + d * mult + ' ' + 150 * mult; var w = 200 * mult; s += ' l ' + w + ' ' + w; s += ' l ' + -w + ' ' + w; s += ' l ' + -w + ' ' + -w + ' Z'; return s; }) .attr('fill', med) .attr('stroke', 'white') .attr('stroke-width', 15 * mult); svg.selectAll('rect.white') .data([150, 350, 550]) .enter() .append('rect') .attr('class', 'white') .attr('width', .5) .attr('height', '100%') .attr('fill', 'white') .attr('x', function (d) { return d * mult; }); svg.selectAll('circle') .data(circles) .enter() .append('circle') .attr('cx', function (d) { return d[0] * mult; }) .attr('cy', function (d) { return d[1] * mult; }) .attr('r', 62.5 * mult) .attr('fill', function (d) { return d[2]; }) .attr('stroke', 'white') .attr('stroke-width', 25 * mult); var transitionDuration = 750; var animateCount = 0; $scope.animate = function () { animateCount++; if (animateCount == 1) { doAnimate(); } }; function doAnimate() { if (!animateCount) { return; } d3.shuffle(circles); svg.selectAll('circle') .data(circles, function (d, i) { return i; }) .transition() .duration(transitionDuration) .attr('cx', function (d) { return d[0] * mult; }) .attr('cy', function (d) { return d[1] * mult; }) .attr('fill', function (d) { return d[2]; }); setTimeout(doAnimate, transitionDuration); } $scope.stop = function (all) { if (all === void 0) { all = false; } if (all) { animateCount = 0; } else if (animateCount > 0) { animateCount--; } }; var short = $('#shortlink')[0]; $scope.shorten = function () { $http.get('/api/shorten').success(function (data) { if (data.id) { short.value = data.id; $rootScope.shortlink = true; setTimeout(function () { short.setSelectionRange(0, data.id.length); }); } }); }; }]); var tsdbDateFormat = 'YYYY/MM/DD-HH:mm:ss'; moment.defaultFormat = tsdbDateFormat; moment.locale('en', { relativeTime: { future: "in %s", past: "%s-ago", s: "%ds", m: "%dm", mm: "%dm", h: "%dh", hh: "%dh", d: "%dd", dd: "%dd", M: "%dn", MM: "%dn", y: "%dy", yy: "%dy" } }); function createCookie(name, value, days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } else { expires = ""; } document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/"; } function readCookie(name) { var nameEQ = escape(name) + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) === ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) === 0) return unescape(c.substring(nameEQ.length, c.length)); } return null; } function eraseCookie(name) { createCookie(name, "", -1); } function getUser() { return readCookie('action-user'); } function setUser(name) { createCookie('action-user', name, 1000); } // from: http://stackoverflow.com/a/15267754/864236 bosunApp.filter('reverse', function () { return function (items) { if (!angular.isArray(items)) { return []; } return items.slice().reverse(); }; }); bosunControllers.controller('ActionCtrl', ['$scope', '$http', '$location', '$route', function ($scope, $http, $location, $route) { var search = $location.search(); $scope.user = readCookie("action-user"); $scope.type = search.type; $scope.notify = true; $scope.msgValid = true; $scope.message = ""; $scope.validateMsg = function () { $scope.msgValid = (!$scope.notify) || ($scope.message != ""); }; if (search.key) { var keys = search.key; if (!angular.isArray(search.key)) { keys = [search.key]; } $location.search('key', null); $scope.setKey('action-keys', keys); } else { $scope.keys = $scope.getKey('action-keys'); } $scope.submit = function () { $scope.validateMsg(); if (!$scope.msgValid || ($scope.user == "")) { return; } var data = { Type: $scope.type, User: $scope.user, Message: $scope.message, Keys: $scope.keys, Notify: $scope.notify }; createCookie("action-user", $scope.user, 1000); $http.post('/api/action', data) .success(function (data) { $location.url('/'); }) .error(function (error) { alert(error); }); }; }]); bosunControllers.controller('ConfigCtrl', ['$scope', '$http', '$location', '$route', '$timeout', '$sce', function ($scope, $http, $location, $route, $timeout, $sce) { var search = $location.search(); $scope.fromDate = search.fromDate || ''; $scope.fromTime = search.fromTime || ''; $scope.toDate = search.toDate || ''; $scope.toTime = search.toTime || ''; $scope.intervals = +search.intervals || 5; $scope.duration = +search.duration || null; $scope.config_text = 'Loading config...'; $scope.selected_alert = search.alert || ''; $scope.email = search.email || ''; $scope.template_group = search.template_group || ''; $scope.items = parseItems(); $scope.tab = search.tab || 'results'; $scope.aceTheme = 'chrome'; $scope.aceMode = 'bosun'; var expr = search.expr; function buildAlertFromExpr() { if (!expr) return; var newAlertName = "test"; var idx = 1; //find a unique alert name while ($scope.items["alert"].indexOf(newAlertName) != -1 || $scope.items["template"].indexOf(newAlertName) != -1) { newAlertName = "test" + idx; idx++; } var text = '\n\ntemplate ' + newAlertName + ' {\n' + ' subject = {{.Last.Status}}: {{.Alert.Name}} on {{.Group.host}}\n' + ' body = `<p>Name: {{.Alert.Name}}\n' + ' <p>Tags:\n' + ' <table>\n' + ' {{range $k, $v := .Group}}\n' + ' <tr><td>{{$k}}</td><td>{{$v}}</td></tr>\n' + ' {{end}}\n' + ' </table>`\n' + '}\n\n'; var expression = atob(expr); var lines = expression.split("\n").map(function (l) { return l.trim(); }); lines[lines.length - 1] = "crit = " + lines[lines.length - 1]; expression = lines.join("\n "); text += 'alert ' + newAlertName + ' {\n' + ' template = ' + newAlertName + '\n' + ' ' + expression + '\n' + '}\n'; $scope.config_text += text; $scope.items = parseItems(); $timeout(function () { //can't scroll editor until after control is updated. Defer it. $scope.scrollTo("alert", newAlertName); }); } function parseItems() { var configText = $scope.config_text; var re = /^\s*(alert|template|notification|lookup|macro)\s+([\w\-\.\$]+)\s*\{/gm; var match; var items = {}; items["alert"] = []; items["template"] = []; items["lookup"] = []; items["notification"] = []; items["macro"] = []; while (match = re.exec(configText)) { var type = match[1]; var name = match[2]; var list = items[type]; if (!list) { list = []; items[type] = list; } list.push(name); } return items; } $http.get('/api/config?hash=' + (search.hash || '')) .success(function (data) { $scope.config_text = data; $scope.items = parseItems(); buildAlertFromExpr(); if (!$scope.selected_alert && $scope.items["alert"].length) { $scope.selected_alert = $scope.items["alert"][0]; } $timeout(function () { //can't scroll editor until after control is updated. Defer it. $scope.scrollTo("alert", $scope.selected_alert); }); }) .error(function (data) { $scope.validationResult = "Error fetching config: " + data; }); $scope.reparse = function () { $scope.items = parseItems(); }; var editor; $scope.aceLoaded = function (_editor) { editor = _editor; $scope.editor = editor; editor.getSession().setUseWrapMode(true); editor.on("blur", function () { $scope.$apply(function () { $scope.items = parseItems(); }); }); }; var syntax = true; $scope.aceToggleHighlight = function () { if (syntax) { editor.getSession().setMode(); syntax = false; return; } syntax = true; editor.getSession().setMode({ path: 'ace/mode/' + $scope.aceMode, v: Date.now() }); }; $scope.scrollTo = function (type, name) { var searchRegex = new RegExp("^\\s*" + type + "\\s+" + name, "g"); editor.find(searchRegex, { backwards: false, wrap: true, caseSensitive: false, wholeWord: false, regExp: true }); if (type == "alert") { $scope.selectAlert(name); } }; $scope.scrollToInterval = function (id) { document.getElementById('time-' + id).scrollIntoView(); $scope.show($scope.sets[id]); }; $scope.show = function (set) { set.show = 'loading...'; $scope.animate(); var url = '/api/rule?' + 'alert=' + encodeURIComponent($scope.selected_alert) + '&from=' + encodeURIComponent(set.Time); $http.post(url, $scope.config_text) .success(function (data) { procResults(data); set.Results = data.Sets[0].Results; }) .error(function (error) { $scope.error = error; }) .finally(function () { $scope.stop(); delete (set.show); }); }; $scope.setInterval = function () { var from = moment.utc($scope.fromDate + ' ' + $scope.fromTime); var to = moment.utc($scope.toDate + ' ' + $scope.toTime); if (!from.isValid() || !to.isValid()) { return; } var diff = from.diff(to); if (!diff) { return; } var intervals = +$scope.intervals; if (intervals < 2) { return; } diff /= 1000 * 60; var d = Math.abs(Math.round(diff / intervals)); if (d < 1) { d = 1; } $scope.duration = d; }; $scope.setDuration = function () { var from = moment.utc($scope.fromDate + ' ' + $scope.fromTime); var to = moment.utc($scope.toDate + ' ' + $scope.toTime); if (!from.isValid() || !to.isValid()) { return; } var diff = from.diff(to); if (!diff) { return; } var duration = +$scope.duration; if (duration < 1) { return; } $scope.intervals = Math.abs(Math.round(diff / duration / 1000 / 60)); }; $scope.selectAlert = function (alert) { $scope.selected_alert = alert; $location.search("alert", alert); // Attempt to find `template = foo` in order to set up quick jump between template and alert var searchRegex = new RegExp("^\\s*alert\\s+" + alert, "g"); var lines = $scope.config_text.split("\n"); $scope.quickJumpTarget = null; for (var i = 0; i < lines.length; i++) { if (searchRegex.test(lines[i])) { for (var j = i + 1; j < lines.length; j++) { // Close bracket at start of line means end of alert. if (/^\s*\}/m.test(lines[j])) { return; } var found = /^\s*template\s*=\s*([\w\-\.\$]+)/m.exec(lines[j]); if (found) { $scope.quickJumpTarget = "template " + found[1]; } } } } }; $scope.quickJump = function () { var parts = $scope.quickJumpTarget.split(" "); if (parts.length != 2) { return; } $scope.scrollTo(parts[0], parts[1]); if (parts[0] == "template" && $scope.selected_alert) { $scope.quickJumpTarget = "alert " + $scope.selected_alert; } }; $scope.setTemplateGroup = function (group) { var match = group.match(/{(.*)}/); if (match) { $scope.template_group = match[1]; } }; var line_re = /test:(\d+)/; $scope.validate = function () { $http.post('/api/config_test', $scope.config_text) .success(function (data) { if (data == "") { $scope.validationResult = "Valid"; $timeout(function () { $scope.validationResult = ""; }, 2000); } else { $scope.validationResult = data; var m = data.match(line_re); if (angular.isArray(m) && (m.length > 1)) { editor.gotoLine(m[1]); } } }) .error(function (error) { $scope.validationResult = 'Error validating: ' + error; }); }; $scope.test = function () { $scope.error = ''; $scope.running = true; $scope.warning = []; $location.search('fromDate', $scope.fromDate || null); $location.search('fromTime', $scope.fromTime || null); $location.search('toDate', $scope.toDate || null); $location.search('toTime', $scope.toTime || null); $location.search('intervals', String($scope.intervals) || null); $location.search('duration', String($scope.duration) || null); $location.search('email', $scope.email || null); $location.search('template_group', $scope.template_group || null); $scope.animate(); var from = moment.utc($scope.fromDate + ' ' + $scope.fromTime); var to = moment.utc($scope.toDate + ' ' + $scope.toTime); if (!from.isValid()) { from = to; } if (!to.isValid()) { to = from; } if (!from.isValid() && !to.isValid()) { from = to = moment.utc(); } var diff = from.diff(to); var intervals; if (diff == 0) { intervals = 1; } else if (Math.abs(diff) < 60 * 1000) { intervals = 2; } else { intervals = +$scope.intervals; } var url = '/api/rule?' + 'alert=' + encodeURIComponent($scope.selected_alert) + '&from=' + encodeURIComponent(from.format()) + '&to=' + encodeURIComponent(to.format()) + '&intervals=' + encodeURIComponent(intervals) + '&email=' + encodeURIComponent($scope.email) + '&template_group=' + encodeURIComponent($scope.template_group); $http.post(url, $scope.config_text) .success(function (data) { $scope.sets = data.Sets; $scope.alert_history = data.AlertHistory; if (data.Hash) { $location.search('hash', data.Hash); } procResults(data); }) .error(function (error) { $scope.error = error; }) .finally(function () { $scope.running = false; $scope.stop(); }); }; $scope.zws = function (v) { return v.replace(/([,{}()])/g, '$1\u200b'); }; $scope.loadTimelinePanel = function (entry, v) { if (v.doneLoading && !v.error) { return; } v.error = null; v.doneLoading = false; var ak = entry.key; var openBrack = ak.indexOf("{"); var closeBrack = ak.indexOf("}"); var alertName = ak.substr(0, openBrack); var template = ak.substring(openBrack + 1, closeBrack); var url = '/api/rule?' + 'alert=' + encodeURIComponent(alertName) + '&from=' + encodeURIComponent(moment.utc(v.Time).format()) + '&template_group=' + encodeURIComponent(template); $http.post(url, $scope.config_text) .success(function (data) { v.subject = data.Subject; v.body = $sce.trustAsHtml(data.Body); }) .error(function (error) { v.error = error; }) .finally(function () { v.doneLoading = true; }); }; function procResults(data) { $scope.subject = data.Subject; $scope.body = $sce.trustAsHtml(data.Body); $scope.data = JSON.stringify(data.Data, null, ' '); $scope.error = data.Errors; $scope.warning = data.Warnings; } $scope.downloadConfig = function () { var blob = new Blob([$scope.config_text], { type: "text/plain;charset=utf-8" }); saveAs(blob, "bosun.conf"); }; return $scope; }]); bosunControllers.controller('DashboardCtrl', ['$scope', '$http', '$location', function ($scope, $http, $location) { var search = $location.search(); $scope.loading = 'Loading'; $scope.error = ''; $scope.filter = search.filter; if (!$scope.filter) { $scope.filter = readCookie("filter"); } $location.search('filter', $scope.filter || null); reload(); function reload() { $scope.refresh($scope.filter).then(function () { $scope.loading = ''; $scope.error = ''; }, function (err) { $scope.loading = ''; $scope.error = 'Unable to fetch alerts: ' + err; }); } $scope.keydown = function ($event) { if ($event.keyCode == 13) { createCookie("filter", $scope.filter || "", 1000); $location.search('filter', $scope.filter || null); } }; }]); bosunApp.directive('tsResults', function () { return { templateUrl: '/partials/results.html', link: function (scope, elem, attrs) { scope.isSeries = function (v) { return typeof (v) === 'object'; }; } }; }); bosunApp.directive('tsComputations', function () { return { scope: { computations: '=tsComputations', time: '=', header: '=' }, templateUrl: '/partials/computations.html', link: function (scope, elem, attrs) { if (scope.time) { var m = moment.utc(scope.time); scope.timeParam = "&date=" + encodeURIComponent(m.format("YYYY-MM-DD")) + "&time=" + encodeURIComponent(m.format("HH:mm")); } scope.btoa = function (v) { return encodeURIComponent(btoa(v)); }; } }; }); function fmtDuration(v) { var diff = moment.duration(v, 'milliseconds'); var f; if (Math.abs(v) < 60000) { return diff.format('ss[s]'); } return diff.format('d[d]hh[h]mm[m]ss[s]'); } function fmtTime(v) { var m = moment(v).utc(); var now = moment().utc(); var msdiff = now.diff(m); var ago = ''; var inn = ''; if (msdiff >= 0) { ago = ' ago'; } else { inn = 'in '; } return m.format() + ' (' + inn + fmtDuration(msdiff) + ago + ')'; } function parseDuration(v) { var pattern = /(\d+)(d|y|n|h|m|s)-ago/; var m = pattern.exec(v); return moment.duration(parseInt(m[1]), m[2].replace('n', 'M')); } bosunApp.directive("tsTime", function () { return { link: function (scope, elem, attrs) { scope.$watch(attrs.tsTime, function (v) { var m = moment(v).utc(); var text = fmtTime(v); if (attrs.tsEndTime) { var diff = moment(scope.$eval(attrs.tsEndTime)).diff(m); var duration = fmtDuration(diff); text += " for " + duration; } if (attrs.noLink) { elem.text(text); } else { var el = document.createElement('a'); el.text = text; el.href = 'http://www.timeanddate.com/worldclock/converted.html?iso='; el.href += m.format('YYYYMMDDTHHmm'); el.href += '&p1=0'; angular.forEach(scope.timeanddate, function (v, k) { el.href += '&p' + (k + 2) + '=' + v; }); elem.html(el); } }); } }; }); bosunApp.directive("tsSince", function () { return { link: function (scope, elem, attrs) { scope.$watch(attrs.tsSince, function (v) { var m = moment(v).utc(); elem.text(m.fromNow()); }); } }; }); bosunApp.directive("tooltip", function () { return { link: function (scope, elem, attrs) { angular.element(elem[0]).tooltip({ placement: "bottom" }); } }; }); bosunApp.directive('tsTab', function () { return { link: function (scope, elem, attrs) { var ta = elem[0]; elem.keydown(function (evt) { if (evt.ctrlKey) { return; } // This is so shift-enter can be caught to run a rule when tsTab is called from // the rule page if (evt.keyCode == 13 && evt.shiftKey) { return; } switch (evt.keyCode) { case 9: evt.preventDefault(); var v = ta.value; var start = ta.selectionStart; ta.value = v.substr(0, start) + "\t" + v.substr(start); ta.selectionStart = ta.selectionEnd = start + 1; return; case 13: if (ta.selectionStart != ta.selectionEnd) { return; } evt.preventDefault(); var v = ta.value; var start = ta.selectionStart; var sub = v.substr(0, start); var last = sub.lastIndexOf("\n") + 1; for (var i = last; i < sub.length && /[ \t]/.test(sub[i]); i++) ; var ws = sub.substr(last, i - last); ta.value = v.substr(0, start) + "\n" + ws + v.substr(start); ta.selectionStart = ta.selectionEnd = start + 1 + ws.length; } }); } }; }); bosunApp.directive('tsresizable', function () { return { restrict: 'A', scope: { callback: '&onResize' }, link: function postLink(scope, elem, attrs) { elem.resizable(); elem.on('resizestop', function (evt, ui) { if (scope.callback) { scope.callback(); } }); } }; }); bosunApp.directive('tsTableSort', ['$timeout', function ($timeout) { return { link: function (scope, elem, attrs) { $timeout(function () { $(elem).tablesorter({ sortList: scope.$eval(attrs.tsTableSort) }); }); } }; }]); bosunApp.directive('tsTimeLine', function () { var tsdbFormat = d3.time.format.utc("%Y/%m/%d-%X"); function parseDate(s) { return moment.utc(s).toDate(); } var margin = { top: 10, right: 10, bottom: 30, left: 250 }; return { link: function (scope, elem, attrs) { scope.shown = {}; scope.collapse = function (i, entry, v) { scope.shown[i] = !scope.shown[i]; if (scope.loadTimelinePanel && entry && scope.shown[i]) { scope.loadTimelinePanel(entry, v); } }; scope.$watch('alert_history', update); function update(history) { if (!history) { return; } var entries = d3.entries(history); if (!entries.length) { return; } entries.sort(function (a, b) { return a.key.localeCompare(b.key); }); scope.entries = entries; var values = entries.map(function (v) { return v.value; }); var keys = entries.map(function (v) { return v.key; }); var barheight = 500 / values.length; barheight = Math.min(barheight, 45); barheight = Math.max(barheight, 15); var svgHeight = values.length * barheight + margin.top + margin.bottom; var height = svgHeight - margin.top - margin.bottom; var svgWidth = elem.width(); var width = svgWidth - margin.left - margin.right; var xScale = d3.time.scale.utc().range([0, width]); var xAxis = d3.svg.axis() .scale(xScale) .orient('bottom'); elem.empty(); var svg = d3.select(elem[0]) .append('svg') .attr('width', svgWidth) .attr('height', svgHeight) .append('g') .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); svg.append('g') .attr('class', 'x axis tl-axis') .attr('transform', 'translate(0,' + height + ')'); xScale.domain([ d3.min(values, function (d) { return d3.min(d.History, function (c) { return parseDate(c.Time); }); }), d3.max(values, function (d) { return d3.max(d.History, function (c) { return parseDate(c.EndTime); }); }), ]); var legend = d3.select(elem[0]) .append('div') .attr('class', 'tl-legend'); var time_legend = legend .append('div') .text(values[0].History[0].Time); var alert_legend = legend .append('div') .text(keys[0]); svg.select('.x.axis') .transition() .call(xAxis); var chart = svg.append('g'); angular.forEach(entries, function (entry, i) { chart.selectAll('.bars') .data(entry.value.History) .enter() .append('rect') .attr('class', function (d) { return 'tl-' + d.Status; }) .attr('x', function (d) { return xScale(parseDate(d.Time)); }) .attr('y', i * barheight) .attr('height', barheight) .attr('width', function (d) { return xScale(parseDate(d.EndTime)) - xScale(parseDate(d.Time)); }) .on('mousemove.x', mousemove_x) .on('mousemove.y', function (d) { alert_legend.text(entry.key); }) .on('click', function (d, j) { var id = 'panel' + i + '-' + j; scope.shown['group' + i] = true; scope.shown[id] = true; if (scope.loadTimelinePanel) { scope.loadTimelinePanel(entry, d); } scope.$apply(); setTimeout(function () { var e = $("#" + id); if (!e) { console.log('no', id, e); return; } $('html, body').scrollTop(e.offset().top); }); }); }); chart.selectAll('.labels') .data(keys) .enter() .append('text') .attr('text-anchor', 'end') .attr('x', 0) .attr('dx', '-.5em') .attr('dy', '.25em') .attr('y', function (d, i) { return (i + .5) * barheight; }) .text(function (d) { return d; }); chart.selectAll('.sep') .data(values) .enter() .append('rect') .attr('y', function (d, i) { return (i + 1) * barheight; }) .attr('height', 1) .attr('x', 0) .attr('width', width) .on('mousemove.x', mousemove_x); function mousemove_x() { var x = xScale.invert(d3.mouse(this)[0]); time_legend .text(tsdbFormat(x)); } } ; } }; }); var fmtUnits = ['', 'k', 'M', 'G', 'T', 'P', 'E']; function nfmt(s, mult, suffix, opts) { opts = opts || {}; var n = parseFloat(s); if (isNaN(n) && typeof s === 'string') { return s; } if (opts.round) n = Math.round(n); if (!n) return suffix ? '0 ' + suffix : '0'; if (isNaN(n) || !isFinite(n)) return '-'; var a = Math.abs(n); if (a >= 1) { var number = Math.floor(Math.log(a) / Math.log(mult)); a /= Math.pow(mult, Math.floor(number)); if (fmtUnits[number]) { suffix = fmtUnits[number] + suffix; } } var r = a.toFixed(5); if (a < 1e-5) { r = a.toString(); } var neg = n < 0 ? '-' : ''; return neg + (+r) + suffix; } bosunApp.filter('nfmt', function () { return function (s) { return nfmt(s, 1000, '', {}); }; }); bosunApp.filter('bytes', function () { return function (s) { return nfmt(s, 1024, 'B', { round: true }); }; }); bosunApp.filter('bits', function () { return function (s) { return nfmt(s, 1024, 'b', { round: true }); }; }); bosunApp.directive('elastic', [ '$timeout', function ($timeout) { return { restrict: 'A', link: function ($scope, element) { $scope.initialHeight = $scope.initialHeight || element[0].style.height; var resize = function () { element[0].style.height = $scope.initialHeight; element[0].style.height = "" + element[0].scrollHeight + "px"; }; element.on("input change", resize); $timeout(resize, 0); } }; } ]); bosunApp.directive('tsGraph', ['$window', 'nfmtFilter', function ($window, fmtfilter) { var margin = { top: 10, right: 10, bottom: 30, left: 80 }; return { scope: { data: '=', height: '=', generator: '=', brushStart: '=bstart', brushEnd: '=bend', enableBrush: '@', max: '=', min: '=', normalize: '=' }, link: function (scope, elem, attrs) { var valueIdx = 1; if (scope.normalize) { valueIdx = 2; } var svgHeight = +scope.height || 150; var height = svgHeight - margin.top - margin.bottom; var svgWidth; var width; var yScale = d3.scale.linear().range([height, 0]); var xScale = d3.time.scale.utc(); var xAxis = d3.svg.axis() .orient('bottom'); var yAxis = d3.svg.axis() .scale(yScale) .orient('left') .ticks(Math.min(10, height / 20)) .tickFormat(fmtfilter); var line; switch (scope.generator) { case 'area': line = d3.svg.area(); break; default: line = d3.svg.line(); } var brush = d3.svg.brush() .x(xScale) .on('brush', brushed); var top = d3.select(elem[0]) .append('svg') .attr('height', svgHeight) .attr('width', '100%'); var svg = top .append('g') .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); var defs = svg.append('defs') .append('clipPath') .attr('id', 'clip') .append('rect') .attr('height', height); var chart = svg.append('g') .attr('pointer-events', 'all') .attr('clip-path', 'url(#clip)'); svg.append('g') .attr('class', 'x axis') .attr('transform', 'translate(0,' + height + ')'); svg.append('g') .attr('class', 'y axis'); var paths = chart.append('g'); chart.append('g') .attr('class', 'x brush'); top.append('rect') .style('opacity', 0) .attr('x', 0) .attr('y', 0) .attr('height', height) .attr('width', margin.left) .style('cursor', 'pointer') .on('click', yaxisToggle); var legendTop = d3.select(elem[0]).append('div'); var xloc = legendTop.append('div'); xloc.style('float', 'left'); var brushText = legendTop.append('div'); brushText.style('float', 'right'); var legend = d3.select(elem[0]).append('div'); legend.style('clear', 'both'); var color = d3.scale.ordinal().range([ '#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#a65628', '#f781bf', '#999999', ]); var mousex = 0; var mousey = 0; var oldx = 0; var hover = svg.append('g') .attr('class', 'hover') .style('pointer-events', 'none') .style('display', 'none'); var hoverPoint = hover.append('svg:circle') .attr('r', 5); var hoverRect = hover.append('svg:rect') .attr('fill', 'white'); var hoverText = hover.append('svg:text') .style('font-size', '12px'); var focus = svg.append('g') .attr('class', 'focus') .style('pointer-events', 'none'); focus.append('line'); var yaxisZero = false; function yaxisToggle() { yaxisZero = !yaxisZero; draw(); } var drawLegend = _.throttle(function (normalizeIdx) { var names = legend.selectAll('.series') .data(scope.data, function (d) { return d.Name; }); names.enter() .append('div') .attr('class', 'series'); names.exit() .remove(); var xi = xScale.invert(mousex); xloc.text('Time: ' + fmtTime(xi)); var t = xi.getTime() / 1000; var minDist = width + height; var minName, minColor; var minX, minY; names .each(function (d) { var idx = bisect(d.Data, t); if (idx >= d.Data.length) { idx = d.Data.length - 1; } var e = d3.select(this); var pt = d.Data[idx]; if (pt) { e.attr('title', pt[normalizeIdx]); e.text(d.Name + ': ' + fmtfilter(pt[1])); var ptx = xScale(pt[0] * 1000); var pty = yScale(pt[normalizeIdx]); var ptd = Math.sqrt(Math.pow(ptx - mousex, 2) + Math.pow(pty - mousey, 2)); if (ptd < minDist) { minDist = ptd; minX = ptx; minY = pty; minName = d.Name + ': ' + pt[1]; minColor = color(d.Name); } } }) .style('color', function (d) { return color(d.Name); }); hover .attr('transform', 'translate(' + minX + ',' + minY + ')'); hoverPoint.style('fill', minColor); hoverText .text(minName) .style('fill', minColor); var isRight = minX > width / 2; var isBottom = minY > height / 2; hoverText .attr('x', isRight ? -5 : 5) .attr('y', isBottom ? -8 : 15) .attr('text-anchor', isRight ? 'end' : 'start'); var node = hoverText.node(); var bb = node.getBBox(); hoverRect .attr('x', bb.x - 1) .attr('y', bb.y - 1) .attr('height', bb.height + 2) .attr('width', bb.width + 2); var x = mousex; if (x > width) { x = 0; } focus.select('line') .attr('x1', x) .attr('x2', x) .attr('y1', 0) .attr('y2', height); if (extentStart) { var s = extentStart; if (extentEnd != extentStart) { s += ' - ' + extentEnd; s += ' (' + extentDiff + ')'; } brushText.text(s); } }, 50); scope.$watch('data', update); var w = angular.element($window); scope.$watch(function () { return w.width(); }, resize, true); w.bind('resize', function () { scope.$apply(); }); function resize() { svgWidth = elem.width(); if (svgWidth <= 0) { return; } width = svgWidth - margin.left - margin.right; xScale.range([0, width]); xAxis.scale(xScale); if (!mousex) { mousex = width + 1; } svg.attr('width', svgWidth); defs.attr('width', width); xAxis.ticks(width / 60); draw(); } var oldx = 0; var bisect = d3.bisector(function (d) { return d[0]; }).left; function update(v) { if (!angular.isArray(v) || v.length == 0) { return; } resize(); } function draw() { if (!scope.data) { return; } if (scope.normalize) { valueIdx = 2; } function mousemove() { var pt = d3.mouse(this); mousex = pt[0]; mousey = pt[1]; drawLegend(valueIdx); } scope.data.map(function (data, i) { var max = d3.max(data.Data, function (d) { return d[1]; }); data.Data.map(function (d, j) { d.push(d[1] / max * 100 || 0); }); }); line.y(function (d) { return yScale(d[valueIdx]); }); line.x(function (d) { return xScale(d[0] * 1000); }); var xdomain = [ d3.min(scope.data, function (d) { return d3.min(d.Data, function (c) { return c[0]; }); }) * 1000, d3.max(scope.data, function (d) { return d3.max(d.Data, function (c) { return c[0]; }); }) * 1000, ]; if (!oldx) { oldx = xdomain[1]; } xScale.domain(xdomain); var ymin = d3.min(scope.data, function (d) { return d3.min(d.Data, function (c) { return c[1]; }); }); var ymax = d3.max(scope.data, function (d) { return d3.max(d.Data, function (c) { return c[valueIdx]; }); }); var diff = (ymax - ymin) / 50; if (!diff) { diff = 1; } ymin -= diff; ymax += diff; if (yaxisZero) { if (ymin > 0) { ymin = 0; } else if (ymax < 0) { ymax = 0; } } var ydomain = [ymin, ymax]; if (angular.isNumber(scope.min)) { ydomain[0] = +scope.min; } if (angular.isNumber(scope.max)) { ydomain[valueIdx] = +scope.max; } yScale.domain(ydomain); if (scope.generator == 'area') { line.y0(yScale(0)); } svg.select('.x.axis') .transition() .call(xAxis); svg.select('.y.axis') .transition() .call(yAxis); svg.append('text') .attr("class", "ylabel") .attr("transform", "rotate(-90)") .attr("y", -margin.left) .attr("x", -(height / 2)) .attr("dy", "1em") .text(_.uniq(scope.data.map(function (v) { return v.Unit; })).join("; ")); var queries = paths.selectAll('.line') .data(scope.data, function (d) { return d.Name; }); switch (scope.generator) { case 'area': queries.enter() .append('path') .attr('stroke', function (d) { return color(d.Name); }) .attr('class', 'line') .style('fill', function (d) { return color(d.Name); }); break; default: queries.enter() .append('path') .attr('stroke', function (d) { return color(d.Name); }) .attr('class', 'line'); } queries.exit() .remove(); queries .attr('d', function (d) { return line(d.Data); }) .attr('transform', null) .transition() .ease('linear') .attr('transform', 'translate(' + (xScale(oldx) - xScale(xdomain[1])) + ')'); chart.select('.x.brush') .call(brush) .selectAll('rect') .attr('height', height) .on('mouseover', function () { hover.style('display', 'block'); }) .on('mouseout', function () { hover.style('display', 'none'); }) .on('mousemove', mousemove); chart.select('.x.brush .extent') .style('stroke', '#fff') .style('fill-opacity', '.125') .style('shape-rendering', 'crispEdges'); oldx = xdomain[1]; drawLegend(valueIdx); } ; var extentStart; var extentEnd; var extentDiff; function brushed() { var extent = brush.extent(); extentStart = datefmt(extent[0]); extentEnd = datefmt(extent[1]); extentDiff = fmtDuration(moment(extent[1]).diff(moment(extent[0]))); drawLegend(valueIdx); if (scope.enableBrush && extentEnd != extentStart) { scope.brushStart = extentStart; scope.brushEnd = extentEnd; scope.$apply(); } } var mfmt = 'YYYY/MM/DD-HH:mm:ss'; function datefmt(d) { return moment(d).utc().format(mfmt); } } }; }]); bosunControllers.controller('ExprCtrl', ['$scope', '$http', '$location', '$route', function ($scope, $http, $location, $route) { var search = $location.search(); var current; try { current = atob(search.expr); } catch (e) { current = ''; } if (!current) { $location.search('expr', btoa('avg(q("avg:rate:os.cpu{host=*bosun*}", "5m", "")) > 80')); return; } $scope.date = search.date || ''; $scope.time = search.time || ''; $scope.expr = current; $scope.running = current; $scope.tab = search.tab || 'results'; $scope.animate(); $http.post('/api/expr?' + 'date=' + encodeURIComponent($scope.date) + '&time=' + encodeURIComponent($scope.time), current) .success(function (data) { $scope.result = data.Results; $scope.queries = data.Queries; $scope.result_type = data.Type; if (data.Type == 'series') { $scope.svg_url = '/api/egraph/' + btoa(current) + '.svg?now=' + Math.floor(Date.now() / 1000); $scope.graph = toChart(data.Results); } $scope.running = ''; }) .error(function (error) { $scope.error = error; $scope.running = ''; }) .finally(function () { $scope.stop(); }); $scope.set = function () { $location.search('expr', btoa($scope.expr)); $location.search('date', $scope.date || null); $location.search('time', $scope.time || null); $route.reload(); }; function toChart(res) { var graph = []; angular.forEach(res, function (d, idx) { var data = []; angular.forEach(d.Value, function (val, ts) { data.push([+ts, val]); }); if (data.length == 0) { return; } var name = '{'; angular.forEach(d.Group, function (tagv, tagk) { if (name.length > 1) { name += ','; } name += tagk + '=' + tagv; }); name += '}'; var series = { Data: data, Name: name }; graph[idx] = series; }); return graph; } $scope.keydown = function ($event) { if ($event.shiftKey && $event.keyCode == 13) { $scope.set(); } }; }]); var TagSet = (function () { function TagSet() { } return TagSet; })(); var TagV = (function () { function TagV() { } return TagV; })(); var RateOptions = (function () { function RateOptions() { } return RateOptions; })(); var Query = (function () { function Query(q) { this.aggregator = q && q.aggregator || 'sum'; this.metric = q && q.metric || ''; this.rate = q && q.rate || false; this.rateOptions = q && q.rateOptions || new RateOptions; if (q && !q.derivative) { // back compute derivative from q if (!this.rate) { this.derivative = 'gauge'; } else if (this.rateOptions.counter) { this.derivative = 'counter'; } else { this.derivative = 'rate'; } } else { this.derivative = q && q.derivative || 'auto'; } this.ds = q && q.ds || ''; this.dstime = q && q.dstime || ''; this.tags = q && q.tags || new TagSet; this.setDs(); this.setDerivative(); } Query.prototype.setDs = function () { if (this.dstime && this.ds) { this.downsample = this.dstime + '-' + this.ds; } else { this.downsample = ''; } }; Query.prototype.setDerivative = function () { var max = this.rateOptions.counterMax; this.rate = false; this.rateOptions = new RateOptions(); switch (this.derivative) { case "rate": this.rate = true; break; case "counter": this.rate = true; this.rateOptions.counter = true; this.rateOptions.counterMax = max; this.rateOptions.resetValue = 1; break; case "gauge": this.rate = false; break; } }; return Query; })(); var Request = (function () { function Request() { this.start = '1h-ago'; this.queries = []; } Request.prototype.prune = function () { var _this = this; for (var i = 0; i < this.queries.length; i++) { angular.forEach(this.queries[i], function (v, k) { var qi = _this.queries[i]; switch (typeof v) { case "string": if (!v) { delete qi[k]; } break; case "boolean": if (!v) { delete qi[k]; } break; case "object": if (Object.keys(v).length == 0) { delete qi[k]; } break; } }); } }; return Request; })(); var graphRefresh; bosunControllers.controller('GraphCtrl', ['$scope', '$http', '$location', '$route', '$timeout', function ($scope, $http, $location, $route, $timeout) { $scope.aggregators = ["sum", "min", "max", "avg", "dev", "zimsum", "mimmin", "minmax"]; $scope.dsaggregators = ["", "sum", "min", "max", "avg", "dev", "zimsum", "mimmin", "minmax"]; $scope.rate_options = ["auto", "gauge", "counter", "rate"]; $scope.canAuto = {}; var search = $location.search(); var j = search.json; if (search.b64) { j = atob(search.b64); } var request = j ? JSON.parse(j) : new Request; $scope.index = parseInt($location.hash()) || 0; $scope.tagvs = []; $scope.sorted_tagks = []; $scope.query_p = []; angular.forEach(request.queries, function (q, i) { $scope.query_p[i] = new Query(q); }); $scope.start = request.start; $scope.end = request.end; $scope.autods = search.autods != 'false'; $scope.refresh = search.refresh == 'true'; $scope.normalize = search.normalize == 'true'; if (search.min) { $scope.min = +search.min; } if (search.max) { $scope.max = +search.max; } var duration_map = { "s": "s", "m": "m", "h": "h", "d": "d", "w": "w", "n": "M", "y": "y" }; var isRel = /^(\d+)(\w)-ago$/; function RelToAbs(m) { return moment().utc().subtract(parseFloat(m[1]), duration_map[m[2]]).format(); } function AbsToRel(s) { //Not strict parsing of the time format. For example, just "2014" will be valid var t = moment.utc(s, moment.defaultFormat).fromNow(); return t; } function SwapTime(s) { if (!s) { return moment().utc().format(); } var m = isRel.exec(s); if (m) { return RelToAbs(m); } return AbsToRel(s); } $scope.SwitchTimes = function () { $scope.start = SwapTime($scope.start); $scope.end = SwapTime($scope.end); }; $scope.AddTab = function () { $scope.index = $scope.query_p.length; $scope.query_p.push(new Query); }; $scope.setIndex = function (i) { $scope.index = i; }; $scope.GetTagKByMetric = function (index) { $scope.tagvs[index] = new TagV; var metric = $scope.query_p[index].metric; if (!metric) { $scope.canAuto[metric] = true; return; } $http.get('/api/tagk/' + metric) .success(function (data) { var q = $scope.query_p[index]; var tags = new TagSet; q.metric_tags = {}; for (var i = 0; i < data.length; i++) { var d = data[i]; q.metric_tags[d] = true; if (q.tags) { tags[d] = q.tags[d]; } if (!tags[d]) { tags[d] = ''; } GetTagVs(d, index); } angular.forEach(q.tags, function (val, key) { if (val) { tags[key] = val; } }); q.tags = tags; // Make sure host is always the first tag. $scope.sorted_tagks[index] = Object.keys(tags); $scope.sorted_tagks[index].sort(function (a, b) { if (a == 'host') { return -1; } else if (b == 'host') { return 1; } return a.localeCompare(b); }); }) .error(function (error) { $scope.error = 'Unable to fetch metrics: ' + error; }); $http.get('/api/metadata/get?metric=' + metric) .success(function (data) { var canAuto = false; angular.forEach(data, function (val) { if (val.Metric == metric && val.Name == 'rate') { canAuto = true; } }); $scope.canAuto[metric] = canAuto; }) .error(function (err) { $scope.error = err; }); }; if ($scope.query_p.length == 0) { $scope.AddTab(); } $http.get('/api/metric') .success(function (data) { $scope.metrics = data; }) .error(function (error) { $scope.error = 'Unable to fetch metrics: ' + error; }); function GetTagVs(k, index) { $http.get('/api/tagv/' + k + '/' + $scope.query_p[index].metric) .success(function (data) { data.sort(); $scope.tagvs[index][k] = data; }) .error(function (error) { $scope.error = 'Unable to fetch metrics: ' + error; }); } function getRequest() { request = new Request; request.start = $scope.start; request.end = $scope.end; angular.forEach($scope.query_p, function (p) { if (!p.metric) { return; } var q = new Query(p); var tags = q.tags; q.tags = new TagSet; angular.forEach(tags, function (v, k) { if (v && k) { q.tags[k] = v; } }); request.queries.push(q); }); return request; } $scope.Query = function () { var r = getRequest(); angular.forEach($scope.query_p, function (q, index) { var m = q.metric_tags; if (!m) { return; } angular.forEach(q.tags, function (key, tag) { if (m[tag]) { return; } delete r.queries[index].tags[tag]; }); }); r.prune(); $location.search('b64', btoa(JSON.stringify(r))); $location.search('autods', $scope.autods ? undefined : 'false'); $location.search('refresh', $scope.refresh ? 'true' : undefined); $location.search('normalize', $scope.normalize ? 'true' : undefined); var min = angular.isNumber($scope.min) ? $scope.min.toString() : null; var max = angular.isNumber($scope.max) ? $scope.max.toString() : null; $location.search('min', min); $location.search('max', max); $route.reload(); }; request = getRequest(); if (!request.queries.length) { return; } var autods = $scope.autods ? '&autods=' + $('#chart').width() : ''; function getMetricMeta(metric) { $http.get('/api/metadata/metrics?metric=' + encodeURIComponent(metric)) .success(function (data) { if (Object.keys(data).length == 1) { $scope.meta[metric] = data[metric]; } }) .error(function (error) { console.log("Error getting metadata for metric " + metric); }); } function get(noRunning) { $timeout.cancel(graphRefresh); if (!noRunning) { $scope.running = 'Running'; } var autorate = ''; $scope.meta = {}; for (var i = 0; i < request.queries.length; i++) { if (request.queries[i].derivative == 'auto') { autorate += '&autorate=' + i; } getMetricMeta(request.queries[i].metric); } var min = angular.isNumber($scope.min) ? '&min=' + encodeURIComponent($scope.min.toString()) : ''; var max = angular.isNumber($scope.max) ? '&max=' + encodeURIComponent($scope.max.toString()) : ''; $scope.animate(); $scope.queryTime = ''; if (request.end && !isRel.exec(request.end)) { var t = moment.utc(request.end, moment.defaultFormat); $scope.queryTime = '&date=' + t.format('YYYY-MM-DD'); $scope.queryTime += '&time=' + t.format('HH:mm'); } $http.get('/api/graph?' + 'b64=' + encodeURIComponent(btoa(JSON.stringify(request))) + autods + autorate + min + max) .success(function (data) { $scope.result = data.Series; if (!$scope.result) { $scope.warning = 'No Results'; } else { $scope.warning = ''; } $scope.queries = data.Queries; $scope.running = ''; $scope.error = ''; var u = $location.absUrl(); u = u.substr(0, u.indexOf('?')) + '?'; u += 'b64=' + search.b64 + autods + autorate + min + max; $scope.url = u; }) .error(function (error) { $scope.error = error; $scope.running = ''; }) .finally(function () { $scope.stop(); if ($scope.refresh) { graphRefresh = $timeout(function () { get(true); }, 5000); } ; }); } ; get(false); }]); bosunApp.directive('tsPopup', function () { return { restrict: 'E', scope: { url: '=' }, template: '<button class="btn btn-default" data-html="true" data-placement="bottom">embed</button>', link: function (scope, elem, attrs) { var button = $('button', elem); scope.$watch(attrs.url, function (url) { if (!url) { return; } var text = '<input type="text" onClick="this.select();" readonly="readonly" value="&lt;a href=&quot;' + url + '&quot;&gt;&lt;img src=&quot;' + url + '&.png=png&quot;&gt;&lt;/a&gt;">'; button.popover({ content: text }); }); } }; }); bosunApp.directive('tsAlertHistory', function () { return { templateUrl: '/partials/alerthistory.html' }; }); bosunControllers.controller('HistoryCtrl', ['$scope', '$http', '$location', '$route', function ($scope, $http, $location, $route) { var search = $location.search(); var keys = {}; if (angular.isArray(search.key)) { angular.forEach(search.key, function (v) { keys[v] = true; }); } else { keys[search.key] = true; } var params = Object.keys(keys).map(function (v) { return 'ak=' + encodeURIComponent(v); }).join('&'); $http.get('/api/status?' + params) .success(function (data) { var selected_alerts = {}; angular.forEach(data, function (v, ak) { if (!keys[ak]) { return; } v.History.map(function (h) { h.Time = moment.utc(h.Time); }); angular.forEach(v.History, function (h, i) { if (i + 1 < v.History.length) { h.EndTime = v.History[i + 1].Time; } else { h.EndTime = moment.utc(); } }); selected_alerts[ak] = { History: v.History.reverse() }; }); if (Object.keys(selected_alerts).length > 0) { $scope.alert_history = selected_alerts; } else { $scope.error = 'No Matching Alerts Found'; } }) .error(function (err) { $scope.error = err; }); }]); bosunControllers.controller('HostCtrl', ['$scope', '$http', '$location', '$route', function ($scope, $http, $location, $route) { var search = $location.search(); $scope.host = search.host; $scope.time = search.time; $scope.tab = search.tab || "stats"; $scope.idata = []; $scope.fsdata = []; $scope.metrics = []; var currentURL = $location.url(); $scope.mlink = function (m) { var r = new Request(); var q = new Query(); q.metric = m; q.tags = { 'host': $scope.host }; r.queries.push(q); return r; }; $scope.setTab = function (t) { $location.search('tab', t); $scope.tab = t; }; $http.get('/api/metric/host/' + $scope.host) .success(function (data) { $scope.metrics = data || []; }); var start = moment().utc().subtract(parseDuration($scope.time)); function parseDuration(v) { var pattern = /(\d+)(d|y|n|h|m|s)-ago/; var m = pattern.exec(v); return moment.duration(parseInt(m[1]), m[2].replace('n', 'M')); } $http.get('/api/metadata/get?tagk=host&tagv=' + encodeURIComponent($scope.host)) .success(function (data) { $scope.metadata = _.filter(data, function (i) { return moment.utc(i.Time) > start; }); }); var autods = '&autods=100'; var cpu_r = new Request(); cpu_r.start = $scope.time; cpu_r.queries = [ new Query({ metric: 'os.cpu', derivative: 'counter', tags: { host: $scope.host } }) ]; $http.get('/api/graph?' + 'json=' + encodeURIComponent(JSON.stringify(cpu_r)) + autods) .success(function (data) { if (!data.Series) { return; } data.Series[0].Name = 'Percent Used'; $scope.cpu = data.Series; }); var mem_r = new Request(); mem_r.start = $scope.time; mem_r.queries.push(new Query({ metric: "os.mem.total", tags: { host: $scope.host } })); mem_r.queries.push(new Query({ metric: "os.mem.used", tags: { host: $scope.host } })); $http.get('/api/graph?' + 'json=' + encodeURIComponent(JSON.stringify(mem_r)) + autods) .success(function (data) { if (!data.Series) { return; } data.Series[1].Name = "Used"; $scope.mem_total = Math.max.apply(null, data.Series[0].Data.map(function (d) { return d[1]; })); $scope.mem = [data.Series[1]]; }); $http.get('/api/tagv/iface/os.net.bytes?host=' + $scope.host) .success(function (data) { angular.forEach(data, function (i, idx) { $scope.idata[idx] = { Name: i }; }); function next(idx) { var idata = $scope.idata[idx]; if (!idata || currentURL != $location.url()) { return; } var net_bytes_r = new Request(); net_bytes_r.start = $scope.time; net_bytes_r.queries = [ new Query({ metric: "os.net.bytes", rate: true, rateOptions: { counter: true, resetValue: 1 }, tags: { host: $scope.host, iface: idata.Name, direction: "*" } }) ]; $http.get('/api/graph?' + 'json=' + encodeURIComponent(JSON.stringify(net_bytes_r)) + autods) .success(function (data) { if (!data.Series) { return; } angular.forEach(data.Series, function (d) { d.Data = d.Data.map(function (dp) { return [dp[0], dp[1] * 8]; }); if (d.Name.indexOf("direction=out") != -1) { d.Data = d.Data.map(function (dp) { return [dp[0], dp[1] * -1]; }); d.Name = "out"; } else { d.Name = "in"; } }); $scope.idata[idx].Data = data.Series; }) .finally(function () { next(idx + 1); }); } next(0); }); $http.get('/api/tagv/disk/os.disk.fs.space_total?host=' + $scope.host) .success(function (data) { angular.forEach(data, function (i, idx) { if (i == '/dev/shm') { return; } var fs_r = new Request(); fs_r.start = $scope.time; fs_r.queries.push(new Query({ metric: "os.disk.fs.space_total", tags: { host: $scope.host, disk: i } })); fs_r.queries.push(new Query({ metric: "os.disk.fs.space_used", tags: { host: $scope.host, disk: i } })); $scope.fsdata[idx] = { Name: i }; $http.get('/api/graph?' + 'json=' + encodeURIComponent(JSON.stringify(fs_r)) + autods) .success(function (data) { if (!data.Series) { return; } data.Series[1].Name = 'Used'; var total = Math.max.apply(null, data.Series[0].Data.map(function (d) { return d[1]; })); var c_val = data.Series[1].Data.slice(-1)[0][1]; var percent_used = c_val / total * 100; $scope.fsdata[idx].total = total; $scope.fsdata[idx].c_val = c_val; $scope.fsdata[idx].percent_used = percent_used; $scope.fsdata[idx].Data = [data.Series[1]]; }); }); }); }]); bosunControllers.controller('IncidentCtrl', ['$scope', '$http', '$location', '$route', function ($scope, $http, $location, $route) { var search = $location.search(); var id = search.id; if (!id) { $scope.error = "must supply incident id as query parameter"; return; } $http.get('/api/incidents/events?id=' + id) .success(function (data) { $scope.incident = data.Incident; $scope.events = data.Events; $scope.actions = data.Actions; }) .error(function (err) { $scope.error = err; }); }]); bosunControllers.controller('ItemsCtrl', ['$scope', '$http', function ($scope, $http) { $http.get('/api/metric') .success(function (data) { $scope.metrics = data; }) .error(function (error) { $scope.status = 'Unable to fetch metrics: ' + error; }); $http.get('/api/tagv/host?since=default') .success(function (data) { $scope.hosts = data; }) .error(function (error) { $scope.status = 'Unable to fetch hosts: ' + error; }); }]); var Tag = (function () { function Tag() { } return Tag; })(); var DP = (function () { function DP() { } return DP; })(); bosunControllers.controller('PutCtrl', ['$scope', '$http', '$route', function ($scope, $http, $route) { $scope.tags = [new Tag]; var dp = new DP; dp.k = moment().utc().format(); $scope.dps = [dp]; $http.get('/api/metric') .success(function (data) { $scope.metrics = data; }) .error(function (error) { $scope.error = 'Unable to fetch metrics: ' + error; }); $scope.Submit = function () { var data = []; var tags = {}; angular.forEach($scope.tags, function (v, k) { if (v.k || v.v) { tags[v.k] = v.v; } }); angular.forEach($scope.dps, function (v, k) { if (v.k && v.v) { var ts = parseInt(moment.utc(v.k, tsdbDateFormat).format('X')); data.push({ metric: $scope.metric, timestamp: ts, value: parseFloat(v.v), tags: tags }); } }); $scope.running = 'submitting data...'; $scope.success = ''; $scope.error = ''; $http.post('/api/put', data) .success(function () { $scope.running = ''; $scope.success = 'Data Submitted'; }) .error(function (error) { $scope.running = ''; $scope.error = error.error.message; }); }; $scope.AddTag = function () { var last = $scope.tags[$scope.tags.length - 1]; if (last.k && last.v) { $scope.tags.push(new Tag); } }; $scope.AddDP = function () { var last = $scope.dps[$scope.dps.length - 1]; if (last.k && last.v) { var dp = new DP;<|fim▁hole|> $scope.GetTagKByMetric = function () { $http.get('/api/tagk/' + $scope.metric) .success(function (data) { if (!angular.isArray(data)) { return; } $scope.tags = [new Tag]; for (var i = 0; i < data.length; i++) { var t = new Tag; t.k = data[i]; $scope.tags.push(t); } }) .error(function (error) { $scope.error = 'Unable to fetch metrics: ' + error; }); }; }]); bosunControllers.controller('SilenceCtrl', ['$scope', '$http', '$location', '$route', function ($scope, $http, $location, $route) { var search = $location.search(); $scope.start = search.start; $scope.end = search.end; $scope.duration = search.duration; $scope.alert = search.alert; $scope.hosts = search.hosts; $scope.tags = search.tags; $scope.edit = search.edit; $scope.forget = search.forget; $scope.user = getUser(); $scope.message = search.message; if (!$scope.end && !$scope.duration) { $scope.duration = '1h'; } function filter(data, startBefore, startAfter, endAfter, endBefore, limit) { var ret = {}; var count = 0; _.each(data, function (v, name) { if (limit && count >= limit) { return; } var s = moment(v.Start).utc(); var e = moment(v.End).utc(); if (startBefore && s > startBefore) { return; } if (startAfter && s < startAfter) { return; } if (endAfter && e < endAfter) { return; } if (endBefore && e > endBefore) { return; } ret[name] = v; }); return ret; } function get() { $http.get('/api/silence/get') .success(function (data) { $scope.silences = []; var now = moment.utc(); $scope.silences.push({ name: 'Active', silences: filter(data, now, null, now, null, 0) }); $scope.silences.push({ name: 'Upcoming', silences: filter(data, null, now, null, null, 0) }); $scope.silences.push({ name: 'Past', silences: filter(data, null, null, null, now, 25) }); }) .error(function (error) { $scope.error = error; }); } get(); function getData() { var tags = ($scope.tags || '').split(','); if ($scope.hosts) { tags.push('host=' + $scope.hosts.split(/[ ,|]+/).join('|')); } tags = tags.filter(function (v) { return v != ""; }); var data = { start: $scope.start, end: $scope.end, duration: $scope.duration, alert: $scope.alert, tags: tags.join(','), edit: $scope.edit, forget: $scope.forget ? 'true' : null, user: $scope.user, message: $scope.message }; return data; } var any = search.start || search.end || search.duration || search.alert || search.hosts || search.tags || search.forget; var state = getData(); $scope.change = function () { $scope.disableConfirm = true; }; if (any) { $scope.error = null; $http.post('/api/silence/set', state) .success(function (data) { if (!data) { data = { '(none)': false }; } $scope.testSilences = data; }) .error(function (error) { $scope.error = error; }); } $scope.test = function () { setUser($scope.user); $location.search('start', $scope.start || null); $location.search('end', $scope.end || null); $location.search('duration', $scope.duration || null); $location.search('alert', $scope.alert || null); $location.search('hosts', $scope.hosts || null); $location.search('tags', $scope.tags || null); $location.search('forget', $scope.forget || null); $location.search('message', $scope.message || null); $route.reload(); }; $scope.confirm = function () { $scope.error = null; $scope.testSilences = null; state.confirm = 'true'; $http.post('/api/silence/set', state) .error(function (error) { $scope.error = error; }) .finally(get); }; $scope.clear = function (id) { if (!window.confirm('Clear this silence?')) { return; } $scope.error = null; $http.post('/api/silence/clear?id=' + id, {}) .error(function (error) { $scope.error = error; }) .finally(get); }; $scope.time = function (v) { var m = moment(v).utc(); return m.format(); }; }]); bosunApp.directive('tsAckGroup', ['$location', function ($location) { return { scope: { ack: '=', groups: '=tsAckGroup', schedule: '=', timeanddate: '=' }, templateUrl: '/partials/ackgroup.html', link: function (scope, elem, attrs) { scope.canAckSelected = scope.ack == 'Needs Acknowledgement'; scope.panelClass = scope.$parent.panelClass; scope.btoa = scope.$parent.btoa; scope.encode = scope.$parent.encode; scope.shown = {}; scope.collapse = function (i) { scope.shown[i] = !scope.shown[i]; }; scope.click = function ($event, idx) { scope.collapse(idx); if ($event.shiftKey && scope.schedule.checkIdx != undefined) { var checked = scope.groups[scope.schedule.checkIdx].checked; var start = Math.min(idx, scope.schedule.checkIdx); var end = Math.max(idx, scope.schedule.checkIdx); for (var i = start; i <= end; i++) { if (i == idx) { continue; } scope.groups[i].checked = checked; } } scope.schedule.checkIdx = idx; scope.update(); }; scope.select = function (checked) { for (var i = 0; i < scope.groups.length; i++) { scope.groups[i].checked = checked; } scope.update(); }; scope.update = function () { scope.canCloseSelected = true; scope.canForgetSelected = true; scope.anySelected = false; for (var i = 0; i < scope.groups.length; i++) { var g = scope.groups[i]; if (!g.checked) { continue; } scope.anySelected = true; if (g.Active && g.Status != 'unknown' && g.Status != 'error') { scope.canCloseSelected = false; } if (g.Status != 'unknown') { scope.canForgetSelected = false; } } }; scope.multiaction = function (type) { var keys = []; angular.forEach(scope.groups, function (group) { if (!group.checked) { return; } if (group.AlertKey) { keys.push(group.AlertKey); } angular.forEach(group.Children, function (child) { keys.push(child.AlertKey); }); }); scope.$parent.setKey("action-keys", keys); $location.path("action"); $location.search("type", type); }; scope.history = function () { var url = '/history?'; angular.forEach(scope.groups, function (group) { if (!group.checked) { return; } if (group.AlertKey) { url += '&key=' + encodeURIComponent(group.AlertKey); } angular.forEach(group.Children, function (child) { url += '&key=' + encodeURIComponent(child.AlertKey); }); }); return url; }; } }; }]); bosunApp.directive('tsState', ['$sce', '$http', function ($sce, $http) { return { templateUrl: '/partials/alertstate.html', link: function (scope, elem, attrs) { scope.name = scope.child.AlertKey; scope.state = scope.child.State; scope.action = function (type) { var key = encodeURIComponent(scope.name); return '/action?type=' + type + '&key=' + key; }; var loadedBody = false; scope.toggle = function () { scope.show = !scope.show; if (scope.show && !loadedBody) { scope.state.Body = "loading..."; loadedBody = true; $http.get('/api/status?ak=' + scope.child.AlertKey) .success(function (data) { var body = data[scope.child.AlertKey].Body; scope.state.Body = $sce.trustAsHtml(body); }) .error(function (err) { scope.state.Body = "Error loading template body: " + err; }); } }; scope.zws = function (v) { if (!v) { return ''; } return v.replace(/([,{}()])/g, '$1\u200b'); }; scope.state.Touched = moment(scope.state.Touched).utc(); angular.forEach(scope.state.History, function (v, k) { v.Time = moment(v.Time).utc(); }); scope.state.last = scope.state.History[scope.state.History.length - 1]; if (scope.state.Actions && scope.state.Actions.length > 0) { scope.state.LastAction = scope.state.Actions[0]; } scope.state.RuleUrl = '/config?' + 'alert=' + encodeURIComponent(scope.state.Alert) + '&fromDate=' + encodeURIComponent(scope.state.last.Time.format("YYYY-MM-DD")) + '&fromTime=' + encodeURIComponent(scope.state.last.Time.format("HH:mm")); var groups = []; angular.forEach(scope.state.Group, function (v, k) { groups.push(k + "=" + v); }); if (groups.length > 0) { scope.state.RuleUrl += '&template_group=' + encodeURIComponent(groups.join(',')); } scope.state.Body = $sce.trustAsHtml(scope.state.Body); } }; }]); bosunApp.directive('tsAck', function () { return { restrict: 'E', templateUrl: '/partials/ack.html' }; }); bosunApp.directive('tsClose', function () { return { restrict: 'E', templateUrl: '/partials/close.html' }; }); bosunApp.directive('tsForget', function () { return { restrict: 'E', templateUrl: '/partials/forget.html' }; });<|fim▁end|>
dp.k = moment.utc(last.k, tsdbDateFormat).add(15, 'seconds').format(); $scope.dps.push(dp); } };
<|file_name|>fulfillments.update_fulfillment.js<|end_file_name|><|fim▁begin|>// 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** 'use strict';<|fim▁hole|> /** * TODO(developer): Uncomment these variables before running the sample. */ /** * Required. The fulfillment to update. */ // const fulfillment = {} /** * Required. The mask to control which fields get updated. If the mask is not * present, all fields will be updated. */ // const updateMask = {} // Imports the Dialogflow library const {FulfillmentsClient} = require('@google-cloud/dialogflow').v2; // Instantiates a client const dialogflowClient = new FulfillmentsClient(); async function callUpdateFulfillment() { // Construct request const request = { fulfillment, updateMask, }; // Run request const response = await dialogflowClient.updateFulfillment(request); console.log(response); } callUpdateFulfillment(); // [END dialogflow_v2_generated_Fulfillments_UpdateFulfillment_async] } process.on('unhandledRejection', err => { console.error(err.message); process.exitCode = 1; }); main(...process.argv.slice(2));<|fim▁end|>
function main(fulfillment, updateMask) { // [START dialogflow_v2_generated_Fulfillments_UpdateFulfillment_async]
<|file_name|>OutputBindingCard.tsx<|end_file_name|><|fim▁begin|>import i18next from 'i18next'; import { Link } from 'office-ui-fabric-react'; import React, { useContext } from 'react'; import { useTranslation } from 'react-i18next'; import { ReactComponent as OutputSvg } from '../../../../../../images/Common/output.svg'; import { ArmObj } from '../../../../../../models/arm-obj'; import { Binding, BindingDirection } from '../../../../../../models/functions/binding'; import { BindingInfo } from '../../../../../../models/functions/function-binding'; import { FunctionInfo } from '../../../../../../models/functions/function-info'; import PortalCommunicator from '../../../../../../portal-communicator'; import { PortalContext } from '../../../../../../PortalContext'; import { ThemeExtended } from '../../../../../../theme/SemanticColorsExtended'; import { ThemeContext } from '../../../../../../ThemeContext'; import { BindingFormBuilder } from '../../../common/BindingFormBuilder'; import { BindingEditorContext, BindingEditorContextInfo } from '../FunctionIntegrate'; import { getBindingDirection } from '../FunctionIntegrate.utils'; import BindingCard, { createNew, EditableBindingCardProps, editExisting, emptyList } from './BindingCard'; import { listStyle } from './BindingCard.styles'; const OutputBindingCard: React.SFC<EditableBindingCardProps> = props => { const { functionInfo, bindings, readOnly, loadBindingSettings } = props; const { t } = useTranslation(); const theme = useContext(ThemeContext); const portalCommunicator = useContext(PortalContext); const bindingEditorContext = useContext(BindingEditorContext) as BindingEditorContextInfo; const outputs = getOutputBindings(functionInfo.properties.config.bindings); const content = getContent( portalCommunicator, functionInfo, bindings, t, bindingEditorContext, theme, outputs, readOnly, loadBindingSettings ); return <BindingCard title={t('output')} Svg={OutputSvg} content={content} {...props} />; }; const getOutputBindings = (bindings: BindingInfo[]): BindingInfo[] => { const outputBindings = bindings.filter(binding => { return getBindingDirection(binding) === BindingDirection.out; }); return outputBindings ? outputBindings : []; }; const getContent = ( portalCommunicator: PortalCommunicator, functionInfo: ArmObj<FunctionInfo>, bindings: Binding[], t: i18next.TFunction, bindingEditorContext: BindingEditorContextInfo, theme: ThemeExtended, outputBindings: BindingInfo[], readOnly: boolean, loadBindingSettings: (bindingId: string, force: boolean) => Promise<void> ): JSX.Element => { const outputList: JSX.Element[] = outputBindings.map((item, i) => { const name = item.name ? `(${item.name})` : ''; const linkName = `${BindingFormBuilder.getBindingTypeName(item, bindings)} ${name}`; return ( <li key={i.toString()}> <Link onClick={() => { loadBindingSettings( bindings.find(binding => binding.type === item.type && binding.direction === BindingDirection.out)!.id, false ).then(() => { editExisting(portalCommunicator, t, functionInfo, item, bindingEditorContext, BindingDirection.out); }); }}> {linkName} </Link> </li> ); }); const completeOutputList = outputList.length > 0 ? outputList : emptyList(t('integrateNoOutputsDefined')); if (!readOnly) { completeOutputList.push( <li key={'newOutput'}> <Link onClick={() => { const inputs = bindings.filter(binding => binding.direction === BindingDirection.out); Promise.all(inputs.map(binding => loadBindingSettings(binding.id, false))).then(() => { createNew(portalCommunicator, t, functionInfo, bindingEditorContext, BindingDirection.out); }); }}> {t('integrateAddOutput')} </Link> </li> ); } return <ul className={listStyle(theme)}>{completeOutputList}</ul>; };<|fim▁hole|>export default OutputBindingCard;<|fim▁end|>
<|file_name|>error_codes_check.rs<|end_file_name|><|fim▁begin|>//! Checks that all error codes have at least one test to prevent having error //! codes that are silently not thrown by the compiler anymore. use std::collections::HashMap; use std::ffi::OsStr; use std::fs::read_to_string; use std::path::Path; use regex::Regex; // A few of those error codes can't be tested but all the others can and *should* be tested! const EXEMPTED_FROM_TEST: &[&str] = &[ "E0227", "E0279", "E0280", "E0313", "E0377", "E0461", "E0462", "E0464", "E0465", "E0476", "E0482", "E0514", "E0519", "E0523", "E0554", "E0640", "E0717", "E0729", ]; // Some error codes don't have any tests apparently... const IGNORE_EXPLANATION_CHECK: &[&str] = &["E0570", "E0601", "E0602", "E0729"]; // If the file path contains any of these, we don't want to try to extract error codes from it. // // We need to declare each path in the windows version (with backslash). const PATHS_TO_IGNORE_FOR_EXTRACTION: &[&str] = &["src/test/", "src\\test\\", "src/doc/", "src\\doc\\", "src/tools/", "src\\tools\\"]; #[derive(Default, Debug)] struct ErrorCodeStatus { has_test: bool, has_explanation: bool, is_used: bool, } fn check_error_code_explanation( f: &str, error_codes: &mut HashMap<String, ErrorCodeStatus>, err_code: String, ) -> bool { let mut invalid_compile_fail_format = false; let mut found_error_code = false; for line in f.lines() { let s = line.trim(); if s.starts_with("```") { if s.contains("compile_fail") && s.contains('E') { if !found_error_code { error_codes.get_mut(&err_code).map(|x| x.has_test = true); found_error_code = true; } } else if s.contains("compile-fail") { invalid_compile_fail_format = true; } } else if s.starts_with("#### Note: this error code is no longer emitted by the compiler") { if !found_error_code { error_codes.get_mut(&err_code).map(|x| x.has_test = true); found_error_code = true; } } } invalid_compile_fail_format } fn check_if_error_code_is_test_in_explanation(f: &str, err_code: &str) -> bool { let mut ignore_found = false; for line in f.lines() { let s = line.trim(); if s.starts_with("#### Note: this error code is no longer emitted by the compiler") { return true; } if s.starts_with("```") { if s.contains("compile_fail") && s.contains(err_code) { return true; } else if s.contains("ignore") { // It's very likely that we can't actually make it fail compilation... ignore_found = true; } } } ignore_found } macro_rules! some_or_continue { ($e:expr) => { match $e { Some(e) => e, None => continue, } }; } fn extract_error_codes(<|fim▁hole|>) { let mut reached_no_explanation = false; for line in f.lines() { let s = line.trim(); if !reached_no_explanation && s.starts_with('E') && s.contains("include_str!(\"") { let err_code = s .split_once(':') .expect( format!( "Expected a line with the format `E0xxx: include_str!(\"..\")`, but got {} \ without a `:` delimiter", s, ) .as_str(), ) .0 .to_owned(); error_codes.entry(err_code.clone()).or_default().has_explanation = true; // Now we extract the tests from the markdown file! let md_file_name = match s.split_once("include_str!(\"") { None => continue, Some((_, md)) => match md.split_once("\")") { None => continue, Some((file_name, _)) => file_name, }, }; let path = some_or_continue!(path.parent()) .join(md_file_name) .canonicalize() .expect("failed to canonicalize error explanation file path"); match read_to_string(&path) { Ok(content) => { let has_test = check_if_error_code_is_test_in_explanation(&content, &err_code); if !has_test && !IGNORE_EXPLANATION_CHECK.contains(&err_code.as_str()) { errors.push(format!( "`{}` doesn't use its own error code in compile_fail example", path.display(), )); } else if has_test && IGNORE_EXPLANATION_CHECK.contains(&err_code.as_str()) { errors.push(format!( "`{}` has a compile_fail example with its own error code, it shouldn't \ be listed in IGNORE_EXPLANATION_CHECK!", path.display(), )); } if check_error_code_explanation(&content, error_codes, err_code) { errors.push(format!( "`{}` uses invalid tag `compile-fail` instead of `compile_fail`", path.display(), )); } } Err(e) => { eprintln!("Couldn't read `{}`: {}", path.display(), e); } } } else if reached_no_explanation && s.starts_with('E') { let err_code = match s.split_once(',') { None => s, Some((err_code, _)) => err_code, } .to_string(); if !error_codes.contains_key(&err_code) { // this check should *never* fail! error_codes.insert(err_code, ErrorCodeStatus::default()); } } else if s == ";" { reached_no_explanation = true; } } } fn extract_error_codes_from_tests(f: &str, error_codes: &mut HashMap<String, ErrorCodeStatus>) { for line in f.lines() { let s = line.trim(); if s.starts_with("error[E") || s.starts_with("warning[E") { let err_code = match s.split_once(']') { None => continue, Some((err_code, _)) => match err_code.split_once('[') { None => continue, Some((_, err_code)) => err_code, }, }; error_codes.entry(err_code.to_owned()).or_default().has_test = true; } } } fn extract_error_codes_from_source( f: &str, error_codes: &mut HashMap<String, ErrorCodeStatus>, regex: &Regex, ) { for line in f.lines() { if line.trim_start().starts_with("//") { continue; } for cap in regex.captures_iter(line) { if let Some(error_code) = cap.get(1) { error_codes.entry(error_code.as_str().to_owned()).or_default().is_used = true; } } } } pub fn check(paths: &[&Path], bad: &mut bool) { let mut errors = Vec::new(); let mut found_explanations = 0; let mut found_tests = 0; let mut error_codes: HashMap<String, ErrorCodeStatus> = HashMap::new(); // We want error codes which match the following cases: // // * foo(a, E0111, a) // * foo(a, E0111) // * foo(E0111, a) // * #[error = "E0111"] let regex = Regex::new(r#"[(,"\s](E\d{4})[,)"]"#).unwrap(); println!("Checking which error codes lack tests..."); for path in paths { super::walk(path, &mut |path| super::filter_dirs(path), &mut |entry, contents| { let file_name = entry.file_name(); if file_name == "error_codes.rs" { extract_error_codes(contents, &mut error_codes, entry.path(), &mut errors); found_explanations += 1; } else if entry.path().extension() == Some(OsStr::new("stderr")) { extract_error_codes_from_tests(contents, &mut error_codes); found_tests += 1; } else if entry.path().extension() == Some(OsStr::new("rs")) { let path = entry.path().to_string_lossy(); if PATHS_TO_IGNORE_FOR_EXTRACTION.iter().all(|c| !path.contains(c)) { extract_error_codes_from_source(contents, &mut error_codes, &regex); } } }); } if found_explanations == 0 { eprintln!("No error code explanation was tested!"); *bad = true; } if found_tests == 0 { eprintln!("No error code was found in compilation errors!"); *bad = true; } if errors.is_empty() { println!("Found {} error codes", error_codes.len()); for (err_code, error_status) in &error_codes { if !error_status.has_test && !EXEMPTED_FROM_TEST.contains(&err_code.as_str()) { errors.push(format!("Error code {} needs to have at least one UI test!", err_code)); } else if error_status.has_test && EXEMPTED_FROM_TEST.contains(&err_code.as_str()) { errors.push(format!( "Error code {} has a UI test, it shouldn't be listed into EXEMPTED_FROM_TEST!", err_code )); } if !error_status.is_used && !error_status.has_explanation { errors.push(format!( "Error code {} isn't used and doesn't have an error explanation, it should be \ commented in error_codes.rs file", err_code )); } } } if errors.is_empty() { // Checking if local constants need to be cleaned. for err_code in EXEMPTED_FROM_TEST { match error_codes.get(err_code.to_owned()) { Some(status) => { if status.has_test { errors.push(format!( "{} error code has a test and therefore should be \ removed from the `EXEMPTED_FROM_TEST` constant", err_code )); } } None => errors.push(format!( "{} error code isn't used anymore and therefore should be removed \ from `EXEMPTED_FROM_TEST` constant", err_code )), } } } errors.sort(); for err in &errors { eprintln!("{}", err); } println!("Found {} error codes with no tests", errors.len()); if !errors.is_empty() { *bad = true; } println!("Done!"); }<|fim▁end|>
f: &str, error_codes: &mut HashMap<String, ErrorCodeStatus>, path: &Path, errors: &mut Vec<String>,
<|file_name|>StatelessAuthenticationFilter.java<|end_file_name|><|fim▁begin|>package conqueror.security; import io.jsonwebtoken.JwtException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.GenericFilterBean; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest;<|fim▁hole|>class StatelessAuthenticationFilter extends GenericFilterBean { private final TokenAuthenticationService tokenAuthenticationService; StatelessAuthenticationFilter(TokenAuthenticationService tokenAuthenticationService) { this.tokenAuthenticationService = tokenAuthenticationService; } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { try { Authentication authentication = tokenAuthenticationService.getAuthentication((HttpServletRequest) req); SecurityContextHolder.getContext().setAuthentication(authentication); chain.doFilter(req, res); SecurityContextHolder.getContext().setAuthentication(null); } catch (AuthenticationException | JwtException e) { SecurityContextHolder.clearContext(); ((HttpServletResponse) res).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } } }<|fim▁end|>
import javax.servlet.http.HttpServletResponse; import java.io.IOException;
<|file_name|>test_ubl.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from odoo.addons.account_edi.tests.common import AccountEdiTestCommon from odoo.tests import tagged from odoo import Command @tagged('post_install_l10n', 'post_install', '-at_install') class TestL10nBeEdi(AccountEdiTestCommon): @classmethod def setUpClass(cls, chart_template_ref='l10n_be.l10nbe_chart_template', edi_format_ref='l10n_be_edi.edi_efff_1'): super().setUpClass(chart_template_ref=chart_template_ref, edi_format_ref=edi_format_ref) # ==== Init ==== cls.tax_10_include = cls.env['account.tax'].create({ 'name': 'tax_10_include', 'amount_type': 'percent', 'amount': 10, 'type_tax_use': 'sale', 'price_include': True, 'include_base_amount': True, 'sequence': 10, }) cls.tax_20 = cls.env['account.tax'].create({ 'name': 'tax_20', 'amount_type': 'percent', 'amount': 20, 'invoice_repartition_line_ids': [ (0, 0, {'factor_percent': 100.0, 'repartition_type': 'base'}), (0, 0, {'factor_percent': 40.0, 'repartition_type': 'tax'}), (0, 0, {'factor_percent': 60.0, 'repartition_type': 'tax'}), ], 'refund_repartition_line_ids': [ (0, 0, {'factor_percent': 100.0, 'repartition_type': 'base'}), (0, 0, {'factor_percent': 40.0, 'repartition_type': 'tax'}), (0, 0, {'factor_percent': 60.0, 'repartition_type': 'tax'}), ], 'type_tax_use': 'sale', 'sequence': 20, }) cls.tax_group = cls.env['account.tax'].create({ 'name': 'tax_group', 'amount_type': 'group', 'amount': 0.0, 'type_tax_use': 'sale', 'children_tax_ids': [(6, 0, (cls.tax_10_include + cls.tax_20).ids)], }) cls.partner_a.vat = 'BE0477472701' # ==== Invoice ==== cls.invoice = cls.env['account.move'].create({ 'move_type': 'out_invoice', 'journal_id': cls.journal.id, 'partner_id': cls.partner_b.id, 'invoice_date': '2017-01-01', 'date': '2017-01-01', 'currency_id': cls.currency_data['currency'].id, 'invoice_line_ids': [(0, 0, { 'product_id': cls.product_a.id, 'product_uom_id': cls.env.ref('uom.product_uom_dozen').id, 'price_unit': 275.0, 'quantity': 5, 'discount': 20.0, 'tax_ids': [(6, 0, cls.tax_20.ids)], })], }) cls.expected_invoice_efff_values = ''' <Invoice> <UBLVersionID>2.0</UBLVersionID> <ID>INV/2017/00001</ID> <IssueDate>2017-01-01</IssueDate> <InvoiceTypeCode>380</InvoiceTypeCode> <DocumentCurrencyCode>Gol</DocumentCurrencyCode> <AccountingSupplierParty> <Party> <PartyName> <Name>company_1_data</Name> </PartyName> <Language> <LocaleCode>en_US</LocaleCode> </Language> <PostalAddress/> <Contact> <Name>company_1_data</Name> </Contact> </Party> </AccountingSupplierParty> <AccountingCustomerParty> <Party> <PartyName> <Name>partner_b</Name> </PartyName> <Language> <LocaleCode>en_US</LocaleCode> </Language> <PostalAddress/> <Contact> <Name>partner_b</Name> </Contact> </Party> </AccountingCustomerParty> <PaymentMeans> <PaymentMeansCode listID="UN/ECE 4461">31</PaymentMeansCode> <PaymentDueDate>2017-01-01</PaymentDueDate> <InstructionID>INV/2017/00001</InstructionID> </PaymentMeans> <TaxTotal> <TaxAmount currencyID="Gol">220.000</TaxAmount> </TaxTotal> <LegalMonetaryTotal> <LineExtensionAmount currencyID="Gol">1100.000</LineExtensionAmount> <TaxExclusiveAmount currencyID="Gol">1100.000</TaxExclusiveAmount> <TaxInclusiveAmount currencyID="Gol">1320.000</TaxInclusiveAmount> <PrepaidAmount currencyID="Gol">0.000</PrepaidAmount> <PayableAmount currencyID="Gol">1320.000</PayableAmount> </LegalMonetaryTotal> <InvoiceLine> <ID>___ignore___</ID> <Note>Discount (20.0 %)</Note> <InvoicedQuantity>5.0</InvoicedQuantity> <LineExtensionAmount currencyID="Gol">1100.000</LineExtensionAmount> <TaxTotal> <TaxAmount currencyID="Gol">220.000</TaxAmount> </TaxTotal> <Item> <Description>product_a</Description> <Name>product_a</Name> </Item> <Price> <PriceAmount currencyID="Gol">275.000</PriceAmount> </Price> </InvoiceLine> </Invoice> ''' #################################################### # Test export #################################################### def test_efff_simple_case(self): ''' Test the generated Facturx Edi attachment without any modification of the invoice. ''' self.assert_generated_file_equal(self.invoice, self.expected_invoice_efff_values) def test_efff_group_of_taxes(self): self.invoice.write({ 'invoice_line_ids': [(1, self.invoice.invoice_line_ids.id, {'tax_ids': [Command.set(self.tax_group.ids)]})], }) applied_xpath = ''' <xpath expr="//TaxTotal/TaxAmount" position="replace"> <TaxAmount currencyID="Gol">320.000</TaxAmount> </xpath> <xpath expr="//LegalMonetaryTotal/LineExtensionAmount" position="replace"> <LineExtensionAmount currencyID="Gol">1000.000</LineExtensionAmount> </xpath> <xpath expr="//LegalMonetaryTotal/TaxExclusiveAmount" position="replace"> <TaxExclusiveAmount currencyID="Gol">1000.000</TaxExclusiveAmount> </xpath> <xpath expr="//InvoiceLine/LineExtensionAmount" position="replace"> <LineExtensionAmount currencyID="Gol">1000.000</LineExtensionAmount> </xpath> <xpath expr="//InvoiceLine/TaxTotal" position="replace"> <TaxTotal> <TaxAmount currencyID="Gol">100.000</TaxAmount> </TaxTotal> <TaxTotal> <TaxAmount currencyID="Gol">220.000</TaxAmount> </TaxTotal> </xpath> ''' self.assert_generated_file_equal(self.invoice, self.expected_invoice_efff_values, applied_xpath) #################################################### # Test import #################################################### def test_invoice_edi_xml_update(self): invoice = self._create_empty_vendor_bill() invoice_count = len(self.env['account.move'].search([])) self.update_invoice_from_file('l10n_be_edi', 'test_xml_file', 'efff_test.xml', invoice) <|fim▁hole|> self.assertEqual(invoice.partner_id, self.partner_a) def test_invoice_edi_xml_create(self): invoice_count = len(self.env['account.move'].search([])) invoice = self.create_invoice_from_file('l10n_be_edi', 'test_xml_file', 'efff_test.xml') self.assertEqual(len(self.env['account.move'].search([])), invoice_count + 1) self.assertEqual(invoice.amount_total, 666.50) self.assertEqual(invoice.amount_tax, 115.67) self.assertEqual(invoice.partner_id, self.partner_a)<|fim▁end|>
self.assertEqual(len(self.env['account.move'].search([])), invoice_count) self.assertEqual(invoice.amount_total, 666.50) self.assertEqual(invoice.amount_tax, 115.67)
<|file_name|>common-defines.cpp<|end_file_name|><|fim▁begin|>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include <time.h> #include "Basics/system-functions.h" #include "Basics/tri-strings.h" #include "Replication/common-defines.h" namespace arangodb { /// @brief generate a timestamp string in a target buffer void TRI_GetTimeStampReplication(char* dst, size_t maxLength) { struct tm tb; time_t tt = time(nullptr); TRI_gmtime(tt, &tb); strftime(dst, maxLength, "%Y-%m-%dT%H:%M:%SZ", &tb); } /// @brief generate a timestamp string in a target buffer void TRI_GetTimeStampReplication(double timeStamp, char* dst, size_t maxLength) { struct tm tb; time_t tt = static_cast<time_t>(timeStamp); TRI_gmtime(tt, &tb); strftime(dst, maxLength, "%Y-%m-%dT%H:%M:%SZ", &tb); } bool TRI_ExcludeCollectionReplication(std::string const& name, bool includeSystem, bool includeFoxxQueues) { if (name.empty()) {<|fim▁hole|> // should not happen... return true; } if (name[0] != '_') { // all regular collections are included return false; } if (!includeSystem) { // do not include any system collections return true; } if (TRI_IsPrefixString(name.c_str(), "_statistics") || name == "_configuration" || name == "_frontend" || name == "_cluster_kickstarter_plans" || name == "_routing" || name == "_fishbowl" || name == "_foxxlog" || name == "_sessions") { // these system collections will always be excluded return true; } else if (!includeFoxxQueues && (name == "_jobs" || name == "_queues")) { return true; } return false; } } // namespace arangodb<|fim▁end|>
<|file_name|>midi_output.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # This file is part of Linux Show Player # # Copyright 2012-2016 Francesco Ceruti <[email protected]> # # Linux Show Player 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. # # Linux Show Player 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|># along with Linux Show Player. If not, see <http://www.gnu.org/licenses/>. import mido from lisp.modules.midi.midi_common import MIDICommon from lisp.modules.midi.midi_utils import mido_backend, mido_port_name class MIDIOutput(MIDICommon): def __init__(self, port_name='AppDefault'): super().__init__(port_name=port_name) def send_from_str(self, str_message): self.send(mido.parse_string(str_message)) def send(self, message): self._port.send(message) def open(self): port_name = mido_port_name(self._port_name, 'O') self._port = mido_backend().open_output(port_name)<|fim▁end|>
# GNU General Public License for more details. # # You should have received a copy of the GNU General Public License
<|file_name|>textarea.js<|end_file_name|><|fim▁begin|>"use strict"; var m = require("mithril"), assign = require("lodash.assign"), id = require("./lib/id"), hide = require("./lib/hide"),<|fim▁hole|>module.exports = { controller : function(options) { var ctrl = this; ctrl.id = id(options); ctrl.text = options.data || ""; ctrl.resize = function(opt, value) { opt.update(opt.path, value); ctrl.text = value; }; }, view : function(ctrl, options) { var field = options.field, hidden = hide(options); if(hidden) { return hidden; } return m("div", { class : options.class }, label(ctrl, options), m("div", { class : css.expander }, m("pre", { class : css.shadow }, m("span", ctrl.text), m("br")), m("textarea", assign({ // attrs id : ctrl.id, class : css.textarea, required : field.required ? "required" : null, // events oninput : m.withAttr("value", ctrl.resize.bind(null, options)) }, field.attrs || {} ), options.data || "") ) ); } };<|fim▁end|>
label = require("./lib/label"), css = require("./textarea.css");
<|file_name|>main.py<|end_file_name|><|fim▁begin|>import htmlPy import socket import json import os sock = socket.socket() sock.connect(('localhost', 5002)) sock.send(b'') sock.recv(1024) sock.recv(1024) sock.recv(1024) app = htmlPy.AppGUI(title=u"Python Best Ever", maximized=True) app.template_path = os.path.abspath("./html") app.static_path = os.path.abspath("./html") template_name = 'index.html' app_data = { 'val': '0' } def processor(response): response = str(response) response = json.loads(response)['message'] print(response) command, data = response.split('#') if '@' in command: command, subcommand = command.split('@') if command == 'put': app_data[subcommand] = data class App(htmlPy.Object): def __init__(self): super(App, self).__init__() @htmlPy.Slot(str)<|fim▁hole|> template_name = str(url) app.template = (template_name, app_data) @htmlPy.Slot(str) def command(self, cmd): cmd = bytes(cmd) sock.send(cmd) response = sock.recv(1024) processor(response) app.template = (template_name, app_data) app.template = (template_name, app_data) app.bind(App()) app.start()<|fim▁end|>
def link(self, url):
<|file_name|>FindUsedTypes.cpp<|end_file_name|><|fim▁begin|>//===- FindUsedTypes.cpp - Find all Types used by a module ----------------===// // // The LLVM Compiler Infrastructure // <|fim▁hole|>// //===----------------------------------------------------------------------===// // // This pass is used to seek out all of the types in use by the program. Note // that this analysis explicitly does not include types only used by the symbol // table. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/FindUsedTypes.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/Assembly/Writer.h" #include "llvm/Support/InstIterator.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; char FindUsedTypes::ID = 0; INITIALIZE_PASS(FindUsedTypes, "print-used-types", "Find Used Types", false, true) // IncorporateType - Incorporate one type and all of its subtypes into the // collection of used types. // void FindUsedTypes::IncorporateType(Type *Ty) { // If ty doesn't already exist in the used types map, add it now, otherwise // return. if (!UsedTypes.insert(Ty)) return; // Already contain Ty. // Make sure to add any types this type references now. // for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end(); I != E; ++I) IncorporateType(*I); } void FindUsedTypes::IncorporateValue(const Value *V) { IncorporateType(V->getType()); // If this is a constant, it could be using other types... if (const Constant *C = dyn_cast<Constant>(V)) { if (!isa<GlobalValue>(C)) for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); OI != OE; ++OI) IncorporateValue(*OI); } } // run - This incorporates all types used by the specified module // bool FindUsedTypes::runOnModule(Module &m) { UsedTypes.clear(); // reset if run multiple times... // Loop over global variables, incorporating their types for (Module::const_global_iterator I = m.global_begin(), E = m.global_end(); I != E; ++I) { IncorporateType(I->getType()); if (I->hasInitializer()) IncorporateValue(I->getInitializer()); } for (Module::iterator MI = m.begin(), ME = m.end(); MI != ME; ++MI) { IncorporateType(MI->getType()); const Function &F = *MI; // Loop over all of the instructions in the function, adding their return // type as well as the types of their operands. // for (const_inst_iterator II = inst_begin(F), IE = inst_end(F); II != IE; ++II) { const Instruction &I = *II; IncorporateType(I.getType()); // Incorporate the type of the instruction for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI) IncorporateValue(*OI); // Insert inst operand types as well } } return false; } // Print the types found in the module. If the optional Module parameter is // passed in, then the types are printed symbolically if possible, using the // symbol table from the module. // void FindUsedTypes::print(raw_ostream &OS, const Module *M) const { OS << "Types in use by this module:\n"; for (SetVector<Type *>::const_iterator I = UsedTypes.begin(), E = UsedTypes.end(); I != E; ++I) { OS << " " << **I << '\n'; } }<|fim▁end|>
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details.
<|file_name|>many_single_char_names.rs<|end_file_name|><|fim▁begin|>#![allow(clippy::too_many_arguments, clippy::diverging_sub_expression)] #![warn(clippy::many_single_char_names)] fn bla() { let a: i32; let (b, c, d): (i32, i64, i16); { { let cdefg: i32; let blar: i32; } { let e: i32; }<|fim▁hole|> let f: i32; } match 5 { 1 => println!(), e => panic!(), } match 5 { 1 => println!(), _ => panic!(), } } } fn bindings(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32, g: i32, h: i32) {} fn bindings2() { let (a, b, c, d, e, f, g, h): (bool, bool, bool, bool, bool, bool, bool, bool) = unimplemented!(); } fn shadowing() { let a = 0i32; let a = 0i32; let a = 0i32; let a = 0i32; let a = 0i32; let a = 0i32; { let a = 0i32; } } fn patterns() { enum Z { A(i32), B(i32), C(i32), D(i32), E(i32), F(i32), } // These should not trigger a warning, since the pattern bindings are a new scope. match Z::A(0) { Z::A(a) => {}, Z::B(b) => {}, Z::C(c) => {}, Z::D(d) => {}, Z::E(e) => {}, Z::F(f) => {}, } } #[allow(clippy::many_single_char_names)] fn issue_3198_allow_works() { let (a, b, c, d, e) = (0, 0, 0, 0, 0); } fn main() {}<|fim▁end|>
{ let e: i32;
<|file_name|>util.py<|end_file_name|><|fim▁begin|>import collections import functools import dpath import six import pprint import stringcase from pyutrack.logger import get_logger def print_friendly(value, sep=', '): if isinstance(value, six.string_types): return value if isinstance(value, collections.Iterable): return sep.join(str(k) for k in value) return str(value) def remove_empty_querystring(url): parsed = six.moves.urllib.parse.urlparse(url) new_query = six.moves.urllib.parse.urlencode( six.moves.urllib.parse.parse_qsl(parsed.query) ) return six.moves.urllib.parse.ParseResult( scheme=parsed.scheme, netloc=parsed.netloc, path=parsed.path, params=parsed.params, query=new_query, fragment=None ).geturl() class Response(dict): def __init__(self, data={}, aliases={}): """ :param data: :param aliases: """ super(Response, self).__init__() self.__aliases = aliases self.update(data) def update(self, other): """ :param other: :return: """ if not other: return super(Response, self).update( { self.__resolve_alias(k): v for k, v in other.items() if k != 'field' } ) for f in other.get('field', []): super(Response, self).update({f['name']: f['value']}) def __resolve_alias(self, key): while key in self.__aliases: key = self.__aliases[key] return key def __getitem__(self, item): return super(Response, self).__getitem__( self.__resolve_alias(item) ) def __setitem__(self, item, value): return super(Response, self).__setitem__( self.__resolve_alias(item), value ) class Type(type): class Association(collections.Iterable): def __init__(self, type, parent, get_config, add_config, del_config): self.type = type self.parent = parent self.get_config = get_config self.add_config = add_config self.del_config = del_config self._cache = None def __iadd__(self, other): if not self.add_config: raise NotImplementedError url = self.add_config.get('url') fields = self.parent.fields.copy() method = getattr( self.parent.connection, self.add_config.get('method') ) for item in other: fields.update({self.add_config.get('key'): item}) method(remove_empty_querystring(url % fields), {}, parse=False) return self def __len__(self): return len(list(self.__iter__())) def __isub__(self, other): if not self.del_config: raise NotImplementedError url = self.del_config.get('url') fields = self.parent.fields.copy() for item in other: fields.update({self.del_config.get('key'): item}) self.parent.connection.delete( remove_empty_querystring(url % fields) ) return self def __iter__(self): if not self._cache: self._cache = self() hydrate = self.get_config.get('hydrate', False) if not isinstance(self._cache, collections.Iterable): raise TypeError( '%s->%s is not iterable' % (self.parent.__class__.__name__, self.type.__name__) ) else: for v in self._cache: yield self.type( self.parent.connection, hydrate=hydrate, **v ) def __call__(self): fields = self.parent.fields.copy() fields.update(self.get_config.get('kwargs', {})) url = remove_empty_querystring(self.get_config.get('url') % fields) return self.get_config.get( 'callback', lambda r: r )(self.parent.connection.get(url)) class AssociationProperty(object): def __init__(self, binding): self.binding = binding def __get__(self, instance, obj_type): return self.binding(instance) class Base(object): __aliases__ = {} def __init__(self, connection, hydrate=False, **fields): """ :param connection: :param hydrate: :param fields: """ aliases = super(Type.Base, self).__getattribute__('__aliases__') super(Type.Base, self).__setattr__('connection', connection) super(Type.Base, self).__setattr__('fields', Response(fields, aliases)) if hydrate: self._get( self.__get__.get('callback', lambda response: response) ) def _get_attribute(self, lookup): try: return self.fields[lookup] except KeyError: return dpath.util.get(self.fields, lookup) def _update(self, callback, **kwargs): resource_data = self.__update_data(kwargs) self.connection.post( self.__update_endpoint(), resource_data, parse=False ) self.fields.update(resource_data) def _delete(self, callback): return callback( self.connection.delete(self.__delete_endpoint(), parse=False) ) @classmethod def _create(cls, connection, callback, **kwargs): return cls( connection, **callback( connection.put(cls.__create_endpoint(**kwargs), kwargs) ) ) @classmethod def _list(cls, connection, callback, **kwargs): hydrate = cls.__list__.get('hydrate', False) data = [ cls(connection, hydrate=hydrate, **obj) for obj in callback(connection.get(cls.__list_endpoint(**kwargs))) ] return data def _get(self, callback): self.fields.update( Response( callback(self.connection.get(self.__get_endpoint())), self.__aliases__ ) ) def _get_association(self, params, **kwargs): if 'kwargs' in params['get']: params['get']['kwargs'].update(kwargs) return Type.Association( params['type'], self, params['get'], params.get('add', {}), params.get('remove', {}) ) def __get_endpoint(self): return remove_empty_querystring( self.__get__.get('url') % self.fields ) @classmethod def __create_endpoint(cls, **kwargs): return remove_empty_querystring( cls.__create__.get('url') % kwargs ) def __update_endpoint(self): return remove_empty_querystring( self.__update__.get('url') % self.fields ) def __update_data(self, kwargs): data = kwargs.copy() fields = kwargs.keys() data.update( { k: self.fields[k] for k in fields if not kwargs[k] and self.fields.get(k) } ) return data def __delete_endpoint(self): return self.__delete__.get('url') % self.fields @classmethod def __list_endpoint(cls, **kwargs): return cls.__list__.get('url') % kwargs def format(self, template=None, oneline=False): """ :param template: :param oneline: :return: """ data_source = self.fields if oneline: fields = getattr(self, '__render_min__', self.__render__) return '\t'.join( str(data_source.get(k, getattr(self, k))) for k in fields ) else: fields = template or self.__render__ resp = '' for k in fields: try: label = stringcase.sentencecase(k).ljust(20) value = data_source.get(k, getattr(self, k, None)) resp += "%s : %s\n" % (label, print_friendly(value)) except KeyError: get_logger().debug( "No %s attribute found for %s", k, self.__class__.__name__ ) return resp def __repr__(self): return pprint.pformat(self.fields) def __str__(self): return ( getattr(self, '__label__', None) or ' '.join('%%(%s)s' % k for k in self.__render__) ) % self.fields def __new__(mcs, name, bases, dct): for verb in ['get', 'delete', 'update']: if '__%s__' % verb in dct: info = dct['__%s__' % verb] fn = Type.__build_func( verb, info.get('args', (())), info.get('kwargs', {}), { 'callback': info.get('callback', lambda response: response) } ) fn.__doc__ = '%s %s' % (verb, name.lower()) dct[verb] = fn for verb in ['create', 'list']: if '__%s__' % verb in dct: info = dct['__%s__' % verb] fn = Type.__build_func( verb, ('connection', ) + info.get('args', ()), info.get('kwargs', {}), { 'callback': info.get('callback', lambda response: response) } ) fn.__doc__ = '%s %s' % (verb, name.lower()) dct[verb] = classmethod(fn) for association, params in dct.get('__associations__', {}).items(): fn = Type.__build_func( 'get_association', (), params.get('get', {}).get('kwargs', {}), {'params': params} ) fn.__doc__ = 'get %s %s' % (name.lower(), association) dct[association] = Type.AssociationProperty(fn) dct[association].__doc__ = '%s %s' % (name.lower(), association) dct["get_%s" % association] = fn <|fim▁hole|> dct[attribute] = property(getter) return super(Type, mcs).__new__(mcs, name, (mcs.Base, ) + bases, dct) @staticmethod def __build_func(verb, args, kwargs, _locals): params = ['self'] params += ['%s' % stringcase.snakecase(k) for k in args] params += [ '%s=%s' % ( stringcase.snakecase(k), "'%s'" % v if isinstance(v, six.string_types) else v ) for k, v in kwargs.items() ] largs = list(_locals.keys()) + list(args) + list(kwargs.keys()) fn = eval( 'lambda %s: self._%s(%s)' % ( ','.join(params), verb, ','.join( ['%s=%s' % (k, stringcase.snakecase(k)) for k in largs] ) ), _locals ) return fn<|fim▁end|>
for attribute, lookup in dct.get('__attributes__', {}).items(): getter = functools.partial(Type.Base._get_attribute, lookup=lookup) getter.__doc__ = attribute
<|file_name|>form_group_name.ts<|end_file_name|><|fim▁begin|>/** * @license * Copyright Google LLC 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 {Directive, forwardRef, Host, Inject, Input, OnDestroy, OnInit, Optional, Self, SkipSelf} from '@angular/core'; import {FormArray} from '../../model'; import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../../validators'; import {AbstractFormGroupDirective} from '../abstract_form_group_directive'; import {ControlContainer} from '../control_container'; import {ReactiveErrors} from '../reactive_errors'; import {composeAsyncValidators, composeValidators, controlPath} from '../shared'; import {AsyncValidatorFn, ValidatorFn} from '../validators'; import {FormGroupDirective} from './form_group_directive'; <|fim▁hole|> useExisting: forwardRef(() => FormGroupName) }; /** * @description * * Syncs a nested `FormGroup` to a DOM element. * * This directive can only be used with a parent `FormGroupDirective`. * * It accepts the string name of the nested `FormGroup` to link, and * looks for a `FormGroup` registered with that name in the parent * `FormGroup` instance you passed into `FormGroupDirective`. * * Use nested form groups to validate a sub-group of a * form separately from the rest or to group the values of certain * controls into their own nested object. * * @see [Reactive Forms Guide](guide/reactive-forms) * * @usageNotes * * ### Access the group by name * * The following example uses the {@link AbstractControl#get get} method to access the * associated `FormGroup` * * ```ts * this.form.get('name'); * ``` * * ### Access individual controls in the group * * The following example uses the {@link AbstractControl#get get} method to access * individual controls within the group using dot syntax. * * ```ts * this.form.get('name.first'); * ``` * * ### Register a nested `FormGroup`. * * The following example registers a nested *name* `FormGroup` within an existing `FormGroup`, * and provides methods to retrieve the nested `FormGroup` and individual controls. * * {@example forms/ts/nestedFormGroup/nested_form_group_example.ts region='Component'} * * @ngModule ReactiveFormsModule * @publicApi */ @Directive({selector: '[formGroupName]', providers: [formGroupNameProvider]}) export class FormGroupName extends AbstractFormGroupDirective implements OnInit, OnDestroy { /** * @description * Tracks the name of the `FormGroup` bound to the directive. The name corresponds * to a key in the parent `FormGroup` or `FormArray`. * Accepts a name as a string or a number. * The name in the form of a string is useful for individual forms, * while the numerical form allows for form groups to be bound * to indices when iterating over groups in a `FormArray`. */ // TODO(issue/24571): remove '!'. @Input('formGroupName') name!: string|number|null; constructor( @Optional() @Host() @SkipSelf() parent: ControlContainer, @Optional() @Self() @Inject(NG_VALIDATORS) validators: any[], @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: any[]) { super(); this._parent = parent; this._validators = validators; this._asyncValidators = asyncValidators; } /** @internal */ _checkParentType(): void { if (_hasInvalidParent(this._parent) && (typeof ngDevMode === 'undefined' || ngDevMode)) { ReactiveErrors.groupParentException(); } } } export const formArrayNameProvider: any = { provide: ControlContainer, useExisting: forwardRef(() => FormArrayName) }; /** * @description * * Syncs a nested `FormArray` to a DOM element. * * This directive is designed to be used with a parent `FormGroupDirective` (selector: * `[formGroup]`). * * It accepts the string name of the nested `FormArray` you want to link, and * will look for a `FormArray` registered with that name in the parent * `FormGroup` instance you passed into `FormGroupDirective`. * * @see [Reactive Forms Guide](guide/reactive-forms) * @see `AbstractControl` * * @usageNotes * * ### Example * * {@example forms/ts/nestedFormArray/nested_form_array_example.ts region='Component'} * * @ngModule ReactiveFormsModule * @publicApi */ @Directive({selector: '[formArrayName]', providers: [formArrayNameProvider]}) export class FormArrayName extends ControlContainer implements OnInit, OnDestroy { /** @internal */ _parent: ControlContainer; /** @internal */ _validators: any[]; /** @internal */ _asyncValidators: any[]; /** * @description * Tracks the name of the `FormArray` bound to the directive. The name corresponds * to a key in the parent `FormGroup` or `FormArray`. * Accepts a name as a string or a number. * The name in the form of a string is useful for individual forms, * while the numerical form allows for form arrays to be bound * to indices when iterating over arrays in a `FormArray`. */ // TODO(issue/24571): remove '!'. @Input('formArrayName') name!: string|number|null; constructor( @Optional() @Host() @SkipSelf() parent: ControlContainer, @Optional() @Self() @Inject(NG_VALIDATORS) validators: any[], @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: any[]) { super(); this._parent = parent; this._validators = validators; this._asyncValidators = asyncValidators; } /** * A lifecycle method called when the directive's inputs are initialized. For internal use only. * @throws If the directive does not have a valid parent. * @nodoc */ ngOnInit(): void { this._checkParentType(); this.formDirective!.addFormArray(this); } /** * A lifecycle method called before the directive's instance is destroyed. For internal use only. * @nodoc */ ngOnDestroy(): void { if (this.formDirective) { this.formDirective.removeFormArray(this); } } /** * @description * The `FormArray` bound to this directive. */ get control(): FormArray { return this.formDirective!.getFormArray(this); } /** * @description * The top-level directive for this group if present, otherwise null. */ get formDirective(): FormGroupDirective|null { return this._parent ? <FormGroupDirective>this._parent.formDirective : null; } /** * @description * Returns an array that represents the path from the top-level form to this control. * Each index is the string name of the control on that level. */ get path(): string[] { return controlPath(this.name == null ? this.name : this.name.toString(), this._parent); } /** * @description * Synchronous validator function composed of all the synchronous validators registered with this * directive. */ get validator(): ValidatorFn|null { return composeValidators(this._validators); } /** * @description * Async validator function composed of all the async validators registered with this directive. */ get asyncValidator(): AsyncValidatorFn|null { return composeAsyncValidators(this._asyncValidators); } private _checkParentType(): void { if (_hasInvalidParent(this._parent) && (typeof ngDevMode === 'undefined' || ngDevMode)) { ReactiveErrors.arrayParentException(); } } } function _hasInvalidParent(parent: ControlContainer): boolean { return !(parent instanceof FormGroupName) && !(parent instanceof FormGroupDirective) && !(parent instanceof FormArrayName); }<|fim▁end|>
export const formGroupNameProvider: any = { provide: ControlContainer,
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.core.urlresolvers import reverse from django.contrib import messages from models import UserVote from forms import UserVoteForm <|fim▁hole|>def vote(request): if request.method == "POST": form = UserVoteForm(request.POST) if form.is_valid(): vote = form.save(commit=False) vote = UserVote.objects.vote(request.user, vote.vote) messages.info(request, "Your mood is %s" % vote.get_vote_display()) else: form = UserVoteForm() return HttpResponseRedirect(reverse('dashboard'))<|fim▁end|>
<|file_name|>sttClient.py<|end_file_name|><|fim▁begin|># # Copyright IBM Corp. 2014 # # 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. # # Author: Daniel Bolanos # Date: 2015 # coding=utf-8 import json # json import threading # multi threading import os # for listing directories import Queue # queue used for thread syncronization import sys # system calls import argparse # for parsing arguments import base64 # necessary to encode in base64 # according to the RFC2045 standard import requests # python HTTP requests library # WebSockets from autobahn.twisted.websocket import WebSocketClientProtocol, \ WebSocketClientFactory, connectWS from twisted.python import log from twisted.internet import ssl, reactor with open("path_output.txt", "r") as file: path_output = file.read() class Utils: @staticmethod def getAuthenticationToken(hostname, serviceName, username, password): uri = hostname + "/authorization/api/v1/token?url=" + hostname + '/' \ + serviceName + "/api" uri = uri.replace("wss://", "https://") uri = uri.replace("ws://", "https://") print uri resp = requests.get(uri, auth=(username, password), verify=False, headers={'Accept': 'application/json'}, timeout=(30, 30)) print resp.text jsonObject = resp.json() return jsonObject['token'] class WSInterfaceFactory(WebSocketClientFactory): def __init__(self, queue, summary, dirOutput, contentType, model, url=None, headers=None, debug=None): WebSocketClientFactory.__init__(self, url=url, headers=headers) self.queue = queue self.summary = summary self.dirOutput = dirOutput self.contentType = contentType self.model = model self.queueProto = Queue.Queue() self.openHandshakeTimeout = 10 self.closeHandshakeTimeout = 10 # start the thread that takes care of ending the reactor so # the script can finish automatically (without ctrl+c) endingThread = threading.Thread(target=self.endReactor, args=()) endingThread.daemon = True endingThread.start() def prepareUtterance(self): try: utt = self.queue.get_nowait() self.queueProto.put(utt) return True except Queue.Empty: print "getUtterance: no more utterances to process, queue is empty!" return False def endReactor(self): self.queue.join() print "about to stop the reactor!" reactor.stop() # this function gets called every time connectWS is called (once # per WebSocket connection/session) def buildProtocol(self, addr): try: utt = self.queueProto.get_nowait() proto = WSInterfaceProtocol(self, self.queue, self.summary, self.dirOutput, self.contentType) proto.setUtterance(utt) return proto except Queue.Empty: print ("queue should not be empty, otherwise this function " "should not have been called") return None # WebSockets interface to the STT service # # note: an object of this class is created for each WebSocket # connection, every time we call connectWS class WSInterfaceProtocol(WebSocketClientProtocol): def __init__(self, factory, queue, summary, dirOutput, contentType): self.factory = factory self.queue = queue self.summary = summary self.dirOutput = dirOutput self.contentType = contentType self.packetRate = 20 self.listeningMessages = 0 self.timeFirstInterim = -1 self.bytesSent = 0 self.chunkSize = 2000 # in bytes super(self.__class__, self).__init__() print dirOutput print "contentType: " + str(self.contentType) + " queueSize: " + \ str(self.queue.qsize()) def setUtterance(self, utt): self.uttNumber = utt[0] self.uttFilename = utt[1] self.summary[self.uttNumber] = {"hypothesis": "", "status": {"code": "", "reason": ""}} self.fileJson = self.dirOutput + "/" + str(self.uttNumber) + \ ".json.txt" try: os.remove(self.fileJson) except OSError: pass # helper method that sends a chunk of audio if needed (as required # what the specified pacing is) def maybeSendChunk(self, data): def sendChunk(chunk, final=False): self.bytesSent += len(chunk) self.sendMessage(chunk, isBinary=True) if final: self.sendMessage(b'', isBinary=True) if (self.bytesSent + self.chunkSize >= len(data)): if (len(data) > self.bytesSent): sendChunk(data[self.bytesSent:len(data)], True) return sendChunk(data[self.bytesSent:self.bytesSent + self.chunkSize]) self.factory.reactor.callLater(0.01, self.maybeSendChunk, data=data) return def onConnect(self, response): print "onConnect, server connected: {0}".format(response.peer) def onOpen(self): print "onOpen" data = {"action": "start", "content-type": str(self.contentType), "continuous": True, "interim_results": True, "inactivity_timeout": 600} data['word_confidence'] = True data['timestamps'] = True data['max_alternatives'] = 3 print "sendMessage(init)" # send the initialization parameters self.sendMessage(json.dumps(data).encode('utf8')) # start sending audio right away (it will get buffered in the # STT service) print self.uttFilename f = open(str(self.uttFilename), 'rb') self.bytesSent = 0 dataFile = f.read() self.maybeSendChunk(dataFile) print "onOpen ends" def onMessage(self, payload, isBinary): if isBinary: print("Binary message received: {0} bytes".format(len(payload))) else: print(u"Text message received: {0}".format(payload.decode('utf8')))<|fim▁hole|> # if uninitialized, receive the initialization response # from the server jsonObject = json.loads(payload.decode('utf8')) if 'state' in jsonObject: self.listeningMessages += 1 if (self.listeningMessages == 2): print "sending close 1000" # close the connection self.sendClose(1000) # if in streaming elif 'results' in jsonObject: jsonObject = json.loads(payload.decode('utf8')) hypothesis = "" # empty hypothesis if (len(jsonObject['results']) == 0): print "empty hypothesis!" # regular hypothesis else: # dump the message to the output directory jsonObject = json.loads(payload.decode('utf8')) f = open(self.fileJson, "a") f.write(json.dumps(jsonObject, indent=4, sort_keys=True)) f.close() res = jsonObject['results'][0] hypothesis = res['alternatives'][0]['transcript'] bFinal = (res['final'] == True) if bFinal: print "final hypothesis: \"" + hypothesis + "\"" self.summary[self.uttNumber]['hypothesis'] += hypothesis else: print "interim hyp: \"" + hypothesis + "\"" def onClose(self, wasClean, code, reason): print("onClose") print("WebSocket connection closed: {0}".format(reason), "code: ", code, "clean: ", wasClean, "reason: ", reason) self.summary[self.uttNumber]['status']['code'] = code self.summary[self.uttNumber]['status']['reason'] = reason # create a new WebSocket connection if there are still # utterances in the queue that need to be processed self.queue.task_done() if self.factory.prepareUtterance() == False: return # SSL client context: default if self.factory.isSecure: contextFactory = ssl.ClientContextFactory() else: contextFactory = None connectWS(self.factory, contextFactory) # function to check that a value is a positive integer def check_positive_int(value): ivalue = int(value) if ivalue < 1: raise argparse.ArgumentTypeError( "\"%s\" is an invalid positive int value" % value) return ivalue # function to check the credentials format def check_credentials(credentials): elements = credentials.split(":") if (len(elements) == 2): return elements else: raise argparse.ArgumentTypeError( "\"%s\" is not a valid format for the credentials " % credentials) if __name__ == '__main__': # parse command line parameters parser = argparse.ArgumentParser( description=('client to do speech recognition using the WebSocket ' 'interface to the Watson STT service')) parser.add_argument( '-credentials', action='store', dest='credentials', help="Basic Authentication credentials in the form 'username:password'", required=True, type=check_credentials) parser.add_argument( '-in', action='store', dest='fileInput', default='./recordings.txt', help='text file containing audio files') parser.add_argument( '-out', action='store', dest='dirOutput', default='./output', help='output directory') parser.add_argument( '-type', action='store', dest='contentType', default='audio/wav', help='audio content type, for example: \'audio/l16; rate=44100\'') parser.add_argument( '-model', action='store', dest='model', default='en-US_BroadbandModel', help='STT model that will be used') parser.add_argument( '-threads', action='store', dest='threads', default='1', help='number of simultaneous STT sessions', type=check_positive_int) parser.add_argument( '-optout', action='store_true', dest='optOut', help=('specify opt-out header so user data, such as speech and ' 'hypotheses are not logged into the server')) parser.add_argument( '-tokenauth', action='store_true', dest='tokenauth', help='use token based authentication') args = parser.parse_args() # create output directory if necessary if (os.path.isdir(args.dirOutput)): pass else: os.makedirs(args.dirOutput) # logging log.startLogging(sys.stdout) # add audio files to the processing queue q = Queue.Queue() lines = [line.rstrip('\n') for line in open(args.fileInput)] fileNumber = 0 for fileName in(lines): print fileName q.put((fileNumber, fileName)) fileNumber += 1 hostname = "stream.watsonplatform.net" headers = {} if (args.optOut is True): headers['X-WDC-PL-OPT-OUT'] = '1' # authentication header if args.tokenauth: headers['X-Watson-Authorization-Token'] = ( Utils.getAuthenticationToken( "https://" + hostname, 'speech-to-text', args.credentials[0], args.credentials[1])) else: string = args.credentials[0] + ":" + args.credentials[1] headers["Authorization"] = "Basic " + base64.b64encode(string) print headers # create a WS server factory with our protocol url = "wss://" + hostname + "/speech-to-text/api/v1/recognize?model=" \ + args.model summary = {} factory = WSInterfaceFactory(q, summary, args.dirOutput, args.contentType, args.model, url, headers, debug=False) factory.protocol = WSInterfaceProtocol for i in range(min(int(args.threads), q.qsize())): factory.prepareUtterance() # SSL client context: default if factory.isSecure: contextFactory = ssl.ClientContextFactory() else: contextFactory = None connectWS(factory, contextFactory) reactor.run() # dump the hypotheses to the output file fileHypotheses = path_output f = open(fileHypotheses, "w") counter = 1 successful = 0 emptyHypotheses = 0 for key, value in (sorted(summary.items())): if value['status']['code'] == 1000: print (value['status']['code'], " ", value['hypothesis'].encode('utf-8')) successful += 1 if value['hypothesis'][0] == "": emptyHypotheses += 1 else: print (value['status']['code'], " REASON: ", value['status']['reason']) f.write(value['hypothesis'].encode('utf-8') + "\n") counter += 1 f.close() print ("successful sessions: ", successful, " (", len(summary) - successful, " errors) (" + str(emptyHypotheses) + " empty hypotheses)")<|fim▁end|>
<|file_name|>conv.cpp<|end_file_name|><|fim▁begin|>/* Copyright (c) 2005, 2006 by CodeSourcery. All rights reserved. This file is available for license from CodeSourcery, Inc. under the terms of a commercial license and under the GPL. It is not part of the VSIPL++ reference implementation and is not available under the BSD license. */ /** @file benchmarks/conv.cpp @author Jules Bergmann @date 2005-07-11 @brief VSIPL++ Library: Benchmark for 1D Convolution. */ /*********************************************************************** Included Files ***********************************************************************/ #include <iostream> #include <vsip/initfin.hpp> #include <vsip/support.hpp> #include <vsip/math.hpp> #include <vsip/signal.hpp> #include <vsip/opt/dispatch_diagnostics.hpp> #include <vsip_csl/test.hpp> #include "loop.hpp" using namespace vsip; /*********************************************************************** Definitions ***********************************************************************/ template <support_region_type Supp, typename T> struct t_conv1 : Benchmark_base { static length_type const Dec = 1; char const* what() { return "t_conv1"; } float ops_per_point(length_type size) { length_type output_size; if (Supp == support_full) output_size = ((size + coeff_size_ - 2)/Dec) + 1; else if (Supp == support_same) output_size = ((size-1)/Dec) + 1; else /* (Supp == support_min) */ output_size = ((size-1)/Dec) - ((coeff_size_-1)/Dec) + 1; float ops = coeff_size_ * output_size * (vsip::impl::Ops_info<T>::mul + vsip::impl::Ops_info<T>::add); return ops / size; } int riob_per_point(length_type) { return -1; } int wiob_per_point(length_type) { return -1; } int mem_per_point(length_type) { return 2*sizeof(T); } void operator()(length_type size, length_type loop, float& time) { length_type output_size; if (Supp == support_full) output_size = ((size + coeff_size_ - 2)/Dec) + 1; else if (Supp == support_same) output_size = ((size-1)/Dec) + 1; else /* (Supp == support_min) */<|fim▁hole|> output_size = ((size-1)/Dec) - ((coeff_size_-1)/Dec) + 1; Vector<T> in (size, T()); Vector<T> out(output_size); Vector<T> coeff(coeff_size_, T()); coeff(0) = T(1); coeff(1) = T(2); symmetry_type const symmetry = nonsym; typedef Convolution<const_Vector, symmetry, Supp, T> conv_type; conv_type conv(coeff, Domain<1>(size), Dec); vsip::impl::profile::Timer t1; t1.start(); for (index_type l=0; l<loop; ++l) conv(in, out); t1.stop(); time = t1.delta(); } t_conv1(length_type coeff_size) : coeff_size_(coeff_size) {} void diag() { using namespace vsip_csl::dispatcher; typedef typename Dispatcher<op::conv<1, nonsym, Supp, T> >::backend backend; std::cout << "BE: " << Backend_name<backend>::name() << std::endl; } length_type coeff_size_; }; void defaults(Loop1P& loop) { loop.loop_start_ = 5000; loop.start_ = 4; loop.user_param_ = 16; } int test(Loop1P& loop, int what) { typedef complex<float> cf_type; switch (what) { case 1: loop(t_conv1<support_full, float>(loop.user_param_)); break; case 2: loop(t_conv1<support_same, float>(loop.user_param_)); break; case 3: loop(t_conv1<support_min, float>(loop.user_param_)); break; case 4: loop(t_conv1<support_full, cf_type>(loop.user_param_)); break; case 5: loop(t_conv1<support_same, cf_type>(loop.user_param_)); break; case 6: loop(t_conv1<support_min, cf_type>(loop.user_param_)); break; case 0: std::cout << "conv -- 1D convolution\n" << " -1 -- float, support=full\n" << " -2 -- float, support=same\n" << " -3 -- float, support=min\n" << " -4 -- complex<float>, support=full\n" << " -5 -- complex<float>, support=same\n" << " -6 -- complex<float>, support=min\n" << "\n" << " Parameters:\n" << " -param N -- size of coefficient vector (default 16)\n" << " -start N -- starting problem size 2^N (default 4 or 16 points)\n" << " -loop_start N -- initial number of calibration loops (default 5000)\n" ; default: return 0; } return 1; }<|fim▁end|>
<|file_name|>cmp.rs<|end_file_name|><|fim▁begin|>#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cmp::Ordering::{self, Less, Equal, Greater}; // pub trait FixedSizeArray<T> { // /// Converts the array to immutable slice // fn as_slice(&self) -> &[T]; // /// Converts the array to mutable slice // fn as_mut_slice(&mut self) -> &mut [T]; // } // macro_rules! array_impls { // ($($N:expr)+) => { // $( // #[unstable(feature = "core")] // impl<T> FixedSizeArray<T> for [T; $N] { // #[inline] // fn as_slice(&self) -> &[T] { // &self[..] // } // #[inline] // fn as_mut_slice(&mut self) -> &mut [T] { // &mut self[..] // } // } // // #[unstable(feature = "array_as_ref", // reason = "should ideally be implemented for all fixed-sized arrays")] // impl<T> AsRef<[T]> for [T; $N] { // #[inline] // fn as_ref(&self) -> &[T] { // &self[..] // } // } // // #[unstable(feature = "array_as_ref", // reason = "should ideally be implemented for all fixed-sized arrays")] // impl<T> AsMut<[T]> for [T; $N] { // #[inline] // fn as_mut(&mut self) -> &mut [T] { // &mut self[..] // } // } // // #[stable(feature = "rust1", since = "1.0.0")] // impl<T:Copy> Clone for [T; $N] { // fn clone(&self) -> [T; $N] { // *self // } // } // // #[stable(feature = "rust1", since = "1.0.0")] // impl<T: Hash> Hash for [T; $N] { // fn hash<H: hash::Hasher>(&self, state: &mut H) { // Hash::hash(&self[..], state) // } // } // // #[stable(feature = "rust1", since = "1.0.0")] // impl<T: fmt::Debug> fmt::Debug for [T; $N] { // fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // fmt::Debug::fmt(&&self[..], f) // } // } // // #[stable(feature = "rust1", since = "1.0.0")] // impl<'a, T> IntoIterator for &'a [T; $N] { // type Item = &'a T; // type IntoIter = Iter<'a, T>; // // fn into_iter(self) -> Iter<'a, T> { // self.iter() // } // } // // #[stable(feature = "rust1", since = "1.0.0")] // impl<'a, T> IntoIterator for &'a mut [T; $N] { // type Item = &'a mut T; // type IntoIter = IterMut<'a, T>; // // fn into_iter(self) -> IterMut<'a, T> { // self.iter_mut() // } // } // // // NOTE: some less important impls are omitted to reduce code bloat // __impl_slice_eq1! { [A; $N], [B; $N] }<|fim▁hole|> // // __impl_slice_eq2! { [A; $N], &'b mut [B; $N] } // // #[stable(feature = "rust1", since = "1.0.0")] // impl<T:Eq> Eq for [T; $N] { } // // #[stable(feature = "rust1", since = "1.0.0")] // impl<T:PartialOrd> PartialOrd for [T; $N] { // #[inline] // fn partial_cmp(&self, other: &[T; $N]) -> Option<Ordering> { // PartialOrd::partial_cmp(&&self[..], &&other[..]) // } // #[inline] // fn lt(&self, other: &[T; $N]) -> bool { // PartialOrd::lt(&&self[..], &&other[..]) // } // #[inline] // fn le(&self, other: &[T; $N]) -> bool { // PartialOrd::le(&&self[..], &&other[..]) // } // #[inline] // fn ge(&self, other: &[T; $N]) -> bool { // PartialOrd::ge(&&self[..], &&other[..]) // } // #[inline] // fn gt(&self, other: &[T; $N]) -> bool { // PartialOrd::gt(&&self[..], &&other[..]) // } // } // // #[stable(feature = "rust1", since = "1.0.0")] // impl<T:Ord> Ord for [T; $N] { // #[inline] // fn cmp(&self, other: &[T; $N]) -> Ordering { // Ord::cmp(&&self[..], &&other[..]) // } // } // )+ // } // } // array_impls! { // 0 1 2 3 4 5 6 7 8 9 // 10 11 12 13 14 15 16 17 18 19 // 20 21 22 23 24 25 26 27 28 29 // 30 31 32 // } type T = i32; type A = T; type B = T; #[test] fn cmp_test1() { let array_a: [A; 17] = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]; let array_b: [B; 17] = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]; let result: Ordering = array_a.cmp(&array_b); assert_eq!(result, Less); } #[test] fn cmp_test2() { let array_a: [A; 17] = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]; let array_b: [B; 17] = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]; let result: Ordering = array_a.cmp(&array_b); assert_eq!(result, Equal); } #[test] fn cmp_test3() { let array_a: [A; 17] = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]; let array_b: [B; 17] = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]; let result: Ordering = array_a.cmp(&array_b); assert_eq!(result, Greater); } }<|fim▁end|>
// __impl_slice_eq2! { [A; $N], [B] } // __impl_slice_eq2! { [A; $N], &'b [B] } // __impl_slice_eq2! { [A; $N], &'b mut [B] } // // __impl_slice_eq2! { [A; $N], &'b [B; $N] }
<|file_name|>api.quiz.test.js<|end_file_name|><|fim▁begin|>describe("Quiz API Tests", function() { var api; var mock; beforeAll(function(done) { api = Playbasis.quizApi; mock = window.mock; window.acquireBuiltPlaybasis(); done(); }); describe("List Active Quizzes test", function() { beforeAll(function(done) { done(); }); it("should return success", function(done) { api.listOfActiveQuizzes() .then((result) => { done(); }, (e) => { console.log(e.message);}) }); }); describe("Detail of Quiz test", function() { var quizId = "57f5d72ab350cf67308b81c6"; //pre-existing quiz 1 beforeAll(function(done) { done(); }); it("should return success", function(done) { api.detailOfQuiz(quizId) .then((result) => { expect(result.response.result).not.toBe(null); expect(result.response.result.quiz_id).toEqual(quizId); done(); }, (e) => { console.log(e.message);}); }); }); describe("Random Get a Quiz for Player test", function() { beforeAll(function(done) { done(); }); it("should return success", function(done) { api.randomQuizForPlayer(mock.env.playerId) .then((result) => { expect(result.response.result).not.toBe(null); expect(result.response.result.quiz_id).not.toBe(null); done(); }, (e) => { console.log(e.message);}); }); }); describe("List Quiz Done by Player test", function() { beforeAll(function(done) { done(); }); it("should return success", function(done) { api.listQuizDone(mock.env.playerId, 5) .then((result) => { done(); }, (e) => { console.log(e.message);}); }); }); describe("List Pending Quiz by Player test", function() { beforeAll(function(done) { done(); }); it("should return success", function(done) { api.listPendingQuiz(mock.env.playerId, 5) .then((result) => { done(); }, (e) => { console.log(e.message);}); }); }); describe("Get Question from Quiz for Player test", function() { var quizId = "57f5d72ab350cf67308b81c6"; //pre-existing quiz 1 beforeAll(function(done) { done(); }); it("should return success", function(done) { api.getQuestionFromQuiz(quizId, mock.env.playerId) .then((result) => { done(); }, (e) => { console.log(e.message);}); }); }); describe("Get Question (with reset timestamp) from Quiz for Player test", function() { var quizId = "57f5d72ab350cf67308b81c6"; //pre-existing quiz 1 beforeAll(function(done) { done(); }); it("should return success", function(done) { api.getQuestionFromQuiz_resetTimeStamp(quizId, mock.env.playerId) .then((result) => { done(); }, (e) => { console.log(e.message);}); }); }); describe("Answer a Question for Quiz test", function() { var quizId = "57f5d72ab350cf67308b81c6"; // pre-existing quiz 1 var optionId = "1521751f31748deab6333a87"; // pre-existing option 1 for quiz 1 var questionId = "138003ef42931448ab4b02e2"; // pre-existing question for quiz 1 beforeAll(function(done) { done(); }); // ensure to reset progress of quiz after answering question afterAll(function(done) { api.resetQuiz(mock.env.playerId, quizId) .then((result) => { done(); }, (e) => { console.log(e.message);}); }); it("should return success", function(done) { api.answerQuestion(quizId, mock.env.playerId, questionId, optionId) .then((result) => { expect(result.response.result).not.toBe(null); expect(result.response.result.score).toEqual(10); // pre-set done(); }, (e) => { console.log(e.message);}); }); }); describe("Rank Player by Score test", function() { var quizId = "57f5d72ab350cf67308b81c6"; // pre-existing quiz 1 beforeAll(function(done) { done(); }); it("should return success", function(done) { api.rankPlayersByScore(quizId, 10) .then((result) => { done(); }, (e) => { console.log(e.message);}); }); }); describe("Query for Quiz's Statistics test", function() { var quizId = "57f5d72ab350cf67308b81c6"; // pre-existing quiz 1<|fim▁hole|> beforeAll(function(done) { done(); }); it("should return success", function(done) { api.quizStatistics(quizId) .then((result) => { done(); }, (e) => { console.log(e.message);}); }); }); describe("Reset Quiz test", function() { var quizId = "57f5d72ab350cf67308b81c6"; // pre-existing quiz 1 beforeAll(function(done) { done(); }); it("should return success", function(done) { api.resetQuiz(mock.env.playerId, quizId) .then((result) => { done(); }, (e) => { console.log(e.message);}); }); }); });<|fim▁end|>
<|file_name|>test_deeplab.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------- # Deformable Convolutional Networks # Copyright (c) 2016 by Contributors # Copyright (c) 2017 Microsoft # Licensed under The Apache-2.0 License [see LICENSE for details] # Modified by Zheng Zhang # -------------------------------------------------------- import argparse import pprint import logging import time import os import mxnet as mx from config.config import config, generate_config, update_config from config.dataset_conf import dataset from config.network_conf import network from symbols import * from dataset import * from core.loader import TestDataLoader from core.tester import Predictor, pred_eval from utils.load_model import load_param def test_deeplab(network, dataset, image_set, root_path, dataset_path, ctx, prefix, epoch, vis, logger=None, output_path=None): if not logger: assert False, 'require a logger' # print config pprint.pprint(config) logger.info('testing config:{}\n'.format(pprint.pformat(config))) # load symbol and testing data sym = eval('get_' + network + '_test')(num_classes=config.dataset.NUM_CLASSES) imdb = eval(dataset)(image_set, root_path, dataset_path, result_path=output_path) segdb = imdb.gt_segdb() # get test data iter test_data = TestDataLoader(segdb, batch_size=len(ctx)) # load model # arg_params, aux_params = load_param(prefix, epoch, convert=True, ctx=ctx, process=True) arg_params, aux_params = load_param(prefix, epoch, process=True)<|fim▁hole|> arg_shape, _, aux_shape = sym.infer_shape(**data_shape_dict) arg_shape_dict = dict(zip(sym.list_arguments(), arg_shape)) aux_shape_dict = dict(zip(sym.list_auxiliary_states(), aux_shape)) # check parameters for k in sym.list_arguments(): if k in data_shape_dict or k in ['softmax_label']: continue assert k in arg_params, k + ' not initialized' assert arg_params[k].shape == arg_shape_dict[k], \ 'shape inconsistent for ' + k + ' inferred ' + str(arg_shape_dict[k]) + ' provided ' + str(arg_params[k].shape) for k in sym.list_auxiliary_states(): assert k in aux_params, k + ' not initialized' assert aux_params[k].shape == aux_shape_dict[k], \ 'shape inconsistent for ' + k + ' inferred ' + str(aux_shape_dict[k]) + ' provided ' + str(aux_params[k].shape) # decide maximum shape data_names = [k[0] for k in test_data.provide_data_single] label_names = ['softmax_label'] max_data_shape = [[('data', (1, 3, max([v[0] for v in config.SCALES]), max([v[1] for v in config.SCALES])))]] # create predictor predictor = Predictor(sym, data_names, label_names, context=ctx, max_data_shapes=max_data_shape, provide_data=test_data.provide_data, provide_label=test_data.provide_label, arg_params=arg_params, aux_params=aux_params) # start detection pred_eval(predictor, test_data, imdb, vis=vis, logger=logger)<|fim▁end|>
# infer shape data_shape_dict = dict(test_data.provide_data_single)
<|file_name|>oneClickInstallerTest.ts<|end_file_name|><|fim▁begin|>import { Arch, Platform } from "electron-builder" import { copyFile, writeFile } from "fs-extra" import * as path from "path" import { assertThat } from "../helpers/fileAssert" import { app, assertPack, copyTestAsset, modifyPackageJson } from "../helpers/packTester" import { checkHelpers, doTest, expectUpdateMetadata } from "../helpers/winHelper" const nsisTarget = Platform.WINDOWS.createTarget(["nsis"]) function pickSnapshotDefines(defines: any) { return { APP_32_NAME: defines.APP_32_NAME, APP_64_NAME: defines.APP_64_NAME, APP_ARM64_NAME: defines.APP_ARM64_NAME, APP_FILENAME: defines.APP_FILENAME, APP_ID: defines.APP_ID, APP_PACKAGE_NAME: defines.APP_PACKAGE_NAME, APP_PRODUCT_FILENAME: defines.APP_PRODUCT_FILENAME, COMPANY_NAME: defines.COMPANY_NAME, ONE_CLICK: defines.ONE_CLICK, PRODUCT_FILENAME: defines.PRODUCT_FILENAME, PRODUCT_NAME: defines.PRODUCT_NAME, SHORTCUT_NAME: defines.SHORTCUT_NAME, UNINSTALL_DISPLAY_NAME: defines.UNINSTALL_DISPLAY_NAME, } } test( "one-click", app( { targets: Platform.WINDOWS.createTarget(["nsis"], Arch.x64), config: { win: { publisherName: "Foo, Inc", }, publish: { provider: "bintray", owner: "actperepo", package: "TestApp", }, nsis: { deleteAppDataOnUninstall: true, packElevateHelper: false, }, }, }, { signedWin: true, packed: async context => { await checkHelpers(context.getResources(Platform.WINDOWS, Arch.x64), false) await doTest(context.outDir, true, "TestApp Setup", "TestApp", null, false) await expectUpdateMetadata(context, Arch.x64, true) }, } ) ) test.ifAll( "custom guid", app({ targets: Platform.WINDOWS.createTarget(["nsis"], Arch.ia32), config: { appId: "boo", productName: "boo Hub", publish: null, nsis: { guid: "Foo Technologies\\Bar", }, }, }) ) test.ifAll.ifNotCiMac( "multi language license", app( { targets: Platform.WINDOWS.createTarget("nsis"), config: { publish: null, nsis: { uninstallDisplayName: "Hi!!!", createDesktopShortcut: false, }, }, }, { projectDirCreated: projectDir => { return Promise.all([ writeFile(path.join(projectDir, "build", "license_en.txt"), "Hi"), writeFile(path.join(projectDir, "build", "license_ru.txt"), "Привет"), writeFile(path.join(projectDir, "build", "license_ko.txt"), "Привет"), writeFile(path.join(projectDir, "build", "license_fi.txt"), "Привет"), ]) }, } ) ) test.ifAll.ifNotCiMac( "html license", app( { targets: Platform.WINDOWS.createTarget("nsis"), config: { publish: null, nsis: { uninstallDisplayName: "Hi!!!", createDesktopShortcut: false, }, }, }, { projectDirCreated: projectDir => { return Promise.all([ writeFile(path.join(projectDir, "build", "license.html"), '<html><body><p>Hi <a href="https://google.com" target="_blank">google</a></p></body></html>'), ]) }, } ) ) test.ifAll.ifDevOrWinCi( "createDesktopShortcut always", app({ targets: Platform.WINDOWS.createTarget("nsis"), config: { publish: null, nsis: { createDesktopShortcut: "always", }, }, }) ) test.ifDevOrLinuxCi( "perMachine, no run after finish", app( { targets: Platform.WINDOWS.createTarget(["nsis"], Arch.ia32), config: { // wine creates incorrect file names and registry entries for unicode, so, we use ASCII productName: "TestApp", fileAssociations: [ { ext: "foo", name: "Test Foo", }, ], nsis: { perMachine: true, runAfterFinish: false, }, publish: { provider: "generic", // tslint:disable:no-invalid-template-strings url: "https://develar.s3.amazonaws.com/test/${os}/${arch}", }, win: { electronUpdaterCompatibility: ">=2.16", }, }, }, { projectDirCreated: projectDir => { return Promise.all([ copyTestAsset("headerIcon.ico", path.join(projectDir, "build", "foo test space.ico")), copyTestAsset("license.txt", path.join(projectDir, "build", "license.txt")), ]) }, packed: async context => { await expectUpdateMetadata(context) await checkHelpers(context.getResources(Platform.WINDOWS, Arch.ia32), true) await doTest(context.outDir, false) }, } ) ) test.ifNotCiMac("installerHeaderIcon", () => { let headerIconPath: string | null = null return assertPack( "test-app-one", { targets: nsisTarget, effectiveOptionComputed: async it => { const defines = it[0] expect(defines.HEADER_ICO).toEqual(headerIconPath) return false }, }, { projectDirCreated: projectDir => { headerIconPath = path.join(projectDir, "build", "installerHeaderIcon.ico") return Promise.all([copyTestAsset("headerIcon.ico", headerIconPath), copyTestAsset("headerIcon.ico", path.join(projectDir, "build", "uninstallerIcon.ico"))]) }, } ) }) test.ifDevOrLinuxCi( "custom include", app( { targets: nsisTarget }, { projectDirCreated: projectDir => copyTestAsset("installer.nsh", path.join(projectDir, "build", "installer.nsh")), packed: context => Promise.all([ assertThat(path.join(context.projectDir, "build", "customHeader")).isFile(), assertThat(path.join(context.projectDir, "build", "customInit")).isFile(), assertThat(path.join(context.projectDir, "build", "customInstall")).isFile(), ]), } ) ) test.skip( "big file pack",<|fim▁hole|> { targets: nsisTarget, config: { extraResources: ["**/*.mov"], nsis: { differentialPackage: false, }, }, }, { projectDirCreated: async projectDir => { await copyFile("/Volumes/Pegasus/15.02.18.m4v", path.join(projectDir, "foo/bar/video.mov")) }, } ) ) test.ifDevOrLinuxCi( "custom script", app( { targets: nsisTarget }, { projectDirCreated: projectDir => copyTestAsset("installer.nsi", path.join(projectDir, "build", "installer.nsi")), packed: context => assertThat(path.join(context.projectDir, "build", "customInstallerScript")).isFile(), } ) ) test.ifAll.ifNotCiMac( "menuCategory", app( { targets: Platform.WINDOWS.createTarget(["nsis"], Arch.ia32), config: { extraMetadata: { name: "test-menu-category", productName: "Test Menu Category", }, publish: null, nsis: { oneClick: false, menuCategory: true, artifactName: "${productName} CustomName ${version}.${ext}", }, }, }, { projectDirCreated: projectDir => modifyPackageJson(projectDir, data => { data.name = "test-menu-category" }), packed: context => { return doTest(context.outDir, false, "Test Menu Category", "test-menu-category", "Foo Bar") }, } ) ) test.ifNotCiMac( "string menuCategory", app( { targets: Platform.WINDOWS.createTarget(["nsis"], Arch.ia32), config: { extraMetadata: { name: "test-menu-category", productName: "Test Menu Category '", }, publish: null, nsis: { oneClick: false, runAfterFinish: false, menuCategory: "Foo/Bar", // tslint:disable-next-line:no-invalid-template-strings artifactName: "${productName} CustomName ${version}.${ext}", }, }, }, { projectDirCreated: projectDir => modifyPackageJson(projectDir, data => { data.name = "test-menu-category" }), packed: async context => { await doTest(context.outDir, false, "Test Menu Category", "test-menu-category", "Foo Bar") }, } ) ) test.ifDevOrLinuxCi( "file associations per user", app({ targets: Platform.WINDOWS.createTarget(["nsis"], Arch.ia32), config: { publish: null, fileAssociations: [ { ext: "foo", name: "Test Foo", }, ], }, }) ) test.ifWindows( "custom exec name", app({ targets: nsisTarget, config: { productName: "foo", win: { executableName: "Boo", }, }, effectiveOptionComputed: async it => { expect(pickSnapshotDefines(it[0])).toMatchSnapshot() return false }, }) )<|fim▁end|>
app(
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # Copyright (c) 2010 OpenStack, 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. import setuptools <|fim▁hole|>depend_links = setup.parse_dependency_links() setuptools.setup( name='glance', version=version.canonical_version_string(always=True), description='The Glance project provides services for discovering, ' 'registering, and retrieving virtual machine images', license='Apache License (2.0)', author='OpenStack', author_email='[email protected]', url='http://glance.openstack.org/', packages=setuptools.find_packages(exclude=['bin']), test_suite='nose.collector', cmdclass=setup.get_cmdclass(), include_package_data=True, install_requires=requires, dependency_links=depend_links, classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.6', 'Environment :: No Input/Output (Daemon)', ], scripts=['bin/glance', 'bin/glance-api', 'bin/glance-cache-prefetcher', 'bin/glance-cache-pruner', 'bin/glance-cache-manage', 'bin/glance-cache-cleaner', 'bin/glance-control', 'bin/glance-manage', 'bin/glance-registry', 'bin/glance-replicator', 'bin/glance-scrubber'], py_modules=[])<|fim▁end|>
from glance.openstack.common import setup from glance.version import version_info as version requires = setup.parse_requirements()
<|file_name|>ptr_offset_0_plus_0.rs<|end_file_name|><|fim▁begin|>// error-pattern: invalid use of NULL pointer fn main() {<|fim▁hole|><|fim▁end|>
let x = 0 as *mut i32; let _x = x.wrapping_offset(8); // ok, this has no inbounds tag let _x = unsafe { x.offset(0) }; // UB despite offset 0, NULL is never inbounds }
<|file_name|>test_media_player.py<|end_file_name|><|fim▁begin|>"""Tests for Vizio config flow.""" from __future__ import annotations from contextlib import asynccontextmanager from datetime import timedelta from typing import Any from unittest.mock import call, patch import pytest from pytest import raises from pyvizio.api.apps import AppConfig from pyvizio.const import ( APPS, DEVICE_CLASS_SPEAKER as VIZIO_DEVICE_CLASS_SPEAKER, DEVICE_CLASS_TV as VIZIO_DEVICE_CLASS_TV, INPUT_APPS, MAX_VOLUME, UNKNOWN_APP, ) import voluptuous as vol from homeassistant.components.media_player import ( ATTR_INPUT_SOURCE, ATTR_MEDIA_VOLUME_LEVEL, ATTR_MEDIA_VOLUME_MUTED, ATTR_SOUND_MODE, DOMAIN as MP_DOMAIN, SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PREVIOUS_TRACK, SERVICE_SELECT_SOUND_MODE, SERVICE_SELECT_SOURCE, SERVICE_TURN_OFF, SERVICE_TURN_ON, SERVICE_VOLUME_DOWN, SERVICE_VOLUME_MUTE, SERVICE_VOLUME_SET, SERVICE_VOLUME_UP, MediaPlayerDeviceClass, ) from homeassistant.components.media_player.const import ATTR_INPUT_SOURCE_LIST from homeassistant.components.vizio import validate_apps from homeassistant.components.vizio.const import ( CONF_ADDITIONAL_CONFIGS, CONF_APPS, CONF_VOLUME_STEP, DEFAULT_VOLUME_STEP, DOMAIN, SERVICE_UPDATE_SETTING, VIZIO_SCHEMA, ) from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON, STATE_UNAVAILABLE from homeassistant.core import HomeAssistant from homeassistant.util import dt as dt_util<|fim▁hole|> from .const import ( ADDITIONAL_APP_CONFIG, APP_LIST, APP_NAME_LIST, CURRENT_APP, CURRENT_APP_CONFIG, CURRENT_EQ, CURRENT_INPUT, CUSTOM_CONFIG, ENTITY_ID, EQ_LIST, INPUT_LIST, INPUT_LIST_WITH_APPS, MOCK_SPEAKER_APPS_FAILURE, MOCK_SPEAKER_CONFIG, MOCK_TV_APPS_FAILURE, MOCK_TV_WITH_ADDITIONAL_APPS_CONFIG, MOCK_TV_WITH_EXCLUDE_CONFIG, MOCK_TV_WITH_INCLUDE_CONFIG, MOCK_USER_VALID_TV_CONFIG, NAME, UNIQUE_ID, UNKNOWN_APP_CONFIG, VOLUME_STEP, ) from tests.common import MockConfigEntry, async_fire_time_changed async def _add_config_entry_to_hass( hass: HomeAssistant, config_entry: MockConfigEntry ) -> None: config_entry.add_to_hass(hass) assert await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() def _get_ha_power_state(vizio_power_state: bool | None) -> str: """Return HA power state given Vizio power state.""" if vizio_power_state: return STATE_ON if vizio_power_state is False: return STATE_OFF return STATE_UNAVAILABLE def _assert_sources_and_volume(attr: dict[str, Any], vizio_device_class: str) -> None: """Assert source list, source, and volume level based on attr dict and device class.""" assert attr[ATTR_INPUT_SOURCE_LIST] == INPUT_LIST assert attr[ATTR_INPUT_SOURCE] == CURRENT_INPUT assert ( attr["volume_level"] == float(int(MAX_VOLUME[vizio_device_class] / 2)) / MAX_VOLUME[vizio_device_class] ) def _get_attr_and_assert_base_attr( hass: HomeAssistant, device_class: str, power_state: str ) -> dict[str, Any]: """Return entity attributes after asserting name, device class, and power state.""" attr = hass.states.get(ENTITY_ID).attributes assert attr["friendly_name"] == NAME assert attr["device_class"] == device_class assert hass.states.get(ENTITY_ID).state == power_state return attr @asynccontextmanager async def _cm_for_test_setup_without_apps( all_settings: dict[str, Any], vizio_power_state: bool | None ) -> None: """Context manager to setup test for Vizio devices without including app specific patches.""" with patch( "homeassistant.components.vizio.media_player.VizioAsync.get_all_settings", return_value=all_settings, ), patch( "homeassistant.components.vizio.media_player.VizioAsync.get_setting_options", return_value=EQ_LIST, ), patch( "homeassistant.components.vizio.media_player.VizioAsync.get_power_state", return_value=vizio_power_state, ): yield async def _test_setup_tv(hass: HomeAssistant, vizio_power_state: bool | None) -> None: """Test Vizio TV entity setup.""" ha_power_state = _get_ha_power_state(vizio_power_state) config_entry = MockConfigEntry( domain=DOMAIN, data=vol.Schema(VIZIO_SCHEMA)(MOCK_USER_VALID_TV_CONFIG), unique_id=UNIQUE_ID, ) async with _cm_for_test_setup_without_apps( {"volume": int(MAX_VOLUME[VIZIO_DEVICE_CLASS_TV] / 2), "mute": "Off"}, vizio_power_state, ): await _add_config_entry_to_hass(hass, config_entry) attr = _get_attr_and_assert_base_attr( hass, MediaPlayerDeviceClass.TV, ha_power_state ) if ha_power_state == STATE_ON: _assert_sources_and_volume(attr, VIZIO_DEVICE_CLASS_TV) assert "sound_mode" not in attr async def _test_setup_speaker( hass: HomeAssistant, vizio_power_state: bool | None ) -> None: """Test Vizio Speaker entity setup.""" ha_power_state = _get_ha_power_state(vizio_power_state) config_entry = MockConfigEntry( domain=DOMAIN, data=vol.Schema(VIZIO_SCHEMA)(MOCK_SPEAKER_CONFIG), unique_id=UNIQUE_ID, ) audio_settings = { "volume": int(MAX_VOLUME[VIZIO_DEVICE_CLASS_SPEAKER] / 2), "mute": "Off", "eq": CURRENT_EQ, } async with _cm_for_test_setup_without_apps( audio_settings, vizio_power_state, ): with patch( "homeassistant.components.vizio.media_player.VizioAsync.get_current_app_config", ) as service_call: await _add_config_entry_to_hass(hass, config_entry) attr = _get_attr_and_assert_base_attr( hass, MediaPlayerDeviceClass.SPEAKER, ha_power_state ) if ha_power_state == STATE_ON: _assert_sources_and_volume(attr, VIZIO_DEVICE_CLASS_SPEAKER) assert not service_call.called assert "sound_mode" in attr @asynccontextmanager async def _cm_for_test_setup_tv_with_apps( hass: HomeAssistant, device_config: dict[str, Any], app_config: dict[str, Any] ) -> None: """Context manager to setup test for Vizio TV with support for apps.""" config_entry = MockConfigEntry( domain=DOMAIN, data=vol.Schema(VIZIO_SCHEMA)(device_config), unique_id=UNIQUE_ID ) async with _cm_for_test_setup_without_apps( {"volume": int(MAX_VOLUME[VIZIO_DEVICE_CLASS_TV] / 2), "mute": "Off"}, True, ): with patch( "homeassistant.components.vizio.media_player.VizioAsync.get_current_app_config", return_value=AppConfig(**app_config), ): await _add_config_entry_to_hass(hass, config_entry) attr = _get_attr_and_assert_base_attr( hass, MediaPlayerDeviceClass.TV, STATE_ON ) assert ( attr["volume_level"] == float(int(MAX_VOLUME[VIZIO_DEVICE_CLASS_TV] / 2)) / MAX_VOLUME[VIZIO_DEVICE_CLASS_TV] ) yield def _assert_source_list_with_apps( list_to_test: list[str], attr: dict[str, Any] ) -> None: """Assert source list matches list_to_test after removing INPUT_APPS from list.""" for app_to_remove in INPUT_APPS: if app_to_remove in list_to_test: list_to_test.remove(app_to_remove) assert attr[ATTR_INPUT_SOURCE_LIST] == list_to_test async def _test_service( hass: HomeAssistant, domain: str, vizio_func_name: str, ha_service_name: str, additional_service_data: dict[str, Any] | None, *args, **kwargs, ) -> None: """Test generic Vizio media player entity service.""" kwargs["log_api_exception"] = False service_data = {ATTR_ENTITY_ID: ENTITY_ID} if additional_service_data: service_data.update(additional_service_data) with patch( f"homeassistant.components.vizio.media_player.VizioAsync.{vizio_func_name}" ) as service_call: await hass.services.async_call( domain, ha_service_name, service_data=service_data, blocking=True, ) assert service_call.called if args or kwargs: assert service_call.call_args == call(*args, **kwargs) async def test_speaker_on( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_update: pytest.fixture, ) -> None: """Test Vizio Speaker entity setup when on.""" await _test_setup_speaker(hass, True) async def test_speaker_off( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_update: pytest.fixture, ) -> None: """Test Vizio Speaker entity setup when off.""" await _test_setup_speaker(hass, False) async def test_speaker_unavailable( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_update: pytest.fixture, ) -> None: """Test Vizio Speaker entity setup when unavailable.""" await _test_setup_speaker(hass, None) async def test_init_tv_on( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_update: pytest.fixture, ) -> None: """Test Vizio TV entity setup when on.""" await _test_setup_tv(hass, True) async def test_init_tv_off( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_update: pytest.fixture, ) -> None: """Test Vizio TV entity setup when off.""" await _test_setup_tv(hass, False) async def test_init_tv_unavailable( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_update: pytest.fixture, ) -> None: """Test Vizio TV entity setup when unavailable.""" await _test_setup_tv(hass, None) async def test_setup_unavailable_speaker( hass: HomeAssistant, vizio_cant_connect: pytest.fixture ) -> None: """Test speaker entity sets up as unavailable.""" config_entry = MockConfigEntry( domain=DOMAIN, data=MOCK_SPEAKER_CONFIG, unique_id=UNIQUE_ID ) await _add_config_entry_to_hass(hass, config_entry) assert len(hass.states.async_entity_ids(MP_DOMAIN)) == 1 assert hass.states.get("media_player.vizio").state == STATE_UNAVAILABLE async def test_setup_unavailable_tv( hass: HomeAssistant, vizio_cant_connect: pytest.fixture ) -> None: """Test TV entity sets up as unavailable.""" config_entry = MockConfigEntry( domain=DOMAIN, data=MOCK_USER_VALID_TV_CONFIG, unique_id=UNIQUE_ID ) await _add_config_entry_to_hass(hass, config_entry) assert len(hass.states.async_entity_ids(MP_DOMAIN)) == 1 assert hass.states.get("media_player.vizio").state == STATE_UNAVAILABLE async def test_services( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_update: pytest.fixture, ) -> None: """Test all Vizio media player entity services.""" await _test_setup_tv(hass, True) await _test_service(hass, MP_DOMAIN, "pow_on", SERVICE_TURN_ON, None) await _test_service(hass, MP_DOMAIN, "pow_off", SERVICE_TURN_OFF, None) await _test_service( hass, MP_DOMAIN, "mute_on", SERVICE_VOLUME_MUTE, {ATTR_MEDIA_VOLUME_MUTED: True}, ) await _test_service( hass, MP_DOMAIN, "mute_off", SERVICE_VOLUME_MUTE, {ATTR_MEDIA_VOLUME_MUTED: False}, ) await _test_service( hass, MP_DOMAIN, "set_input", SERVICE_SELECT_SOURCE, {ATTR_INPUT_SOURCE: "USB"}, "USB", ) await _test_service( hass, MP_DOMAIN, "vol_up", SERVICE_VOLUME_UP, None, num=DEFAULT_VOLUME_STEP ) await _test_service( hass, MP_DOMAIN, "vol_down", SERVICE_VOLUME_DOWN, None, num=DEFAULT_VOLUME_STEP ) await _test_service( hass, MP_DOMAIN, "vol_up", SERVICE_VOLUME_SET, {ATTR_MEDIA_VOLUME_LEVEL: 1}, num=(100 - 15), ) await _test_service( hass, MP_DOMAIN, "vol_down", SERVICE_VOLUME_SET, {ATTR_MEDIA_VOLUME_LEVEL: 0}, num=(15 - 0), ) await _test_service(hass, MP_DOMAIN, "ch_up", SERVICE_MEDIA_NEXT_TRACK, None) await _test_service(hass, MP_DOMAIN, "ch_down", SERVICE_MEDIA_PREVIOUS_TRACK, None) await _test_service( hass, MP_DOMAIN, "set_setting", SERVICE_SELECT_SOUND_MODE, {ATTR_SOUND_MODE: "Music"}, "audio", "eq", "Music", ) # Test that the update_setting service does config validation/transformation correctly await _test_service( hass, DOMAIN, "set_setting", SERVICE_UPDATE_SETTING, {"setting_type": "Audio", "setting_name": "AV Delay", "new_value": "0"}, "audio", "av_delay", 0, ) await _test_service( hass, DOMAIN, "set_setting", SERVICE_UPDATE_SETTING, {"setting_type": "Audio", "setting_name": "EQ", "new_value": "Music"}, "audio", "eq", "Music", ) async def test_options_update( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_update: pytest.fixture, ) -> None: """Test when config entry update event fires.""" await _test_setup_speaker(hass, True) config_entry = hass.config_entries.async_entries(DOMAIN)[0] assert config_entry.options new_options = config_entry.options.copy() updated_options = {CONF_VOLUME_STEP: VOLUME_STEP} new_options.update(updated_options) hass.config_entries.async_update_entry( entry=config_entry, options=new_options, ) assert config_entry.options == updated_options await _test_service( hass, MP_DOMAIN, "vol_up", SERVICE_VOLUME_UP, None, num=VOLUME_STEP ) async def _test_update_availability_switch( hass: HomeAssistant, initial_power_state: bool | None, final_power_state: bool | None, caplog: pytest.fixture, ) -> None: now = dt_util.utcnow() future_interval = timedelta(minutes=1) # Setup device as if time is right now with patch("homeassistant.util.dt.utcnow", return_value=now): await _test_setup_speaker(hass, initial_power_state) # Clear captured logs so that only availability state changes are captured for # future assertion caplog.clear() # Fast forward time to future twice to trigger update and assert vizio log message for i in range(1, 3): future = now + (future_interval * i) with patch( "homeassistant.components.vizio.media_player.VizioAsync.get_power_state", return_value=final_power_state, ), patch("homeassistant.util.dt.utcnow", return_value=future), patch( "homeassistant.util.utcnow", return_value=future ): async_fire_time_changed(hass, future) await hass.async_block_till_done() if final_power_state is None: assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE else: assert hass.states.get(ENTITY_ID).state != STATE_UNAVAILABLE # Ensure connection status messages from vizio.media_player appear exactly once # (on availability state change) vizio_log_list = [ log for log in caplog.records if log.name == "homeassistant.components.vizio.media_player" ] assert len(vizio_log_list) == 1 async def test_update_unavailable_to_available( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_update: pytest.fixture, caplog: pytest.fixture, ) -> None: """Test device becomes available after being unavailable.""" await _test_update_availability_switch(hass, None, True, caplog) async def test_update_available_to_unavailable( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_update: pytest.fixture, caplog: pytest.fixture, ) -> None: """Test device becomes unavailable after being available.""" await _test_update_availability_switch(hass, True, None, caplog) async def test_setup_with_apps( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_update_with_apps: pytest.fixture, caplog: pytest.fixture, ) -> None: """Test device setup with apps.""" async with _cm_for_test_setup_tv_with_apps( hass, MOCK_USER_VALID_TV_CONFIG, CURRENT_APP_CONFIG ): attr = hass.states.get(ENTITY_ID).attributes _assert_source_list_with_apps(list(INPUT_LIST_WITH_APPS + APP_NAME_LIST), attr) assert CURRENT_APP in attr[ATTR_INPUT_SOURCE_LIST] assert attr[ATTR_INPUT_SOURCE] == CURRENT_APP assert attr["app_name"] == CURRENT_APP assert "app_id" not in attr await _test_service( hass, MP_DOMAIN, "launch_app", SERVICE_SELECT_SOURCE, {ATTR_INPUT_SOURCE: CURRENT_APP}, CURRENT_APP, APP_LIST, ) async def test_setup_with_apps_include( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_update_with_apps: pytest.fixture, caplog: pytest.fixture, ) -> None: """Test device setup with apps and apps["include"] in config.""" async with _cm_for_test_setup_tv_with_apps( hass, MOCK_TV_WITH_INCLUDE_CONFIG, CURRENT_APP_CONFIG ): attr = hass.states.get(ENTITY_ID).attributes _assert_source_list_with_apps(list(INPUT_LIST_WITH_APPS + [CURRENT_APP]), attr) assert CURRENT_APP in attr[ATTR_INPUT_SOURCE_LIST] assert attr[ATTR_INPUT_SOURCE] == CURRENT_APP assert attr["app_name"] == CURRENT_APP assert "app_id" not in attr async def test_setup_with_apps_exclude( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_update_with_apps: pytest.fixture, caplog: pytest.fixture, ) -> None: """Test device setup with apps and apps["exclude"] in config.""" async with _cm_for_test_setup_tv_with_apps( hass, MOCK_TV_WITH_EXCLUDE_CONFIG, CURRENT_APP_CONFIG ): attr = hass.states.get(ENTITY_ID).attributes _assert_source_list_with_apps(list(INPUT_LIST_WITH_APPS + [CURRENT_APP]), attr) assert CURRENT_APP in attr[ATTR_INPUT_SOURCE_LIST] assert attr[ATTR_INPUT_SOURCE] == CURRENT_APP assert attr["app_name"] == CURRENT_APP assert "app_id" not in attr async def test_setup_with_apps_additional_apps_config( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_update_with_apps: pytest.fixture, caplog: pytest.fixture, ) -> None: """Test device setup with apps and apps["additional_configs"] in config.""" async with _cm_for_test_setup_tv_with_apps( hass, MOCK_TV_WITH_ADDITIONAL_APPS_CONFIG, ADDITIONAL_APP_CONFIG["config"], ): attr = hass.states.get(ENTITY_ID).attributes assert attr[ATTR_INPUT_SOURCE_LIST].count(CURRENT_APP) == 1 _assert_source_list_with_apps( list( INPUT_LIST_WITH_APPS + APP_NAME_LIST + [ app["name"] for app in MOCK_TV_WITH_ADDITIONAL_APPS_CONFIG[CONF_APPS][ CONF_ADDITIONAL_CONFIGS ] if app["name"] not in APP_NAME_LIST ] ), attr, ) assert ADDITIONAL_APP_CONFIG["name"] in attr[ATTR_INPUT_SOURCE_LIST] assert attr[ATTR_INPUT_SOURCE] == ADDITIONAL_APP_CONFIG["name"] assert attr["app_name"] == ADDITIONAL_APP_CONFIG["name"] assert "app_id" not in attr await _test_service( hass, MP_DOMAIN, "launch_app", SERVICE_SELECT_SOURCE, {ATTR_INPUT_SOURCE: "Netflix"}, "Netflix", APP_LIST, ) await _test_service( hass, MP_DOMAIN, "launch_app_config", SERVICE_SELECT_SOURCE, {ATTR_INPUT_SOURCE: CURRENT_APP}, **CUSTOM_CONFIG, ) # Test that invalid app does nothing with patch( "homeassistant.components.vizio.media_player.VizioAsync.launch_app" ) as service_call1, patch( "homeassistant.components.vizio.media_player.VizioAsync.launch_app_config" ) as service_call2: await hass.services.async_call( MP_DOMAIN, SERVICE_SELECT_SOURCE, service_data={ATTR_ENTITY_ID: ENTITY_ID, ATTR_INPUT_SOURCE: "_"}, blocking=True, ) assert not service_call1.called assert not service_call2.called def test_invalid_apps_config(hass: HomeAssistant): """Test that schema validation fails on certain conditions.""" with raises(vol.Invalid): vol.Schema(vol.All(VIZIO_SCHEMA, validate_apps))(MOCK_TV_APPS_FAILURE) with raises(vol.Invalid): vol.Schema(vol.All(VIZIO_SCHEMA, validate_apps))(MOCK_SPEAKER_APPS_FAILURE) async def test_setup_with_unknown_app_config( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_update_with_apps: pytest.fixture, caplog: pytest.fixture, ) -> None: """Test device setup with apps where app config returned is unknown.""" async with _cm_for_test_setup_tv_with_apps( hass, MOCK_USER_VALID_TV_CONFIG, UNKNOWN_APP_CONFIG ): attr = hass.states.get(ENTITY_ID).attributes _assert_source_list_with_apps(list(INPUT_LIST_WITH_APPS + APP_NAME_LIST), attr) assert attr[ATTR_INPUT_SOURCE] == UNKNOWN_APP assert attr["app_name"] == UNKNOWN_APP assert attr["app_id"] == UNKNOWN_APP_CONFIG async def test_setup_with_no_running_app( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_update_with_apps: pytest.fixture, caplog: pytest.fixture, ) -> None: """Test device setup with apps where no app is running.""" async with _cm_for_test_setup_tv_with_apps( hass, MOCK_USER_VALID_TV_CONFIG, vars(AppConfig()) ): attr = hass.states.get(ENTITY_ID).attributes _assert_source_list_with_apps(list(INPUT_LIST_WITH_APPS + APP_NAME_LIST), attr) assert attr[ATTR_INPUT_SOURCE] == "CAST" assert "app_id" not in attr assert "app_name" not in attr async def test_setup_tv_without_mute( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_update: pytest.fixture, ) -> None: """Test Vizio TV entity setup when mute property isn't returned by Vizio API.""" config_entry = MockConfigEntry( domain=DOMAIN, data=vol.Schema(VIZIO_SCHEMA)(MOCK_USER_VALID_TV_CONFIG), unique_id=UNIQUE_ID, ) async with _cm_for_test_setup_without_apps( {"volume": int(MAX_VOLUME[VIZIO_DEVICE_CLASS_TV] / 2)}, STATE_ON, ): await _add_config_entry_to_hass(hass, config_entry) attr = _get_attr_and_assert_base_attr(hass, MediaPlayerDeviceClass.TV, STATE_ON) _assert_sources_and_volume(attr, VIZIO_DEVICE_CLASS_TV) assert "sound_mode" not in attr assert "is_volume_muted" not in attr async def test_apps_update( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_update_with_apps: pytest.fixture, caplog: pytest.fixture, ) -> None: """Test device setup with apps where no app is running.""" with patch( "homeassistant.components.vizio.gen_apps_list_from_url", return_value=None, ): async with _cm_for_test_setup_tv_with_apps( hass, MOCK_USER_VALID_TV_CONFIG, vars(AppConfig()) ): # Check source list, remove TV inputs, and verify that the integration is # using the default APPS list sources = hass.states.get(ENTITY_ID).attributes[ATTR_INPUT_SOURCE_LIST] apps = list(set(sources) - set(INPUT_LIST)) assert len(apps) == len(APPS) with patch( "homeassistant.components.vizio.gen_apps_list_from_url", return_value=APP_LIST, ): async_fire_time_changed(hass, dt_util.now() + timedelta(days=2)) await hass.async_block_till_done() # Check source list, remove TV inputs, and verify that the integration is # now using the APP_LIST list sources = hass.states.get(ENTITY_ID).attributes[ATTR_INPUT_SOURCE_LIST] apps = list(set(sources) - set(INPUT_LIST)) assert len(apps) == len(APP_LIST) async def test_vizio_update_with_apps_on_input( hass: HomeAssistant, vizio_connect, vizio_update_with_apps_on_input ) -> None: """Test a vizio TV with apps that is on a TV input.""" config_entry = MockConfigEntry( domain=DOMAIN, data=vol.Schema(VIZIO_SCHEMA)(MOCK_USER_VALID_TV_CONFIG), unique_id=UNIQUE_ID, ) await _add_config_entry_to_hass(hass, config_entry) attr = _get_attr_and_assert_base_attr(hass, MediaPlayerDeviceClass.TV, STATE_ON) # app ID should not be in the attributes assert "app_id" not in attr<|fim▁end|>
<|file_name|>ProjectIntegrationTest.java<|end_file_name|><|fim▁begin|>/* * Copyright 2012-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.ide.intellij; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import com.facebook.buck.android.AssumeAndroidPlatform; import com.facebook.buck.testutil.ProcessResult; import com.facebook.buck.testutil.TemporaryPaths; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.TestDataHelper; import com.facebook.buck.util.environment.Platform; import com.facebook.buck.util.xml.XmlDomParser; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import java.io.File; import java.io.IOException; import org.hamcrest.Matchers; import org.junit.Assume; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.w3c.dom.Node; public class ProjectIntegrationTest { @Rule public TemporaryPaths temporaryFolder = new TemporaryPaths(); @Before public void setUp() throws Exception { // These tests consistently fail on Windows due to path separator issues. Assume.assumeFalse(Platform.detect() == Platform.WINDOWS); } @Test public void testAndroidLibraryProject() throws InterruptedException, IOException { runBuckProjectAndVerify("android_library"); } @Test public void testAndroidBinaryProject() throws InterruptedException, IOException { runBuckProjectAndVerify("android_binary"); } @Test public void testVersion2BuckProject() throws InterruptedException, IOException { runBuckProjectAndVerify("project1"); } @Test public void testVersion2BuckProjectWithoutAutogeneratingSources() throws InterruptedException, IOException { runBuckProjectAndVerify("project_without_autogeneration"); } @Test public void testVersion2BuckProjectSlice() throws InterruptedException, IOException { runBuckProjectAndVerify("project_slice", "--without-tests", "modules/dep1:dep1"); } @Test public void testVersion2BuckProjectSourceMerging() throws InterruptedException, IOException { runBuckProjectAndVerify("aggregation"); } @Test public void testBuckProjectWithCustomAndroidSdks() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_custom_android_sdks"); } @Test public void testBuckProjectWithCustomJavaSdks() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_custom_java_sdks"); } @Test public void testBuckProjectWithIntellijSdk() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_intellij_sdk"); } @Test public void testVersion2BuckProjectWithProjectSettings() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_project_settings"); } @Test public void testVersion2BuckProjectWithScripts() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_scripts", "//modules/dep1:dep1"); } @Test public void testVersion2BuckProjectWithUnusedLibraries() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_with_unused_libraries", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project"); result.assertSuccess("buck project should exit cleanly"); assertFalse(workspace.resolve(".idea/libraries/library_libs_jsr305.xml").toFile().exists()); } @Test public void testVersion2BuckProjectWithExcludedResources() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_excluded_resources"); } @Test public void testVersion2BuckProjectWithAssets() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_assets"); } @Test public void testVersion2BuckProjectWithLanguageLevel() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_language_level"); } @Test public void testVersion2BuckProjectWithOutputUrl() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_output_url"); } @Test public void testVersion2BuckProjectWithJavaResources() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_java_resources"); } public void testVersion2BuckProjectWithExtraOutputModules() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_extra_output_modules"); } @Test public void testVersion2BuckProjectWithGeneratedSources() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_generated_sources"); } @Test public void testBuckProjectWithSubdirGlobResources() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_subdir_glob_resources"); } @Test public void testRobolectricTestRule() throws InterruptedException, IOException { runBuckProjectAndVerify("robolectric_test"); } @Test public void testAndroidResourcesInDependencies() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_android_resources"); } @Test public void testPrebuiltJarWithJavadoc() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_prebuilt_jar"); } @Test public void testZipFile() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_zipfile"); } @Test public void testAndroidResourcesAndLibraryInTheSameFolder() throws InterruptedException, IOException { runBuckProjectAndVerify("android_resources_in_the_same_folder"); } @Test public void testAndroidResourcesWithPackagesAtTheSameLocation() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_multiple_resources_with_package_names"); } @Test public void testCxxLibrary() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_cxx_library"); } @Test public void testAggregatingCxxLibrary() throws InterruptedException, IOException { runBuckProjectAndVerify("aggregation_with_cxx_library"); } @Test public void testSavingGeneratedFilesList() throws InterruptedException, IOException { runBuckProjectAndVerify( "save_generated_files_list", "--file-with-list-of-generated-files", ".idea/generated-files.txt"); } @Test public void testMultipleLibraries() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_multiple_libraries"); } @Test public void testProjectWithIgnoredTargets() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_ignored_targets"); } @Test public void testProjectWithCustomPackages() throws InterruptedException, IOException { runBuckProjectAndVerify("aggregation_with_custom_packages"); } @Test public void testAndroidResourceAggregation() throws InterruptedException, IOException { runBuckProjectAndVerify("android_resource_aggregation"); } @Test public void testAndroidResourceAggregationWithLimit() throws InterruptedException, IOException { runBuckProjectAndVerify("android_resource_aggregation_with_limit"); } @Test public void testProjectIncludesTestsByDefault() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_tests_by_default", "//modules/lib:lib"); } @Test public void testProjectExcludesTestsWhenRequested() throws InterruptedException, IOException { runBuckProjectAndVerify("project_without_tests", "--without-tests", "//modules/lib:lib"); } @Test public void testProjectExcludesDepTestsWhenRequested() throws InterruptedException, IOException { runBuckProjectAndVerify( "project_without_dep_tests", "--without-dependencies-tests", "//modules/lib:lib"); } @Test public void testUpdatingExistingWorkspace() throws InterruptedException, IOException { runBuckProjectAndVerify("update_existing_workspace"); } @Test public void testCreateNewWorkspace() throws InterruptedException, IOException { runBuckProjectAndVerify("create_new_workspace"); } @Test public void testUpdateMalformedWorkspace() throws InterruptedException, IOException { runBuckProjectAndVerify("update_malformed_workspace"); } @Test public void testUpdateWorkspaceWithoutIgnoredNodes() throws InterruptedException, IOException { runBuckProjectAndVerify("update_workspace_without_ignored_nodes"); } @Test public void testUpdateWorkspaceWithoutManagerNode() throws InterruptedException, IOException { runBuckProjectAndVerify("update_workspace_without_manager_node"); } @Test public void testUpdateWorkspaceWithoutProjectNode() throws InterruptedException, IOException { runBuckProjectAndVerify("update_workspace_without_project_node"); } @Test public void testProjectWthPackageBoundaryException() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_package_boundary_exception", "//project2:lib"); } @Test public void testProjectWithProjectRoot() throws InterruptedException, IOException { runBuckProjectAndVerify( "project_with_project_root", "--intellij-project-root", "project1", "--intellij-include-transitive-dependencies", "--intellij-module-group-name", "", "//project1/lib:lib"); } @Test public void testGeneratingAndroidManifest() throws InterruptedException, IOException { runBuckProjectAndVerify("generate_android_manifest"); } @Test public void testGeneratingAndroidManifestWithMinSdkWithDifferentVersionsFromManifest() throws InterruptedException, IOException { runBuckProjectAndVerify("min_sdk_version_different_from_manifests"); } @Test public void testGeneratingAndroidManifestWithMinSdkFromBinaryManifest() throws InterruptedException, IOException { runBuckProjectAndVerify("min_sdk_version_from_binary_manifest"); } @Test public void testGeneratingAndroidManifestWithMinSdkFromBuckConfig() throws InterruptedException, IOException { runBuckProjectAndVerify("min_sdk_version_from_buck_config"); } @Test public void testGeneratingAndroidManifestWithNoMinSdkConfig() throws InterruptedException, IOException { runBuckProjectAndVerify("min_sdk_version_with_no_config"); } @Test public void testPreprocessScript() throws InterruptedException, IOException { ProcessResult result = runBuckProjectAndVerify("preprocess_script_test"); assertEquals("intellij", result.getStdout().trim()); } @Test public void testScalaProject() throws InterruptedException, IOException { runBuckProjectAndVerify("scala_project"); } @Test public void testIgnoredPathAddedToExcludedFolders() throws InterruptedException, IOException { runBuckProjectAndVerify("ignored_excluded"); } @Test public void testBuckModuleRegenerateSubproject() throws Exception { AssumeAndroidPlatform.assumeSdkIsAvailable(); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "incrementalProject", temporaryFolder.newFolder()) .setUp(); final String extraModuleFilePath = "modules/extra/modules_extra.iml"; final File extraModuleFile = workspace.getPath(extraModuleFilePath).toFile(); workspace .runBuckCommand("project", "--intellij-aggregation-mode=none", "//modules/tip:tip") .assertSuccess(); assertFalse(extraModuleFile.exists()); final String modulesBefore = workspace.getFileContents(".idea/modules.xml"); final String fileXPath = String.format( "/project/component/modules/module[contains(@filepath,'%s')]", extraModuleFilePath); assertThat(XmlDomParser.parse(modulesBefore), Matchers.not(Matchers.hasXPath(fileXPath)));<|fim▁hole|> // Run regenerate on the new modules workspace .runBuckCommand( "project", "--intellij-aggregation-mode=none", "--update", "//modules/extra:extra") .assertSuccess(); assertTrue(extraModuleFile.exists()); final String modulesAfter = workspace.getFileContents(".idea/modules.xml"); assertThat(XmlDomParser.parse(modulesAfter), Matchers.hasXPath(fileXPath)); workspace.verify(); } @Test public void testBuckModuleRegenerateSubprojectNoOp() throws InterruptedException, IOException { AssumeAndroidPlatform.assumeSdkIsAvailable(); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "incrementalProject", temporaryFolder.newFolder()) .setUp(); workspace .runBuckCommand( "project", "--intellij-aggregation-mode=none", "//modules/tip:tip", "//modules/extra:extra") .assertSuccess(); workspace.verify(); // Run regenerate, should be a no-op relative to previous workspace .runBuckCommand( "project", "--intellij-aggregation-mode=none", "--update", "//modules/extra:extra") .assertSuccess(); workspace.verify(); } @Test public void testCrossCellIntelliJProject() throws Exception { AssumeAndroidPlatform.assumeSdkIsAvailable(); ProjectWorkspace primary = TestDataHelper.createProjectWorkspaceForScenario( this, "inter-cell/primary", temporaryFolder.newFolder()); primary.setUp(); ProjectWorkspace secondary = TestDataHelper.createProjectWorkspaceForScenario( this, "inter-cell/secondary", temporaryFolder.newFolder()); secondary.setUp(); TestDataHelper.overrideBuckconfig( primary, ImmutableMap.of( "repositories", ImmutableMap.of("secondary", secondary.getPath(".").normalize().toString()))); // First try with cross-cell enabled String target = "//apps/sample:app_with_cross_cell_android_lib"; ProcessResult result = primary.runBuckCommand( "project", "--config", "project.embedded_cell_buck_out_enabled=true", "--ide", "intellij", target); result.assertSuccess(); String libImlPath = ".idea/libraries/secondary__java_com_crosscell_crosscell.xml"; Node doc = XmlDomParser.parse(primary.getFileContents(libImlPath)); String urlXpath = "/component/library/CLASSES/root/@url"; // Assert that the library URL is inside the project root assertThat( doc, Matchers.hasXPath( urlXpath, Matchers.startsWith("jar://$PROJECT_DIR$/buck-out/cells/secondary/gen/"))); result = primary.runBuckCommand( "project", "--config", "project.embedded_cell_buck_out_enabled=false", "--ide", "intellij", target); result.assertSuccess(); Node doc2 = XmlDomParser.parse(primary.getFileContents(libImlPath)); // Assert that the library URL is outside the project root assertThat(doc2, Matchers.hasXPath(urlXpath, Matchers.startsWith("jar://$PROJECT_DIR$/.."))); } private ProcessResult runBuckProjectAndVerify(String folderWithTestData, String... commandArgs) throws InterruptedException, IOException { AssumeAndroidPlatform.assumeSdkIsAvailable(); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, folderWithTestData, temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand(Lists.asList("project", commandArgs).toArray(new String[0])); result.assertSuccess("buck project should exit cleanly"); workspace.verify(); return result; } }<|fim▁end|>
<|file_name|>hdfs_disk_usage_per_datanode.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # -*- coding: utf-8 -*- # # Author: Joseph Herlant <[email protected]> # File name: hdfs_disk_usage_per_datanode.py # Creation date: 2014-10-08 # # Distributed under terms of the GNU GPLv3 license. """ This nagios active check parses the Hadoop HDFS web interface url: http://<namenode>:<port>/dfsnodelist.jsp?whatNodes=LIVE to check for active datanodes that use disk beyond the given thresholds. The output includes performance datas and is truncated if longer than 1024 chars. Tested on: Hadoop CDH3U5 """ __author__ = 'Joseph Herlant' __copyright__ = 'Copyright 2014, Joseph Herlant' __credits__ = ['Joseph Herlant'] __license__ = 'GNU GPLv3' __version__ = '1.0.2' __maintainer__ = 'Joseph Herlant' __email__ = '[email protected]' __status__ = 'Production' __website__ = 'https://github.com/aerostitch/' from mechanize import Browser from BeautifulSoup import BeautifulSoup import argparse, sys if __name__ == '__main__': # use -h argument to get help parser = argparse.ArgumentParser( description='A Nagios check to verify all datanodes disk usage in \ an HDFS cluster from the namenode web interface.') parser.add_argument('-n', '--namenode', required=True, help='hostname of the namenode of the cluster') parser.add_argument('-p', '--port', type=int, default=50070, help='port of the namenode http interface. \ Defaults to 50070.') parser.add_argument('-w', '--warning', type=int, default=80, help='warning threshold. Defaults to 80.') parser.add_argument('-c', '--critical', type=int, default=90, help='critical threshold. Defaults to 90.') args = parser.parse_args() # Get the web page from the namenode url = "http://%s:%d/dfsnodelist.jsp?whatNodes=LIVE" % \ (args.namenode, args.port) try: page = Browser().open(url) except IOError: print 'CRITICAL: Cannot access namenode interface on %s:%d!' % \ (args.namenode, args.port) sys.exit(2) # parse the page html = page.read() soup = BeautifulSoup(html) datanodes = soup.findAll('td', {'class' : 'name'}) pcused = soup.findAll('td', {'class' : 'pcused', 'align' : 'right'}) w_msg = '' c_msg = '' perfdata = '' for (idx, node) in enumerate(datanodes): pct = float(pcused[idx].contents[0].strip()) node = datanodes[idx].findChildren('a')[0].contents[0].strip() if pct >= args.critical: c_msg += ' %s=%.1f%%,' % (node, pct) perfdata += ' %s=%.1f,' % (node, pct) elif pct >= args.warning: w_msg += ' %s=%.1f%%,' % (node, pct) perfdata += ' %s=%.1f,' % (node, pct) else: perfdata += ' %s=%.1f,' % (node, pct) # Prints the values and exits with the nagios exit code if len(c_msg) > 0: print ('CRITICAL:%s%s |%s' % (c_msg, w_msg, perfdata)).strip(',')[:1024] sys.exit(2) elif len(w_msg) > 0:<|fim▁hole|> sys.exit(1) elif len(perfdata) == 0: print 'CRITICAL: Unable to find any node data in the page.' sys.exit(2) else: print ('OK |%s' % (perfdata)).strip(',')[:1024] sys.exit(0)<|fim▁end|>
print ('WARNING:%s |%s' % (w_msg, perfdata)).strip(',')[:1024]
<|file_name|>PersonService.java<|end_file_name|><|fim▁begin|>package com.walmart.labs.pcs.normalize.MongoDB.SpringBoot.service; import com.walmart.labs.pcs.normalize.MongoDB.SpringBoot.entity.Person; import com.walmart.labs.pcs.normalize.MongoDB.SpringBoot.repository.PersonRepository; import com.walmart.labs.pcs.normalize.MongoDB.SpringBoot.repository.PersonRepositoryImp; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; /** * Created by pzhong1 on 1/23/15. */ public class PersonService {<|fim▁hole|> public List<Person> getAllPersons(){ return personRepository.findAll(); } public Person searchPerson(String id){ return personRepository.findOne(id); } public void insertPersonWithNameJohnAndRandomAge(Person person){ personRepository.save(person); } public void dropPersonCollection() { personRepository.deleteAll(); } }<|fim▁end|>
@Autowired private PersonRepository personRepository;
<|file_name|>seq_with_cursor.py<|end_file_name|><|fim▁begin|># # Copyright 2003,2004 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # # misc utilities from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import types class seq_with_cursor (object): __slots__ = [ 'items', 'index' ] def __init__ (self, items, initial_index = None, initial_value = None): assert len (items) > 0, "seq_with_cursor: len (items) == 0" self.items = items self.set_index (initial_index) if initial_value is not None: self.set_index_by_value(initial_value) def set_index (self, initial_index): if initial_index is None: self.index = len (self.items) / 2 elif initial_index >= 0 and initial_index < len (self.items): self.index = initial_index else: raise ValueError def set_index_by_value(self, v): """ Set index to the smallest value such that items[index] >= v. If there is no such item, set index to the maximum value. """ self.set_index(0) # side effect! cv = self.current() more = True while cv < v and more: cv, more = next(self) # side effect! def __next__ (self): new_index = self.index + 1 if new_index < len (self.items): self.index = new_index return self.items[new_index], True else: return self.items[self.index], False<|fim▁hole|> if new_index >= 0: self.index = new_index return self.items[new_index], True else: return self.items[self.index], False def current (self): return self.items[self.index] def get_seq (self): return self.items[:] # copy of items<|fim▁end|>
def prev (self): new_index = self.index - 1
<|file_name|>promise.js<|end_file_name|><|fim▁begin|>~function (global) { // status var PENDING = 0, FULFILLED = 1, REJECTED = 2; var Promise = function (fun) { var me = this, resolve = function (val) { me.resolve(val); }, reject = function (val) { me.reject(val); }; me._status = PENDING; me._onFulfilled = null; me._onRejected = null; (typeof fun === 'function') && fun(resolve, reject); }; var fn = Promise.prototype; fn.then = function (resolve, reject) { var pms = new Promise(); this._onFulfilled = function (val) { var ret = resolve ? resolve(val) : val; if (Promise.isPromise(ret)) { ret.then(function (val) { pms.resolve(val); }); } else{ pms.resolve(ret); } }; this._onRejected = function (val) { var ret = reject ? reject(val) : val; pms.reject(ret); }; return pms; } fn.catch = function (reject) { return this.then(null, reject); } fn.resolve = function (val) { if (this._status === PENDING) { this._status = FULFILLED; this._onFulfilled && this._onFulfilled(val); } } fn.reject = function (val) {<|fim▁hole|> } fn.all = function (arr) { var pms = new Promise(); var len = arr.length, i = -1, count = 0, results = []; while (++i < len) { ~function (i) { arr[i].then( function (val) { results[i] = val; if (++count === len) { pms.resolve(results); } }, function (val) { pms.reject(val); } ); }(i); } return pms; } fn.resolve = function (obj) { var ret; if (!Promise.isPromise(obj)) { ret = obj; obj = new Promise(); } setTimeout(function () { obj.resolve(ret); }); return obj; } fn.reject = function (obj) { var ret; if (!Promise.isPromise(obj)) { ret = obj; obj = new Promise(); } setTimeout(function () { obj.reject(ret); }); return obj; } fn.isPromise = function (obj) { return obj instanceof Promise; } global.Promise = Promise; try{ module.exports = Promise; } catch (e){} }(this);<|fim▁end|>
if (this._status === PENDING) { this._status = REJECTED; this._onRejected && this._onRejected(val); }
<|file_name|>lisp.rs<|end_file_name|><|fim▁begin|>#![macro_use] //! This module contains Rust definitions whose C equivalents live in //! lisp.h. use libc::{c_char, c_void, intptr_t, ptrdiff_t, uintptr_t}; #[cfg(test)] use std::cmp::max; use std::convert::From; use std::fmt::{Debug, Error, Formatter}; use std::mem; use std::ops::{Deref, DerefMut}; use std::slice; use remacs_sys::{font, EmacsDouble, EmacsInt, EmacsUint, EqualKind, Fcons, PseudovecType, CHECK_IMPURE, INTMASK, INTTYPEBITS, MOST_NEGATIVE_FIXNUM, MOST_POSITIVE_FIXNUM, USE_LSB_TAG, VALBITS, VALMASK}; use remacs_sys::{Lisp_Cons, Lisp_Float, Lisp_Misc_Any, Lisp_Misc_Type, Lisp_Object, Lisp_Subr, Lisp_Type}; use remacs_sys::{Qarrayp, Qbufferp, Qchar_table_p, Qcharacterp, Qconsp, Qfloatp, Qframe_live_p, Qframep, Qhash_table_p, Qinteger_or_marker_p, Qintegerp, Qlistp, Qmarkerp, Qnil, Qnumber_or_marker_p, Qnumberp, Qoverlayp, Qplistp, Qprocessp, Qstringp, Qsymbolp, Qt, Qthreadp, Qunbound, Qwholenump, Qwindow_live_p, Qwindow_valid_p, Qwindowp}; use remacs_sys::{empty_unibyte_string, internal_equal, lispsym, make_float, misc_get_ty}; use buffers::{LispBufferRef, LispOverlayRef}; use chartable::LispCharTableRef; use fonts::LispFontRef; use frames::LispFrameRef; use hashtable::LispHashTableRef; use lists::circular_list; use marker::LispMarkerRef; use multibyte::{Codepoint, LispStringRef, MAX_CHAR}; use obarray::LispObarrayRef; use process::LispProcessRef; use symbols::LispSymbolRef; use threads::ThreadStateRef; use vectors::{LispVectorRef, LispVectorlikeRef}; use windows::LispWindowRef; // TODO: tweak Makefile to rebuild C files if this changes. /// Emacs values are represented as tagged pointers. A few bits are /// used to represent the type, and the remaining bits are either used /// to store the value directly (e.g. integers) or the address of a /// more complex data type (e.g. a cons cell). /// /// TODO: example representations /// /// `EmacsInt` represents an integer big enough to hold our tagged /// pointer representation. /// /// In Emacs C, this is `EMACS_INT`. /// /// `EmacsUint` represents the unsigned equivalent of `EmacsInt`. /// In Emacs C, this is `EMACS_UINT`. /// /// Their definition are determined in a way consistent with Emacs C. /// Under casual systems, they're the type isize and usize respectively. #[repr(C)] #[derive(PartialEq, Eq, Clone, Copy)] pub struct LispObject(Lisp_Object); impl LispObject { #[inline] pub fn constant_unbound() -> LispObject { LispObject::from(Qunbound) } #[inline] pub fn constant_t() -> LispObject { LispObject::from(Qt) } #[inline] pub fn constant_nil() -> LispObject { LispObject::from(Qnil) } #[inline] pub fn from_bool(v: bool) -> LispObject { if v { LispObject::constant_t() } else { LispObject::constant_nil() } } #[inline] pub fn from_float(v: EmacsDouble) -> LispObject { LispObject::from(unsafe { make_float(v) }) } #[inline] pub fn to_raw(self) -> EmacsInt { self.0 } } impl From<EmacsInt> for LispObject { #[inline] fn from(i: EmacsInt) -> Self { LispObject(i) } } impl LispObject { pub fn get_type(self) -> Lisp_Type { let raw = self.to_raw() as EmacsUint; let res = (if USE_LSB_TAG { raw & (!VALMASK as EmacsUint) } else { raw >> VALBITS }) as u8; unsafe { mem::transmute(res) } } pub fn tag_ptr<T>(external: ExternalPtr<T>, ty: Lisp_Type) -> LispObject { let raw = external.as_ptr() as intptr_t; let res = if USE_LSB_TAG { let ptr = raw as intptr_t; let tag = ty as intptr_t; (ptr + tag) as EmacsInt } else { let ptr = raw as EmacsUint as uintptr_t; let tag = ty as EmacsUint as uintptr_t; ((tag << VALBITS) + ptr) as EmacsInt }; LispObject::from(res) } #[inline] pub fn get_untaggedptr(self) -> *mut c_void { (self.to_raw() & VALMASK) as intptr_t as *mut c_void } } // Symbol support (LispType == Lisp_Symbol == 0) impl LispObject { #[inline] pub fn is_symbol(self) -> bool { self.get_type() == Lisp_Type::Lisp_Symbol } #[inline] pub fn as_symbol(self) -> Option<LispSymbolRef> { if self.is_symbol() { Some(LispSymbolRef::new( unsafe { mem::transmute(self.symbol_ptr_value()) }, )) } else { None } } #[inline] pub fn as_symbol_or_error(self) -> LispSymbolRef { if self.is_symbol() { LispSymbolRef::new(unsafe { mem::transmute(self.symbol_ptr_value()) }) } else { wrong_type!(Qsymbolp, self) } } #[inline] pub fn symbol_or_string_as_string(self) -> LispStringRef { match self.as_symbol() { Some(sym) => sym.symbol_name() .as_string() .expect("Expected a symbol name?"), None => self.as_string_or_error(), } } #[inline] fn symbol_ptr_value(&self) -> EmacsInt { let ptr_value = if USE_LSB_TAG { self.to_raw() as EmacsInt } else { self.get_untaggedptr() as EmacsInt }; let lispsym_offset = unsafe { &lispsym as *const _ as EmacsInt }; ptr_value + lispsym_offset } } // Misc support (LispType == Lisp_Misc == 1) // Lisp_Misc is a union. Now we don't really care about its variants except the // super type layout. LispMisc is an unsized type for this, and LispMiscAny is // only the header and a padding, which is consistent with the c version. // directly creating and moving or copying this struct is simply wrong! // If needed, we can calculate all variants size and allocate properly. #[repr(C)] #[derive(Debug)] pub struct ExternalPtr<T>(*mut T); impl<T> Clone for ExternalPtr<T> { fn clone(&self) -> Self { ExternalPtr::new(self.0) } } impl<T> Copy for ExternalPtr<T> {} impl<T> ExternalPtr<T> { pub fn new(p: *mut T) -> ExternalPtr<T> { ExternalPtr(p) } pub fn as_ptr(&self) -> *const T { self.0 } pub fn as_mut(&mut self) -> *mut T { self.0 } } impl<T> Deref for ExternalPtr<T> { type Target = T; fn deref(&self) -> &Self::Target { unsafe { &*self.0 } } } impl<T> DerefMut for ExternalPtr<T> { fn deref_mut(&mut self) -> &mut Self::Target { unsafe { &mut *self.0 } } } impl<T> PartialEq for ExternalPtr<T> { fn eq(&self, other: &ExternalPtr<T>) -> bool { self.as_ptr() == other.as_ptr() } fn ne(&self, other: &ExternalPtr<T>) -> bool { self.as_ptr() != other.as_ptr() } } pub type LispSubrRef = ExternalPtr<Lisp_Subr>; unsafe impl Sync for LispSubrRef {} pub type LispMiscRef = ExternalPtr<Lisp_Misc_Any>; impl LispMiscRef { #[inline] pub fn get_type(self) -> Lisp_Misc_Type { unsafe { mem::transmute(misc_get_ty(self.as_ptr()) as i32) } } } #[test] fn test_lisp_misc_any_size() { // Should be 32 bits, which is 4 bytes. assert!(mem::size_of::<Lisp_Misc_Any>() == 4); } impl LispObject { #[inline] pub fn is_misc(self) -> bool { self.get_type() == Lisp_Type::Lisp_Misc } #[inline] pub fn as_misc(self) -> Option<LispMiscRef> { if self.is_misc() { unsafe { Some(self.to_misc_unchecked()) } } else { None } } unsafe fn to_misc_unchecked(self) -> LispMiscRef { LispMiscRef::new(mem::transmute(self.get_untaggedptr())) } } // Fixnum(Integer) support (LispType == Lisp_Int0 | Lisp_Int1 == 2 | 6(LSB) ) /// Fixnums are inline integers that fit directly into Lisp's tagged word. /// There's two `LispType` variants to provide an extra bit. /// Natnums(natural number) are the non-negative fixnums. /// There were special branches in the original code for better performance. /// However they are unified into the fixnum logic under LSB mode. /// TODO: Recheck these logic in original C code. impl LispObject { #[inline] pub fn from_fixnum(n: EmacsInt) -> LispObject { debug_assert!(MOST_NEGATIVE_FIXNUM <= n && n <= MOST_POSITIVE_FIXNUM); Self::from_fixnum_truncated(n) } #[inline] pub fn from_fixnum_truncated(n: EmacsInt) -> LispObject { let o = if USE_LSB_TAG { (n << INTTYPEBITS) as EmacsUint + Lisp_Type::Lisp_Int0 as EmacsUint } else { (n & INTMASK) as EmacsUint + ((Lisp_Type::Lisp_Int0 as EmacsUint) << VALBITS) }; LispObject::from(o as EmacsInt) } /// Convert a positive integer into its LispObject representation. /// /// This is also the function to use when translating `XSETFASTINT` /// from Emacs C. // TODO: the C claims that make_natnum is faster, but it does the same // thing as make_number when USE_LSB_TAG is 1, which it is for us. We // should remove this in favour of make_number. // // TODO: it would be clearer if this function took a u64 or libc::c_int. #[inline] pub fn from_natnum(n: EmacsInt) -> LispObject { debug_assert!(0 <= n && n <= MOST_POSITIVE_FIXNUM); LispObject::from_fixnum_truncated(n) } #[inline] pub fn int_or_float_from_fixnum(n: EmacsInt) -> LispObject { if n < MOST_NEGATIVE_FIXNUM || n > MOST_POSITIVE_FIXNUM { Self::from_float(n as f64) } else { Self::from_fixnum(n) } } #[inline] pub fn fixnum_overflow(n: EmacsInt) -> bool { n < MOST_NEGATIVE_FIXNUM || n > MOST_POSITIVE_FIXNUM } #[inline] unsafe fn to_fixnum_unchecked(self) -> EmacsInt { let raw = self.to_raw(); if !USE_LSB_TAG { raw & INTMASK } else { raw >> INTTYPEBITS } } #[inline] pub fn is_fixnum(self) -> bool { let ty = self.get_type(); (ty as u8 & ((Lisp_Type::Lisp_Int0 as u8) | !(Lisp_Type::Lisp_Int1 as u8))) == Lisp_Type::Lisp_Int0 as u8 } #[inline] pub fn as_fixnum(self) -> Option<EmacsInt> { if self.is_fixnum() { Some(unsafe { self.to_fixnum_unchecked() }) } else { None } } #[inline] pub fn as_fixnum_or_error(self) -> EmacsInt { if self.is_fixnum() { unsafe { self.to_fixnum_unchecked() } } else { wrong_type!(Qintegerp, self) } } #[inline] pub fn as_fixnum_coerce_marker_or_error(self) -> EmacsInt { if let Some(n) = self.as_fixnum() { n } else if let Some(m) = self.as_marker() { m.charpos_or_error() as EmacsInt } else { wrong_type!(Qinteger_or_marker_p, self); } } /// TODO: Bignum support? (Current Emacs doesn't have it) #[inline] pub fn is_integer(self) -> bool { self.is_fixnum() } #[inline] pub fn is_natnum(self) -> bool { self.as_fixnum().map_or(false, |i| i >= 0) } #[inline] pub fn as_natnum_or_error(self) -> EmacsInt { if self.is_natnum() { unsafe { self.to_fixnum_unchecked() } } else { wrong_type!(Qwholenump, self) } } } // Vectorlike support (LispType == 5) impl LispObject { #[inline] pub fn is_vectorlike(self) -> bool { self.get_type() == Lisp_Type::Lisp_Vectorlike } #[inline] pub fn is_vector(self) -> bool { self.as_vectorlike().map_or(false, |v| v.is_vector()) } #[inline] pub fn as_vectorlike(self) -> Option<LispVectorlikeRef> { if self.is_vectorlike() { Some(LispVectorlikeRef::new( unsafe { mem::transmute(self.get_untaggedptr()) }, )) } else { None } } /* #[inline] pub fn as_vectorlike_or_error(self) -> LispVectorlikeRef { if self.is_vectorlike() { LispVectorlikeRef::new(unsafe { mem::transmute(self.get_untaggedptr()) }) } else { wrong_type!(Qvectorp, self) } } */ pub unsafe fn as_vectorlike_unchecked(self) -> LispVectorlikeRef { LispVectorlikeRef::new(mem::transmute(self.get_untaggedptr())) } pub unsafe fn as_vector_unchecked(self) -> LispVectorRef { self.as_vectorlike_unchecked().as_vector_unchecked() } pub fn as_vector_or_string_length(self) -> isize { if let Some(s) = self.as_string() { return s.len_chars(); } else if let Some(vl) = self.as_vectorlike() { if let Some(v) = vl.as_vector() { return v.len() as isize; } }; wrong_type!(Qarrayp, self); } } impl LispObject { pub fn is_thread(self) -> bool { self.as_vectorlike() .map_or(false, |v| v.is_pseudovector(PseudovecType::PVEC_THREAD)) } pub fn as_thread(self) -> Option<ThreadStateRef> { self.as_vectorlike().map_or(None, |v| v.as_thread()) } pub fn as_thread_or_error(self) -> ThreadStateRef { self.as_thread() .unwrap_or_else(|| wrong_type!(Qthreadp, self)) } pub fn is_mutex(self) -> bool { self.as_vectorlike() .map_or(false, |v| v.is_pseudovector(PseudovecType::PVEC_MUTEX)) } pub fn is_condition_variable(self) -> bool { self.as_vectorlike() .map_or(false, |v| v.is_pseudovector(PseudovecType::PVEC_CONDVAR)) } pub fn is_byte_code_function(self) -> bool { self.as_vectorlike() .map_or(false, |v| v.is_pseudovector(PseudovecType::PVEC_COMPILED)) } pub fn is_subr(self) -> bool { self.as_vectorlike() .map_or(false, |v| v.is_pseudovector(PseudovecType::PVEC_SUBR)) } pub fn is_buffer(self) -> bool { self.as_vectorlike() .map_or(false, |v| v.is_pseudovector(PseudovecType::PVEC_BUFFER)) } pub fn as_buffer(self) -> Option<LispBufferRef> { self.as_vectorlike().map_or(None, |v| v.as_buffer()) } pub fn as_buffer_or_error(self) -> LispBufferRef { self.as_buffer() .unwrap_or_else(|| wrong_type!(Qbufferp, self)) } pub fn is_char_table(self) -> bool { self.as_vectorlike() .map_or(false, |v| v.is_pseudovector(PseudovecType::PVEC_CHAR_TABLE)) } pub fn as_char_table(self) -> Option<LispCharTableRef> { self.as_vectorlike().and_then(|v| v.as_char_table()) } pub fn as_char_table_or_error(self) -> LispCharTableRef { if let Some(chartable) = self.as_char_table() { chartable } else { wrong_type!(Qchar_table_p, self) } } pub fn is_bool_vector(self) -> bool { self.as_vectorlike().map_or( false, |v| v.is_pseudovector(PseudovecType::PVEC_BOOL_VECTOR), ) } pub fn is_array(self) -> bool { self.is_vector() || self.is_string() || self.is_char_table() || self.is_bool_vector() } pub fn is_sequence(self) -> bool { self.is_cons() || self.is_nil() || self.is_array() } /* pub fn is_window_configuration(self) -> bool { self.as_vectorlike().map_or( false, |v| v.is_pseudovector(PseudovecType::PVEC_WINDOW_CONFIGURATION), ) } */ pub fn is_process(self) -> bool { self.as_vectorlike() .map_or(false, |v| v.is_pseudovector(PseudovecType::PVEC_PROCESS)) } pub fn as_process(self) -> Option<LispProcessRef> { self.as_vectorlike().map_or(None, |v| v.as_process()) } pub fn as_process_or_error(self) -> LispProcessRef { self.as_process() .unwrap_or_else(|| wrong_type!(Qprocessp, self)) } pub fn is_window(self) -> bool { self.as_vectorlike() .map_or(false, |v| v.is_pseudovector(PseudovecType::PVEC_WINDOW)) } pub fn as_window(self) -> Option<LispWindowRef> { self.as_vectorlike().map_or(None, |v| v.as_window()) } pub fn as_window_or_error(self) -> LispWindowRef { self.as_window() .unwrap_or_else(|| wrong_type!(Qwindowp, self)) } pub fn as_minibuffer_or_error(self) -> LispWindowRef { let w = self.as_window() .unwrap_or_else(|| wrong_type!(Qwindowp, self)); if !w.is_minibuffer() { error!("Window is not a minibuffer window"); } w } pub fn as_live_window(self) -> Option<LispWindowRef> { self.as_window() .and_then(|w| if w.is_live() { Some(w) } else { None }) } pub fn as_live_window_or_error(self) -> LispWindowRef { self.as_live_window() .unwrap_or_else(|| wrong_type!(Qwindow_live_p, self)) } pub fn as_valid_window(self) -> Option<LispWindowRef> { self.as_window() .and_then(|w| if w.is_valid() { Some(w) } else { None }) } pub fn as_valid_window_or_error(self) -> LispWindowRef { self.as_valid_window() .unwrap_or_else(|| wrong_type!(Qwindow_valid_p, self)) } /* pub fn is_frame(self) -> bool { self.as_vectorlike() .map_or(false, |v| v.is_pseudovector(PseudovecType::PVEC_FRAME)) } */ pub fn as_frame(self) -> Option<LispFrameRef> { self.as_vectorlike().map_or(None, |v| v.as_frame()) } pub fn as_frame_or_error(self) -> LispFrameRef { self.as_frame() .unwrap_or_else(|| wrong_type!(Qframep, self)) } pub fn as_live_frame(self) -> Option<LispFrameRef> { self.as_frame() .and_then(|f| if f.is_live() { Some(f) } else { None }) } pub fn as_live_frame_or_error(self) -> LispFrameRef { self.as_live_frame() .unwrap_or_else(|| wrong_type!(Qframe_live_p, self)) } pub fn is_hash_table(self) -> bool { self.as_vectorlike() .map_or(false, |v| v.is_pseudovector(PseudovecType::PVEC_HASH_TABLE)) } pub fn is_font(self) -> bool { self.as_vectorlike() .map_or(false, |v| v.is_pseudovector(PseudovecType::PVEC_FONT)) } pub fn as_font(self) -> Option<LispFontRef> { self.as_vectorlike().map_or(None, |v| { if v.is_pseudovector(PseudovecType::PVEC_FONT) { Some(LispFontRef::from_vectorlike(v)) } else { None } }) } pub fn is_font_entity(self) -> bool { self.is_font() && self.as_vectorlike().map_or(false, |vec| { vec.pseudovector_size() == font::FONT_ENTITY_MAX as EmacsInt }) } pub fn is_font_object(self) -> bool { self.is_font() && self.as_vectorlike().map_or(false, |vec| { vec.pseudovector_size() == font::FONT_OBJECT_MAX as EmacsInt }) } pub fn is_font_spec(self) -> bool { self.is_font() && self.as_vectorlike().map_or(false, |vec| { vec.pseudovector_size() == font::FONT_SPEC_MAX as EmacsInt }) } pub fn is_record(self) -> bool { self.as_vectorlike() .map_or(false, |v| v.is_pseudovector(PseudovecType::PVEC_RECORD)) } } impl LispObject { pub fn as_hash_table_or_error(&self) -> LispHashTableRef { if self.is_hash_table() { LispHashTableRef::new(unsafe { mem::transmute(self.get_untaggedptr()) }) } else { wrong_type!(Qhash_table_p, *self); } } /* pub fn as_hash_table(&self) -> Option<LispHashTableRef> { if self.is_hash_table() { Some(LispHashTableRef::new( unsafe { mem::transmute(self.get_untaggedptr()) }, )) } else { None } } */ pub fn from_hash_table(hashtable: LispHashTableRef) -> LispObject { let object = LispObject::tag_ptr(hashtable, Lisp_Type::Lisp_Vectorlike); debug_assert!( object.is_vectorlike() && object.get_untaggedptr() == hashtable.as_ptr() as *mut c_void ); debug_assert!(object.is_hash_table()); object } } // Cons support (LispType == 6 | 3) /// From `FOR_EACH_TAIL_INTERNAL` in `lisp.h` pub struct TailsIter { list: LispObject, tail: LispObject, tortoise: LispObject, errsym: Option<Lisp_Object>, max: isize, n: isize, q: u16, } impl TailsIter { fn new(list: LispObject, errsym: Option<Lisp_Object>) -> Self { Self { list, tail: list, tortoise: list, errsym, max: 2, n: 0, q: 2, } } pub fn rest(&self) -> LispObject { // This is kind of like Peekable but even when None is returned there // might still be a valid item in self.tail. self.tail } fn circular(&self) -> Option<LispCons> { if self.errsym.is_some() { circular_list(self.tail); } else { None } } } impl Iterator for TailsIter { type Item = LispCons; fn next(&mut self) -> Option<Self::Item> { match self.tail.as_cons() { None => { if self.errsym.is_some() && self.tail.is_not_nil() { wrong_type!(self.errsym.clone().unwrap(), self.list) } None } Some(tail_cons) => { self.tail = tail_cons.cdr(); self.q = self.q.wrapping_sub(1); if self.q != 0 { if self.tail == self.tortoise { return self.circular(); } } else { self.n = self.n.wrapping_sub(1); if self.n > 0 { if self.tail == self.tortoise { return self.circular(); } } else { self.max <<= 1; self.q = self.max as u16; self.n = self.max >> 16; self.tortoise = self.tail; } } Some(tail_cons) } } } } pub struct CarIter { tails: TailsIter, }<|fim▁hole|> pub fn new(list: LispObject, errsym: Option<Lisp_Object>) -> Self { Self { tails: TailsIter::new(list, errsym), } } pub fn rest(&self) -> LispObject { self.tails.tail } } impl Iterator for CarIter { type Item = LispObject; fn next(&mut self) -> Option<Self::Item> { self.tails.next().map(|c| c.car()) } } impl LispObject { #[inline] pub fn cons(car: LispObject, cdr: LispObject) -> Self { unsafe { LispObject::from(Fcons(car.to_raw(), cdr.to_raw())) } } #[inline] pub fn is_cons(self) -> bool { self.get_type() == Lisp_Type::Lisp_Cons } #[inline] pub fn as_cons(self) -> Option<LispCons> { if self.is_cons() { Some(LispCons(self)) } else { None } } #[inline] pub fn as_cons_or_error(self) -> LispCons { if self.is_cons() { LispCons(self) } else { wrong_type!(Qconsp, self) } } #[inline] pub fn is_list(self) -> bool { self.is_cons() || self.is_nil() } /// Iterate over all tails of self. self should be a list, i.e. a chain /// of cons cells ending in nil. Otherwise a wrong-type-argument error /// will be signaled. pub fn iter_tails(self) -> TailsIter { TailsIter::new(self, Some(Qlistp)) } /// Iterate over all tails of self. If self is not a cons-chain, /// iteration will stop at the first non-cons without signaling. pub fn iter_tails_safe(self) -> TailsIter { TailsIter::new(self, None) } /// Iterate over all tails of self. self should be a plist, i.e. a chain /// of cons cells ending in nil. Otherwise a wrong-type-argument error /// will be signaled. pub fn iter_tails_plist(self) -> TailsIter { TailsIter::new(self, Some(Qplistp)) } /// Iterate over the car cells of a list. pub fn iter_cars(self) -> CarIter { CarIter::new(self, Some(Qlistp)) } /// Iterate over all cars of self. If self is not a cons-chain, /// iteration will stop at the first non-cons without signaling. pub fn iter_cars_safe(self) -> CarIter { CarIter::new(self, None) } } /// A newtype for objects we know are conses. #[derive(Clone, Copy)] pub struct LispCons(LispObject); impl LispCons { pub fn as_obj(self) -> LispObject { self.0 } fn _extract(self) -> *mut Lisp_Cons { unsafe { mem::transmute(self.0.get_untaggedptr()) } } /// Return the car (first cell). pub fn car(self) -> LispObject { LispObject::from(unsafe { (*self._extract()).car }) } /// Return the cdr (second cell). pub fn cdr(self) -> LispObject { LispObject::from(unsafe { (*self._extract()).cdr }) } /// Set the car of the cons cell. pub fn set_car(self, n: LispObject) { unsafe { (*self._extract()).car = n.to_raw(); } } /// Set the car of the cons cell. pub fn set_cdr(self, n: LispObject) { unsafe { (*self._extract()).cdr = n.to_raw(); } } /// Check that "self" is an impure (i.e. not readonly) cons cell. pub fn check_impure(self) { unsafe { CHECK_IMPURE(self.0.to_raw(), self._extract() as *const c_void); } } } // Float support (LispType == Lisp_Float == 7 ) #[test] fn test_lisp_float_size() { let double_size = mem::size_of::<EmacsDouble>(); let ptr_size = mem::size_of::<*const Lisp_Float>(); assert!(mem::size_of::<Lisp_Float>() == max(double_size, ptr_size)); } pub type LispFloatRef = ExternalPtr<Lisp_Float>; impl LispFloatRef { pub fn as_data(&self) -> &EmacsDouble { unsafe { &*(self.data.as_ptr() as *const EmacsDouble) } } } impl LispObject { #[inline] pub fn is_float(self) -> bool { self.get_type() == Lisp_Type::Lisp_Float } #[inline] unsafe fn to_float_unchecked(self) -> LispFloatRef { debug_assert!(self.is_float()); LispFloatRef::new(mem::transmute(self.get_untaggedptr())) } unsafe fn get_float_data_unchecked(self) -> EmacsDouble { *self.to_float_unchecked().as_data() } pub fn as_float(self) -> Option<EmacsDouble> { if self.is_float() { Some(unsafe { self.get_float_data_unchecked() }) } else { None } } pub fn as_float_or_error(self) -> EmacsDouble { if self.is_float() { unsafe { self.get_float_data_unchecked() } } else { wrong_type!(Qfloatp, self) } } /* /// If the LispObject is a number (of any kind), get a floating point value for it pub fn any_to_float(self) -> Option<EmacsDouble> { self.as_float() .or_else(|| self.as_fixnum().map(|i| i as EmacsDouble)) } */ pub fn any_to_float_or_error(self) -> EmacsDouble { self.as_float().unwrap_or_else(|| { self.as_fixnum() .unwrap_or_else(|| wrong_type!(Qnumberp, self)) as EmacsDouble }) } } // String support (LispType == 4) impl LispObject { #[inline] pub fn is_string(self) -> bool { self.get_type() == Lisp_Type::Lisp_String } #[inline] pub fn as_string(self) -> Option<LispStringRef> { if self.is_string() { Some(unsafe { self.as_string_unchecked() }) } else { None } } #[inline] pub fn as_string_or_error(self) -> LispStringRef { self.as_string() .unwrap_or_else(|| wrong_type!(Qstringp, self)) } #[inline] pub unsafe fn as_string_unchecked(self) -> LispStringRef { LispStringRef::new(mem::transmute(self.get_untaggedptr())) } #[inline] pub fn empty_unibyte_string() -> LispObject { LispObject::from(unsafe { empty_unibyte_string }) } /// Replaces STRING_SET_UNIBYTE in C. If your string has size 0, /// it will replace your string variable with 'empty_unibyte_string'. #[inline] pub fn set_string_unibyte(lstring: &mut LispObject) { let mut string = lstring.as_string_or_error(); if string.size == 0 { *lstring = Self::empty_unibyte_string(); } else { string.size_byte = -1; } } } // Other functions pub trait IsLispNatnum { fn check_natnum(&self); } impl IsLispNatnum for EmacsInt { fn check_natnum(&self) { if *self < 0 { wrong_type!(Qwholenump, LispObject::from_fixnum(*self)); } } } pub enum LispNumber { Fixnum(EmacsInt), Float(f64), } impl LispObject { #[inline] pub fn is_number(self) -> bool { self.is_fixnum() || self.is_float() } /* #[inline] pub fn as_number_or_error(self) -> LispNumber { if let Some(n) = self.as_fixnum() { LispNumber::Fixnum(n) } else if let Some(f) = self.as_float() { LispNumber::Float(f) } else { wrong_type!(Qnumberp, self) } } */ #[inline] pub fn as_number_coerce_marker_or_error(self) -> LispNumber { if let Some(n) = self.as_fixnum() { LispNumber::Fixnum(n) } else if let Some(f) = self.as_float() { LispNumber::Float(f) } else if let Some(m) = self.as_marker() { LispNumber::Fixnum(m.charpos_or_error() as EmacsInt) } else { wrong_type!(Qnumber_or_marker_p, self) } } #[inline] pub fn is_nil(self) -> bool { self.to_raw() == Qnil } #[inline] pub fn is_not_nil(self) -> bool { self.to_raw() != Qnil } #[inline] pub fn is_t(self) -> bool { self.to_raw() == Qt } #[inline] pub fn is_marker(self) -> bool { self.as_misc() .map_or(false, |m| m.get_type() == Lisp_Misc_Type::Marker) } #[inline] pub fn as_marker(self) -> Option<LispMarkerRef> { self.as_misc().and_then(|m| { if m.get_type() == Lisp_Misc_Type::Marker { unsafe { Some(mem::transmute(m)) } } else { None } }) } pub fn as_marker_or_error(self) -> LispMarkerRef { self.as_marker() .unwrap_or_else(|| wrong_type!(Qmarkerp, self)) } /// Nonzero iff X is a character. pub fn is_character(self) -> bool { self.as_fixnum() .map_or(false, |i| 0 <= i && i <= MAX_CHAR as EmacsInt) } /// Check if Lisp object is a character or not and return the codepoint /// Similar to CHECK_CHARACTER #[inline] pub fn as_character_or_error(self) -> Codepoint { if !self.is_character() { wrong_type!(Qcharacterp, self) } self.as_fixnum().unwrap() as Codepoint } #[inline] pub fn is_overlay(self) -> bool { self.as_misc() .map_or(false, |m| m.get_type() == Lisp_Misc_Type::Overlay) } pub fn as_overlay(self) -> Option<LispOverlayRef> { self.as_misc().and_then(|m| { if m.get_type() == Lisp_Misc_Type::Overlay { unsafe { Some(mem::transmute(m)) } } else { None } }) } pub fn as_overlay_or_error(self) -> LispOverlayRef { self.as_overlay() .unwrap_or_else(|| wrong_type!(Qoverlayp, self)) } // The three Emacs Lisp comparison functions. #[inline] pub fn eq(self, other: LispObject) -> bool { self == other } #[allow(dead_code)] #[inline] pub fn ne(self, other: LispObject) -> bool { self != other } #[inline] pub fn eql(self, other: LispObject) -> bool { if self.is_float() { self.equal_no_quit(other) } else { self.eq(other) } } #[inline] pub fn equal(self, other: LispObject) -> bool { unsafe { internal_equal(self.to_raw(), other.to_raw(), EqualKind::Plain, 0, Qnil) } } #[inline] pub fn equal_no_quit(self, other: LispObject) -> bool { unsafe { internal_equal(self.to_raw(), other.to_raw(), EqualKind::NoQuit, 0, Qnil) } } } /// Used to denote functions that have no limit on the maximum number /// of arguments. pub const MANY: i16 = -2; /// Internal function to get a displayable string out of a Lisp string. fn display_string(obj: LispObject) -> String { let s = obj.as_string().unwrap(); let slice = unsafe { slice::from_raw_parts(s.const_data_ptr(), s.len_bytes() as usize) }; String::from_utf8_lossy(slice).into_owned() } impl Debug for LispObject { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { let ty = self.get_type(); let self_ptr = &self as *const _ as usize; if ty as u8 >= 8 { write!( f, "#<INVALID-OBJECT @ {:#X}: VAL({:#X})>", self_ptr, self.to_raw() )?; return Ok(()); } if self.is_nil() { return write!(f, "nil"); } match ty { Lisp_Type::Lisp_Symbol => { let name = self.as_symbol_or_error().symbol_name(); write!(f, "'{}", display_string(name))?; } Lisp_Type::Lisp_Cons => { let mut cdr = *self; write!(f, "'(")?; while let Some(cons) = cdr.as_cons() { write!(f, "{:?} ", cons.car())?; cdr = cons.cdr(); } if cdr.is_nil() { write!(f, ")")?; } else { write!(f, ". {:?}", cdr)?; } } Lisp_Type::Lisp_Float => { write!(f, "{}", self.as_float().unwrap())?; } Lisp_Type::Lisp_Vectorlike => { let vl = self.as_vectorlike().unwrap(); if vl.is_vector() { write!(f, "[")?; for el in vl.as_vector().unwrap().as_slice() { write!(f, "{:?} ", el)?; } write!(f, "]")?; } else { write!( f, "#<VECTOR-LIKE @ {:#X}: VAL({:#X})>", self_ptr, self.to_raw() )?; } } Lisp_Type::Lisp_Int0 | Lisp_Type::Lisp_Int1 => { write!(f, "{}", self.as_fixnum().unwrap())?; } Lisp_Type::Lisp_Misc => { write!(f, "#<MISC @ {:#X}: VAL({:#X})>", self_ptr, self.to_raw())?; } Lisp_Type::Lisp_String => { write!(f, "{:?}", display_string(*self))?; } } Ok(()) } } /// Intern (e.g. create a symbol from) a string. pub fn intern<T: AsRef<str>>(string: T) -> LispObject { let s = string.as_ref(); LispObarrayRef::constant_obarray() .intern_cstring(s.as_ptr() as *const c_char, s.len() as ptrdiff_t) } extern "C" { pub fn defsubr(sname: *const Lisp_Subr); } macro_rules! export_lisp_fns { ($($f:ident),+) => { pub fn rust_init_syms() { unsafe { $( defsubr(concat_idents!(S, $f).as_ptr()); )+ } } } } #[test] fn test_basic_float() { let val = 8.0; let result = mock_float!(val); assert!(result.is_float() && result.as_float() == Some(val)); }<|fim▁end|>
impl CarIter {
<|file_name|>test_wikidata.py<|end_file_name|><|fim▁begin|>def test_signal_wikidata_url(ranker): rank = lambda url: ranker.client.get_signal_value_from_url("wikidata_url", url)<|fim▁hole|> assert rank("http://www.douglasadams.com") > 0.5 assert rank("http://www.douglasadams.com/?a=b") > 0.5 assert rank("http://www.douglasadams.com/page2") == 0. # TODO, check domain? assert rank("http://www.paulherbert.com/") == 0.<|fim▁end|>
<|file_name|>AgendaChart.js<|end_file_name|><|fim▁begin|>import React, {PropTypes, Component} from 'react'; import moment from 'moment'; import StyleSheet from 'styles/agenda.styl'; export default class AgendaChart extends Component { static propTypes = { items: PropTypes.array, currentDate: PropTypes.number, roomName: PropTypes.string } render() { const start = moment().hour(8).minutes(0); const {currentDate, items, roomName} = this.props; let currTime; if (moment(currentDate).isSame(moment(), 'day')) {<|fim▁hole|> currTime = moment().diff(start, 'hours', true); } return ( <div className={StyleSheet.container}> <div className="room-header biggie"> <span className="room-title"> {roomName} </span> </div> <div className="content-container"> {(currTime > 0) && <div className="current-time" style={{ top: `${currTime * 10}%` }}/> } {items.map(item => { const morning = moment(currentDate).hour(8).minutes(0); const fromTop = moment(item.start.dateTime).diff(morning, 'hours', true); const fromBottom = moment(item.end.dateTime).diff(item.start.dateTime, 'hours', true); return ( <div key={`agenda-${item.id}`} className="agenda-item" style={{ top: `${(fromTop * 10)}%`, height: `${(fromBottom * 10)}%` }}> <p className="content"> {item.summary} <br/> {moment(item.start.dateTime).format('h:mm ')}- {moment(item.end.dateTime).format(' h:mm')} </p> </div> ); })} </div> </div> ); } }<|fim▁end|>
<|file_name|>ToastText.tsx<|end_file_name|><|fim▁begin|>import * as React from 'react'; import { Icon } from './Icon'; interface IProps { id?: string; title?: string | React.ReactNode; icon?: string; onClose: () => void; } const ToastText = ({ id, title, icon, onClose}: IProps) => { const ref = React.useRef(null); return ( <React.Fragment> {icon ? <div className='sd-toast__icon'> <Icon name={icon} /> </div> : null} {typeof title === 'string' ? (<span style={{width: '100%'}} ref={ref} id={id}> <div className='sd-toast__message'>{title}</div> </span>) : <span style={{width: '100%', display: 'inherit'}} ref={ref} id={id}> {title} </span>} {onClose && <Close onClose={onClose} />} </React.Fragment> ); }; const Close = ({ onClose }: { onClose: () => void }) => ( <button className="icn-btn sd-toast__actions" type="button" aria-label="Close" onClick={onClose} ><|fim▁hole|> <Icon name='close-small' /> </button> ); export default ToastText;<|fim▁end|>
<|file_name|>preprocessors.py<|end_file_name|><|fim▁begin|>""" Prototype demo: python holoviews/ipython/convert.py Conversion_Example.ipynb | python """ import ast from nbconvert.preprocessors import Preprocessor def comment_out_magics(source): """ Utility used to make sure AST parser does not choke on unrecognized magics. """ filtered = [] for line in source.splitlines(): if line.strip().startswith('%'): filtered.append('# ' + line) else: filtered.append(line) return '\n'.join(filtered) def wrap_cell_expression(source, template='{expr}'):<|fim▁hole|> """ If a cell ends in an expression that could be displaying a HoloViews object (as determined using the AST), wrap it with a given prefix and suffix string. If the cell doesn't end in an expression, return the source unchanged. """ cell_output_types = (ast.IfExp, ast.BoolOp, ast.BinOp, ast.Call, ast.Name, ast.Attribute) try: node = ast.parse(comment_out_magics(source)) except SyntaxError: return source filtered = source.splitlines() if node.body != []: last_expr = node.body[-1] if not isinstance(last_expr, ast.Expr): pass # Not an expression elif isinstance(last_expr.value, cell_output_types): # CAREFUL WITH UTF8! expr_end_slice = filtered[last_expr.lineno-1][:last_expr.col_offset] expr_start_slice = filtered[last_expr.lineno-1][last_expr.col_offset:] start = '\n'.join(filtered[:last_expr.lineno-1] + ([expr_end_slice] if expr_end_slice else [])) ending = '\n'.join(([expr_start_slice] if expr_start_slice else []) + filtered[last_expr.lineno:]) # BUG!! Adds newline for 'foo'; <expr> return start + '\n' + template.format(expr=ending) return source def filter_magic(source, magic, strip=True): """ Given the source of a cell, filter out the given magic and collect the lines using the magic into a list. If strip is True, the IPython syntax part of the magic (e.g %magic or %%magic) is stripped from the returned lines. """ filtered, magic_lines=[],[] for line in source.splitlines(): if line.strip().startswith(magic): magic_lines.append(line) else: filtered.append(line) if strip: magic_lines = [el.replace(magic,'') for el in magic_lines] return '\n'.join(filtered), magic_lines def strip_magics(source): """ Given the source of a cell, filter out all cell and line magics. """ filtered=[] for line in source.splitlines(): if not line.startswith('%') or line.startswith('%%'): filtered.append(line) return '\n'.join(filtered) def replace_line_magic(source, magic, template='{line}'): """ Given a cell's source, replace line magics using a formatting template, where {line} is the string that follows the magic. """ filtered = [] for line in source.splitlines(): if line.strip().startswith(magic): substitution = template.format(line=line.replace(magic, '')) filtered.append(substitution) else: filtered.append(line) return '\n'.join(filtered) class OptsMagicProcessor(Preprocessor): """ Preprocessor to convert notebooks to Python source to convert use of opts magic to use the util.opts utility instead. """ def preprocess_cell(self, cell, resources, index): if cell['cell_type'] == 'code': source = replace_line_magic(cell['source'], '%opts', template='hv.util.opts({line!r})') source, opts_lines = filter_magic(source, '%%opts') if opts_lines: # Escape braces e.g normalization options as they pass through format template = 'hv.util.opts({options!r}, {{expr}})'.format( options=' '.join(opts_lines).replace('{','{{').replace('}','}}')) source = wrap_cell_expression(source, template) cell['source'] = source return cell, resources def __call__(self, nb, resources): return self.preprocess(nb,resources) class OutputMagicProcessor(Preprocessor): """ Preprocessor to convert notebooks to Python source to convert use of output magic to use the util.output utility instead. """ def preprocess_cell(self, cell, resources, index): if cell['cell_type'] == 'code': source = replace_line_magic(cell['source'], '%output', template='hv.util.output({line!r})') source, output_lines = filter_magic(source, '%%output') if output_lines: template = 'hv.util.output({options!r}, {{expr}})'.format( options=output_lines[-1]) source = wrap_cell_expression(source, template) cell['source'] = source return cell, resources def __call__(self, nb, resources): return self.preprocess(nb,resources) class StripMagicsProcessor(Preprocessor): """ Preprocessor to convert notebooks to Python source to strips out all magics. To be applied after the preprocessors that can handle holoviews magics appropriately. """ def preprocess_cell(self, cell, resources, index): if cell['cell_type'] == 'code': cell['source'] = strip_magics(cell['source']) return cell, resources def __call__(self, nb, resources): return self.preprocess(nb,resources) class Substitute(Preprocessor): """ An nbconvert preprocessor that substitutes one set of HTML data output for another, adding annotation to the output as required. The constructor accepts the notebook format version and a substitutions dictionary: {source_html:(target_html, annotation)} Where the annotation may be None (i.e. no annotation). """ annotation = '<center><b>%s</b></center>' def __init__(self, version, substitutions, **kw): self.nbversion = version self.substitutions = substitutions super(Preprocessor, self).__init__(**kw) def __call__(self, nb, resources): # Temporary hack around 'enabled' flag return self.preprocess(nb,resources) def replace(self, src): "Given some source html substitute and annotated as applicable" for html in self.substitutions.keys(): if src == html: annotation = self.annotation % self.substitutions[src][1] return annotation + self.substitutions[src][0] return src def preprocess_cell(self, cell, resources, index): v4 = (self.nbversion[0] == 4) if cell['cell_type'] == 'code': for outputs in cell['outputs']: output_key = ('execute_result' if v4 else 'pyout') if outputs['output_type'] == output_key: # V1-3 if not v4 and 'html' in outputs: outputs['html'] = self.replace(outputs['html']) # V4 for data in outputs.get('data',[]): if v4 and data == 'text/html': substitution = self.replace(outputs['data']['text/html']) outputs['data']['text/html'] = substitution return cell, resources<|fim▁end|>
<|file_name|>canonical_alias.rs<|end_file_name|><|fim▁begin|>//! Types for the [`m.room.canonical_alias`] event.<|fim▁hole|>use ruma_macros::EventContent; use serde::{Deserialize, Serialize}; use crate::RoomAliasId; /// The content of an `m.room.canonical_alias` event. /// /// Informs the room as to which alias is the canonical one. #[derive(Clone, Debug, Default, Deserialize, Serialize, EventContent)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] #[ruma_event(type = "m.room.canonical_alias", kind = State)] pub struct RoomCanonicalAliasEventContent { /// The canonical alias. /// /// Rooms with `alias: None` should be treated the same as a room /// with no canonical alias. #[serde( default, deserialize_with = "ruma_serde::empty_string_as_none", skip_serializing_if = "Option::is_none" )] pub alias: Option<Box<RoomAliasId>>, /// List of alternative aliases to the room. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub alt_aliases: Vec<Box<RoomAliasId>>, } impl RoomCanonicalAliasEventContent { /// Creates an empty `RoomCanonicalAliasEventContent`. pub fn new() -> Self { Self { alias: None, alt_aliases: Vec::new() } } } #[cfg(test)] mod tests { use crate::{event_id, room_alias_id, room_id, user_id, MilliSecondsSinceUnixEpoch}; use js_int::uint; use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use super::RoomCanonicalAliasEventContent; use crate::events::{StateEvent, Unsigned}; #[test] fn serialization_with_optional_fields_as_none() { let canonical_alias_event = StateEvent { content: RoomCanonicalAliasEventContent { alias: Some(room_alias_id!("#somewhere:localhost").to_owned()), alt_aliases: Vec::new(), }, event_id: event_id!("$h29iv0s8:example.com").to_owned(), origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)), prev_content: None, room_id: room_id!("!dummy:example.com").to_owned(), sender: user_id!("@carl:example.com").to_owned(), state_key: "".into(), unsigned: Unsigned::default(), }; let actual = to_json_value(&canonical_alias_event).unwrap(); let expected = json!({ "content": { "alias": "#somewhere:localhost" }, "event_id": "$h29iv0s8:example.com", "origin_server_ts": 1, "room_id": "!dummy:example.com", "sender": "@carl:example.com", "state_key": "", "type": "m.room.canonical_alias" }); assert_eq!(actual, expected); } #[test] fn absent_field_as_none() { let json_data = json!({ "content": {}, "event_id": "$h29iv0s8:example.com", "origin_server_ts": 1, "room_id": "!dummy:example.com", "sender": "@carl:example.com", "state_key": "", "type": "m.room.canonical_alias" }); assert_eq!( from_json_value::<StateEvent<RoomCanonicalAliasEventContent>>(json_data) .unwrap() .content .alias, None ); } #[test] fn null_field_as_none() { let json_data = json!({ "content": { "alias": null }, "event_id": "$h29iv0s8:example.com", "origin_server_ts": 1, "room_id": "!dummy:example.com", "sender": "@carl:example.com", "state_key": "", "type": "m.room.canonical_alias" }); assert_eq!( from_json_value::<StateEvent<RoomCanonicalAliasEventContent>>(json_data) .unwrap() .content .alias, None ); } #[test] fn empty_field_as_none() { let json_data = json!({ "content": { "alias": "" }, "event_id": "$h29iv0s8:example.com", "origin_server_ts": 1, "room_id": "!dummy:example.com", "sender": "@carl:example.com", "state_key": "", "type": "m.room.canonical_alias" }); assert_eq!( from_json_value::<StateEvent<RoomCanonicalAliasEventContent>>(json_data) .unwrap() .content .alias, None ); } #[test] fn nonempty_field_as_some() { let alias = Some(room_alias_id!("#somewhere:localhost").to_owned()); let json_data = json!({ "content": { "alias": "#somewhere:localhost" }, "event_id": "$h29iv0s8:example.com", "origin_server_ts": 1, "room_id": "!dummy:example.com", "sender": "@carl:example.com", "state_key": "", "type": "m.room.canonical_alias" }); assert_eq!( from_json_value::<StateEvent<RoomCanonicalAliasEventContent>>(json_data) .unwrap() .content .alias, alias ); } }<|fim▁end|>
//! //! [`m.room.canonical_alias`]: https://spec.matrix.org/v1.2/client-server-api/#mroomcanonical_alias
<|file_name|>conf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # pywim documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another # directory, add these directories to sys.path here. If the directory is # relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # Get the project root dir, which is the parent dir of this cwd = os.getcwd() project_root = os.path.dirname(cwd) # Insert the project root dir as the first element in the PYTHONPATH. # This lets us ensure that the source package is imported, and that its # version is used. sys.path.insert(0, project_root)<|fim▁hole|> # -- General configuration --------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'PyWIM' copyright = u"2016, Ivan Ogasawara" # The version info for the project you're documenting, acts as replacement # for |version| and |release|, also used in various other places throughout # the built documents. # # The short X.Y version. version = pywim.__version__ # The full version, including alpha/beta/rc tags. release = pywim.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to # some non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built # documents. #keep_warnings = False # -- Options for HTML output ------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a # theme further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as # html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the # top of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon # of the docs. This file should be a Windows icon file (.ico) being # 16x16 or 32x32 pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) # here, relative to this directory. They are copied after the builtin # static files, so a file named "default.css" will overwrite the builtin # "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names # to template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. # Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. # Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages # will contain a <link> tag referring to it. The value of this option # must be the base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'pywimdoc' # -- Options for LaTeX output ------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto/manual]). latex_documents = [ ('index', 'pywim.tex', u'PyWIM Documentation', u'Ivan Ogasawara', 'manual'), ] # The name of an image file (relative to this directory) to place at # the top of the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings # are parts, not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output ------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pywim', u'PyWIM Documentation', [u'Ivan Ogasawara'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ---------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'pywim', u'PyWIM Documentation', u'Ivan Ogasawara', 'pywim', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False<|fim▁end|>
import pywim
<|file_name|>mth-to-last-element.py<|end_file_name|><|fim▁begin|>import sys def main(): with open(sys.argv[1]) as input_file: for line in input_file.readlines(): input_list = list(reversed(line.strip().split(' '))) index = int(input_list[0]) del input_list[0] print(input_list[index - 1]) <|fim▁hole|>if __name__ == '__main__': main()<|fim▁end|>
<|file_name|>token.go<|end_file_name|><|fim▁begin|>package token import ( "encoding/base32" "net/http" "time" "github.com/dgrijalva/jwt-go" "github.com/dgrijalva/jwt-go/request" ) const ( // UserToken is the kind of token to represent a user token. UserToken = "user" // SessToken is the kind of token to represent a session token. SessToken = "sess" // SignerAlgo is the default algorithm used to sign JWT tokens. SignerAlgo = "HS256" ) // SecretFunc is a helper function to retrieve the used JWT secret. type SecretFunc func(*Token) ([]byte, error) // Result represents to token to the outer world for HTTP responses. type Result struct { Token string `json:"token,omitempty"` Expire string `json:"expire,omitempty"` } // Token is internally used to differ between the kinds of tokens. type Token struct { Kind string Text string }<|fim▁hole|>func (t *Token) SignUnlimited(secret string) (*Result, error) { return t.SignExpiring(secret, 0) } // SignExpiring signs a token that maybe expires. func (t *Token) SignExpiring(secret string, exp time.Duration) (*Result, error) { token := jwt.New(jwt.SigningMethodHS256) claims := token.Claims.(jwt.MapClaims) claims["type"] = t.Kind claims["text"] = t.Text signingKey, _ := base32.StdEncoding.DecodeString(secret) tokenString, err := token.SignedString(signingKey) if exp > 0 { expire := time.Now().Add(exp) claims["exp"] = expire.Unix() return &Result{ Token: tokenString, Expire: expire.Format(time.RFC3339), }, err } return &Result{ Token: tokenString, }, err } // New initializes a new simple token of a specified kind. func New(kind, text string) *Token { return &Token{ Kind: kind, Text: text, } } // Parse can parse the authorization information from a request. func Parse(r *http.Request, fn SecretFunc) (*Token, error) { token := &Token{} raw, err := request.OAuth2Extractor.ExtractToken(r) if err != nil { return nil, err } parsed, err := jwt.Parse(raw, keyFunc(token, fn)) if err != nil { return nil, err } else if !parsed.Valid { return nil, jwt.ValidationError{} } return token, nil } // Direct can parse the token directly without a request. func Direct(val string, fn SecretFunc) (*Token, error) { token := &Token{} parsed, err := jwt.Parse(val, keyFunc(token, fn)) if err != nil { return nil, err } else if !parsed.Valid { return nil, jwt.ValidationError{} } return token, nil } func keyFunc(token *Token, fn SecretFunc) jwt.Keyfunc { return func(t *jwt.Token) (interface{}, error) { if t.Method.Alg() != SignerAlgo { return nil, jwt.ErrSignatureInvalid } claims := t.Claims.(jwt.MapClaims) kindv, ok := claims["type"] if !ok { return nil, jwt.ValidationError{} } token.Kind, _ = kindv.(string) textv, ok := claims["text"] if !ok { return nil, jwt.ValidationError{} } token.Text, _ = textv.(string) return fn(token) } }<|fim▁end|>
// SignUnlimited signs a token the never expires.
<|file_name|>FrozenSerializationBench.cpp<|end_file_name|><|fim▁begin|>/* * Copyright (c) Meta Platforms, Inc. and 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. */ #include <folly/Benchmark.h> #include <thrift/lib/cpp2/frozen/FrozenUtil.h> #include <thrift/lib/cpp2/frozen/test/gen-cpp2/Example_layouts.h> #include <thrift/lib/cpp2/frozen/test/gen-cpp2/Example_types.h> #include <thrift/lib/cpp2/protocol/Serializer.h> using namespace apache::thrift; using namespace apache::thrift::frozen; using namespace apache::thrift::test; EveryLayout stressValue2 = [] { EveryLayout x; *x.aBool_ref() = true; *x.aInt_ref() = 2; *x.aList_ref() = {3, 5}; *x.aSet_ref() = {7, 11}; *x.aHashSet_ref() = {13, 17}; *x.aMap_ref() = {{19, 23}, {29, 31}}; *x.aHashMap_ref() = {{37, 41}, {43, 47}}; x.optInt_ref() = 53; *x.aFloat_ref() = 59.61; x.optMap_ref() = {{2, 4}, {3, 9}}; return x; }(); BENCHMARK(CompactSerialize, iters) {<|fim▁hole|> while (iters--) { std::string out; CompactSerializer::serialize(stressValue2, &out); s += out.size(); } folly::doNotOptimizeAway(s); } BENCHMARK_RELATIVE(FrozenFreeze, iters) { size_t s = 0; folly::BenchmarkSuspender setup; Layout<EveryLayout> layout; LayoutRoot::layout(stressValue2, layout); setup.dismiss(); while (iters--) { std::string out = freezeDataToString(stressValue2, layout); s += out.size(); } folly::doNotOptimizeAway(s); } BENCHMARK_RELATIVE(FrozenFreezePreallocate, iters) { size_t s = 0; folly::BenchmarkSuspender setup; Layout<EveryLayout> layout; LayoutRoot::layout(stressValue2, layout); setup.dismiss(); while (iters--) { std::array<byte, 1024> buffer; auto write = folly::MutableByteRange(buffer.begin(), buffer.end()); ByteRangeFreezer::freeze(layout, stressValue2, write); s += buffer.size() - write.size(); } folly::doNotOptimizeAway(s); } BENCHMARK_DRAW_LINE(); BENCHMARK(CompactDeserialize, iters) { size_t s = 0; folly::BenchmarkSuspender setup; std::string out; CompactSerializer::serialize(stressValue2, &out); setup.dismiss(); while (iters--) { EveryLayout copy; CompactSerializer::deserialize(out, copy); s += out.size(); } folly::doNotOptimizeAway(s); } BENCHMARK_RELATIVE(FrozenThaw, iters) { size_t s = 0; folly::BenchmarkSuspender setup; Layout<EveryLayout> layout; LayoutRoot::layout(stressValue2, layout); std::string out = freezeDataToString(stressValue2, layout); setup.dismiss(); while (iters--) { EveryLayout copy; layout.thaw(ViewPosition{reinterpret_cast<byte*>(&out[0]), 0}, copy); s += out.size(); } folly::doNotOptimizeAway(s); } #if 0 ============================================================================ relative time/iter iters/s ============================================================================ CompactSerialize 439.75ns 2.27M FrozenFreeze 21.53% 2.04us 489.59K FrozenFreezePreallocate 62.33% 705.48ns 1.42M ---------------------------------------------------------------------------- CompactDeserialize 787.59ns 1.27M FrozenThaw 98.97% 795.77ns 1.26M ============================================================================ #endif int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); gflags::ParseCommandLineFlags(&argc, &argv, true); folly::runBenchmarks(); return 0; }<|fim▁end|>
size_t s = 0;
<|file_name|>ip2_convolve3x3.rs<|end_file_name|><|fim▁begin|>/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License");<|fim▁hole|> * 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. */ #include "ip.rsh" int32_t gWidth; int32_t gHeight; rs_allocation gIn; float gCoeffs[9]; uchar4 RS_KERNEL root(uint32_t x, uint32_t y) { uint32_t x1 = min((int32_t)x+1, gWidth-1); uint32_t x2 = max((int32_t)x-1, 0); uint32_t y1 = min((int32_t)y+1, gHeight-1); uint32_t y2 = max((int32_t)y-1, 0); float4 p00 = convert_float4(rsGetElementAt_uchar4(gIn, x1, y1)); float4 p01 = convert_float4(rsGetElementAt_uchar4(gIn, x, y1)); float4 p02 = convert_float4(rsGetElementAt_uchar4(gIn, x2, y1)); float4 p10 = convert_float4(rsGetElementAt_uchar4(gIn, x1, y)); float4 p11 = convert_float4(rsGetElementAt_uchar4(gIn, x, y)); float4 p12 = convert_float4(rsGetElementAt_uchar4(gIn, x2, y)); float4 p20 = convert_float4(rsGetElementAt_uchar4(gIn, x1, y2)); float4 p21 = convert_float4(rsGetElementAt_uchar4(gIn, x, y2)); float4 p22 = convert_float4(rsGetElementAt_uchar4(gIn, x2, y2)); p00 *= gCoeffs[0]; p01 *= gCoeffs[1]; p02 *= gCoeffs[2]; p10 *= gCoeffs[3]; p11 *= gCoeffs[4]; p12 *= gCoeffs[5]; p20 *= gCoeffs[6]; p21 *= gCoeffs[7]; p22 *= gCoeffs[8]; p00 += p01; p02 += p10; p11 += p12; p20 += p21; p22 += p00; p02 += p11; p20 += p22; p20 += p02; p20 = clamp(p20, 0.f, 255.f); return convert_uchar4(p20); }<|fim▁end|>
<|file_name|>waterfall_sink_c_impl.cc<|end_file_name|><|fim▁begin|>/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio 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, or (at your option) * any later version. * * GNU Radio 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 GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "waterfall_sink_c_impl.h" #include <gr_io_signature.h> #include <string.h> #include <volk/volk.h> namespace gr { namespace qtgui { waterfall_sink_c::sptr waterfall_sink_c::make(int fftsize, int wintype, double fc, double bw, const std::string &name, QWidget *parent) { return gnuradio::get_initial_sptr (new waterfall_sink_c_impl(fftsize, wintype, fc, bw, name, parent)); } waterfall_sink_c_impl::waterfall_sink_c_impl(int fftsize, int wintype, double fc, double bw, const std::string &name, QWidget *parent) : gr_sync_block("waterfall_sink_c", gr_make_io_signature(1, -1, sizeof(gr_complex)), gr_make_io_signature(0, 0, 0)), d_fftsize(fftsize), d_fftavg(1.0), d_wintype((filter::firdes::win_type)(wintype)), d_center_freq(fc), d_bandwidth(bw), d_name(name), d_nconnections(1), d_parent(parent) { d_main_gui = NULL; // Perform fftshift operation; // this is usually desired when plotting d_shift = true; d_fft = new fft::fft_complex(d_fftsize, true); d_fbuf = fft::malloc_float(d_fftsize); memset(d_fbuf, 0, d_fftsize*sizeof(float)); d_index = 0; for(int i = 0; i < d_nconnections; i++) { d_residbufs.push_back(fft::malloc_complex(d_fftsize)); d_magbufs.push_back(fft::malloc_double(d_fftsize)); memset(d_residbufs[i], 0, d_fftsize*sizeof(float)); memset(d_magbufs[i], 0, d_fftsize*sizeof(double)); } buildwindow(); initialize(); } waterfall_sink_c_impl::~waterfall_sink_c_impl() { for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs[i]); fft::free(d_magbufs[i]); } delete d_fft; fft::free(d_fbuf); } void waterfall_sink_c_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned int ninputs = ninput_items_required.size(); for (unsigned int i = 0; i < ninputs; i++) { ninput_items_required[i] = std::min(d_fftsize, 8191); } } void waterfall_sink_c_impl::initialize() { if(qApp != NULL) { d_qApplication = qApp; } else { int argc=0; char **argv = NULL; d_qApplication = new QApplication(argc, argv); } d_main_gui = new WaterfallDisplayForm(d_nconnections, d_parent); d_main_gui->SetFFTSize(d_fftsize); d_main_gui->SetFFTWindowType(d_wintype); d_main_gui->SetFrequencyRange(d_center_freq, d_center_freq - d_bandwidth/2.0, d_center_freq + d_bandwidth/2.0); // initialize update time to 10 times a second set_update_time(0.1); d_last_time = 0; } void waterfall_sink_c_impl::exec_() { d_qApplication->exec(); } QWidget* waterfall_sink_c_impl::qwidget() { return d_main_gui; } PyObject* waterfall_sink_c_impl::pyqwidget() { PyObject *w = PyLong_FromVoidPtr((void*)d_main_gui); PyObject *retarg = Py_BuildValue("N", w);<|fim▁hole|> waterfall_sink_c_impl::set_fft_size(const int fftsize) { d_fftsize = fftsize; d_main_gui->SetFFTSize(fftsize); } int waterfall_sink_c_impl::fft_size() const { return d_fftsize; } void waterfall_sink_c_impl::set_fft_average(const float fftavg) { d_fftavg = fftavg; d_main_gui->SetFFTAverage(fftavg); } float waterfall_sink_c_impl::fft_average() const { return d_fftavg; } void waterfall_sink_c_impl::set_frequency_range(const double centerfreq, const double bandwidth) { d_center_freq = centerfreq; d_bandwidth = bandwidth; d_main_gui->SetFrequencyRange(d_center_freq, -d_bandwidth/2.0, d_bandwidth/2.0); } void waterfall_sink_c_impl::set_update_time(double t) { //convert update time to ticks gruel::high_res_timer_type tps = gruel::high_res_timer_tps(); d_update_time = t * tps; d_main_gui->setUpdateTime(t); } void waterfall_sink_c_impl::set_title(const std::string &title) { d_main_gui->setTitle(0, title.c_str()); } void waterfall_sink_c_impl::set_color(const std::string &color) { d_main_gui->setColor(0, color.c_str()); } void waterfall_sink_c_impl::set_line_width(int width) { d_main_gui->setLineWidth(0, width); } void waterfall_sink_c_impl::set_line_style(Qt::PenStyle style) { d_main_gui->setLineStyle(0, style); } void waterfall_sink_c_impl::set_line_marker(QwtSymbol::Style marker) { d_main_gui->setLineMarker(0, marker); } void waterfall_sink_c_impl::set_size(int width, int height) { d_main_gui->resize(QSize(width, height)); } void waterfall_sink_c_impl::fft(float *data_out, const gr_complex *data_in, int size) { if(d_window.size()) { volk_32fc_32f_multiply_32fc_a(d_fft->get_inbuf(), data_in, &d_window.front(), size); } else { memcpy(d_fft->get_inbuf(), data_in, sizeof(gr_complex)*size); } d_fft->execute(); // compute the fft volk_32fc_s32f_x2_power_spectral_density_32f_a(data_out, d_fft->get_outbuf(), size, 1.0, size); // Perform shift operation unsigned int len = (unsigned int)(floor(size/2.0)); float *tmp = (float*)malloc(sizeof(float)*len); memcpy(tmp, &data_out[0], sizeof(float)*len); memcpy(&data_out[0], &data_out[len], sizeof(float)*(size - len)); memcpy(&data_out[size - len], tmp, sizeof(float)*len); free(tmp); } void waterfall_sink_c_impl::windowreset() { filter::firdes::win_type newwintype; newwintype = d_main_gui->GetFFTWindowType(); if(d_wintype != newwintype) { d_wintype = newwintype; buildwindow(); } } void waterfall_sink_c_impl::buildwindow() { d_window.clear(); if(d_wintype != filter::firdes::WIN_NONE) { d_window = filter::firdes::window(d_wintype, d_fftsize, 6.76); } } void waterfall_sink_c_impl::fftresize() { int newfftsize = d_main_gui->GetFFTSize(); d_fftavg = d_main_gui->GetFFTAverage(); if(newfftsize != d_fftsize) { // Resize residbuf and replace data for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs[i]); fft::free(d_magbufs[i]); d_residbufs[i] = fft::malloc_complex(newfftsize); d_magbufs[i] = fft::malloc_double(newfftsize); memset(d_residbufs[i], 0, newfftsize*sizeof(gr_complex)); memset(d_magbufs[i], 0, newfftsize*sizeof(double)); } // Set new fft size and reset buffer index // (throws away any currently held data, but who cares?) d_fftsize = newfftsize; d_index = 0; // Reset window to reflect new size buildwindow(); // Reset FFTW plan for new size delete d_fft; d_fft = new fft::fft_complex(d_fftsize, true); fft::free(d_fbuf); d_fbuf = fft::malloc_float(d_fftsize); memset(d_fbuf, 0, d_fftsize*sizeof(float)); } } int waterfall_sink_c_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int j=0; const gr_complex *in = (const gr_complex*)input_items[0]; // Update the FFT size from the application fftresize(); windowreset(); for(int i=0; i < noutput_items; i+=d_fftsize) { unsigned int datasize = noutput_items - i; unsigned int resid = d_fftsize-d_index; // If we have enough input for one full FFT, do it if(datasize >= resid) { for(int n = 0; n < d_nconnections; n++) { // Fill up residbuf with d_fftsize number of items in = (const gr_complex*)input_items[n]; memcpy(d_residbufs[n]+d_index, &in[j], sizeof(gr_complex)*resid); fft(d_fbuf, d_residbufs[n], d_fftsize); for(int x = 0; x < d_fftsize; x++) { d_magbufs[n][x] = (double)((1.0-d_fftavg)*d_magbufs[n][x] + (d_fftavg)*d_fbuf[x]); } //volk_32f_convert_64f_a(d_magbufs[n], d_fbuf, d_fftsize); } if(gruel::high_res_timer_now() - d_last_time > d_update_time) { d_last_time = gruel::high_res_timer_now(); d_qApplication->postEvent(d_main_gui, new WaterfallUpdateEvent(d_magbufs, d_fftsize, d_last_time)); } d_index = 0; j += resid; } // Otherwise, copy what we received into the residbuf for next time else { for(int n = 0; n < d_nconnections; n++) { in = (const gr_complex*)input_items[n]; memcpy(d_residbufs[n]+d_index, &in[j], sizeof(gr_complex)*datasize); } d_index += datasize; j += datasize; } } return j; } } /* namespace qtgui */ } /* namespace gr */<|fim▁end|>
return retarg; } void