prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>Result.ts<|end_file_name|><|fim▁begin|>import {Serializable, Serialize, UnmarshallError} from "ts-serialize"; import {JsValue, Json} from "ts-json-definition";<|fim▁hole|>const dateUnmarshaller = (value: JsValue, json: Json, clazz: any, classPropertyName: string, jsonPropertyName: string, target: Function, mbType: Optional<Function>, jsonPath: string[], classPath: string[]) : Either<UnmarshallError[], Date> => { if(typeof value === "string") { let time = parseInt(value.replace("/Date(", "").replace("+0000)/", "")); if(!isNaN(time)) { return Right<UnmarshallError[], Date>(new Date(time)); } } return Left<UnmarshallError[], Date>([new UnmarshallError(value, mbType, jsonPropertyName, classPropertyName, target, jsonPath, classPath)]); }; class Result extends Serializable { @Serialize("Date", dateUnmarshaller) date : Date; @Serialize("Num1") num1 : number; @Serialize("Num2") num2 : number; @Serialize("Num3") num3 : number; @Serialize("Num4") num4 : number; @Serialize("Num5") num5 : number; @Serialize("Star1") star1 : number; @Serialize("Star2") star2 : number; constructor(num1 : number, num2 : number, num3 : number, num4 : number, num5 : number, star1 : number, star2 : number) { super(); this.date = new Date(); this.num1 = num1; this.num2 = num2; this.num3 = num3; this.num4 = num4; this.num5 = num5; this.star1 = star1; this.star2 = star2; } } export default Result; /* "Date": "/Date(1103846400000+0000)/", "Jackpot": 0, "NextJackpot": 0, "Num1": 3, "Num2": 4, "Num3": 27, "Num4": 29, "Num5": 37, "PrizeCombinations": [], "RaffleNumber": 46, "Star1": 5, "Star2": 6 */<|fim▁end|>
import {Either, Right, Left, Optional} from "scalts";
<|file_name|>model.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python ############################################################################## ## ## This file is part of Sardana ## ## http://www.sardana-controls.org/ ## ## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain ## ## Sardana 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. ## ## Sardana 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 Sardana. If not, see <http://www.gnu.org/licenses/>. ## ############################################################################## """ model.py: """ from lxml import etree from taurus.external.qt import Qt from sardana.taurus.core.tango.sardana import macro class MacroSequenceTreeModel(Qt.QAbstractItemModel): def __init__(self, parent=None): Qt.QAbstractItemModel.__init__(self, parent) self.columns = 4 self.setRoot(macro.SequenceNode()) self.headers = ["Macro", "Parameters", "Progress", "Pause"] def root(self): return self._root def setRoot(self, root): self._root = root self.reset() def clearSequence(self): self.setRoot(macro.SequenceNode()) def isEmpty(self): return len(self.root()) == 0 def flags(self, index): column = index.column() node = self.nodeFromIndex(index) flags = Qt.Qt.ItemIsEnabled if column == 0: flags |= Qt.Qt.ItemIsSelectable elif column == 1: if isinstance(node, macro.SingleParamNode) and \ not node.type() == "User": flags |= Qt.Qt.ItemIsEditable else: flags |= Qt.Qt.ItemIsSelectable elif column == 2: flags |= Qt.Qt.ItemIsSelectable elif index.column() == 3: flags |= (Qt.Qt.ItemIsSelectable | Qt.Qt.ItemIsEditable) if isinstance(node, macro.MacroNode): flags |= Qt.Qt.ItemIsDragEnabled if node.isAllowedHooks(): flags |= Qt.Qt.ItemIsDropEnabled return flags def _insertRow(self, parentIndex, node=None, row=-1): parentNode = self.nodeFromIndex(parentIndex) if row == -1: row = len(parentNode) if isinstance(parentNode, macro.RepeatParamNode): if node == None: node = parentNode.newRepeat() self.beginInsertRows(parentIndex, row, row) row = parentNode.insertChild(node, row) self.endInsertRows() return self.index(row, 0, parentIndex) def _removeRow(self, index): """This method is used remove macro (pased via index)""" node = self.nodeFromIndex(index) parentIndex = index.parent() parentNode = self.nodeFromIndex(parentIndex) row = parentNode.rowOfChild(node) self.beginRemoveRows(parentIndex, row, row) parentNode.removeChild(node) self.endRemoveRows() def _upRow(self, index): node = self.nodeFromIndex(index) parentIndex = index.parent() parentNode = self.nodeFromIndex(parentIndex) row = parentNode.rowOfChild(node) self._removeRow(index) newIndex = self._insertRow(parentIndex, node, row - 1) if isinstance(parentNode, macro.RepeatParamNode): parentNode.arrangeIndexes() return newIndex def _downRow(self, index): node = self.nodeFromIndex(index) parentIndex = index.parent() parentNode = self.nodeFromIndex(parentIndex) row = parentNode.rowOfChild(node) self._removeRow(index) newIndex = self._insertRow(parentIndex, node, row + 1) if isinstance(parentNode, macro.RepeatParamNode): parentNode.arrangeIndexes() return newIndex def _leftRow(self, index): """This method is used to move selected macro (pased via index) to it's grandparent's hook list. In tree representation it basically move macro to the left""" node = self.nodeFromIndex(index) parentIndex = index.parent() grandParentIndex = parentIndex.parent() self._removeRow(index) return self._insertRow(grandParentIndex, node) def _rightRow(self, index): """This method is used to move selected macro (pased via index) to it's grandparent's hook list. In tree representation it basically move macro to the left""" node = self.nodeFromIndex(index) parentIndex = index.parent() row = index.row() self._removeRow(index) newParentIndex = self.index(row, 0, parentIndex) return self._insertRow(newParentIndex, node) def rowCount(self, parent): branchNode = self.nodeFromIndex(parent)<|fim▁hole|> def columnCount(self, parent): return self.columns def data(self, index, role): if role == Qt.Qt.DisplayRole: node = self.nodeFromIndex(index) if index.column() == 0: return Qt.QVariant(node.name()) elif index.column() == 1: return Qt.QVariant(str(node.value())) elif index.column() == 2: if isinstance(node, macro.MacroNode): return Qt.QVariant(node.progress()) elif role == Qt.Qt.DecorationRole: node = self.nodeFromIndex(index) if index.column() == 3: if isinstance(node, macro.MacroNode): if node.isPause(): return Qt.QVariant(Qt.QIcon(":/actions/media-playback-pause.svg")) return Qt.QVariant() def setData (self, index, value, role=Qt.Qt.EditRole): node = self.nodeFromIndex(index) if index.column() == 1: if isinstance(node, macro.SingleParamNode): node.setValue(Qt.from_qvariant(value, str)) self.emit(Qt.SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index) while True: index = index.parent() node = self.nodeFromIndex(index) if isinstance(node, macro.MacroNode): self.emit(Qt.SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index.sibling(index.row(), self.columnCount(index) - 1)) break elif index.column() == 2: progress = Qt.from_qvariant(value, float) node.setProgress(progress) self.emit(Qt.SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index) elif index.column() == 3: node.setPause(Qt.from_qvariant(value, bool)) self.emit(Qt.SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index) return True def headerData(self, section, orientation, role): if orientation == Qt.Qt.Horizontal and role == Qt.Qt.DisplayRole: return Qt.QVariant(self.headers[section]) return Qt.QVariant() def index(self, row, column, parent): assert self.root() is not None branchNode = self.nodeFromIndex(parent) assert branchNode is not None return self.createIndex(row, column, branchNode.child(row)) def parent(self, child): node = self.nodeFromIndex(child) if node is None: return Qt.QModelIndex() parent = node.parent() if parent is None: return Qt.QModelIndex() grandparent = parent.parent() if grandparent is None: return Qt.QModelIndex() row = grandparent.rowOfChild(parent) assert row != -1 return self.createIndex(row, 0, parent) def nodeFromIndex(self, index): if index.isValid(): return index.internalPointer() else: return self.root() def toXmlString(self, pretty=False, withId=True): xmlSequence = self.root().toXml(withId=withId) xmlTree = etree.ElementTree(xmlSequence) xmlString = etree.tostring(xmlTree, pretty_print=pretty) return xmlString def fromXmlString(self, xmlString): xmlElement = etree.fromstring(xmlString) newRoot = macro.SequenceNode(None) newRoot.fromXml(xmlElement) self.setRoot(newRoot) self.reset() return newRoot def fromPlainText(self, text): newRoot = macro.SequenceNode(None) newRoot.fromPlainText(text) self.setRoot(newRoot) self.reset() return newRoot def assignIds(self): """ Assigns ids for all macros present in the sequence. If certain macro already had an id, it stays without change. A list of all ids is returned :return: (list) """ parentNode = self.root() return self.__assignIds(parentNode) def __assignIds(self, parentNode): ids = [] for childNode in parentNode.children(): if isinstance(childNode, macro.MacroNode): id = childNode.assignId() ids.append(id) ids.extend(self.__assignIds(childNode)) return ids def firstMacroId(self): return self.root().child(0).id() def lastMacroId(self): root = self.root() return root.child(len(root.children()) - 1).id() def createIdIndexDictionary(self): parentIndex = Qt.QModelIndex() parentNode = self.root() return self.__createIdIndexDictionary(parentIndex, parentNode) def __createIdIndexDictionary(self, parentIndex, parentNode): d = {} for row, child in enumerate(parentNode.children()): if isinstance(child, macro.MacroNode): index = self.index(row, 0, parentIndex) d[child.id()] = index d.update(self.__createIdIndexDictionary(index, child)) return d # def supportedDropActions(self): # return Qt.Qt.CopyAction | Qt.Qt.MoveAction # def mimeTypes(self): # types = Qt.QStringList() # types.append("text/xml") # return types # def mimeData(self, indexes): # mimeData = Qt.QMimeData() # encodedData = Qt.QByteArray() # stream = Qt.QDataStream(encodedData, Qt.QIODevice.WriteOnly) # doc = xml.dom.minidom.Document() # for i,index in enumerate(indexes): # if i % 2: # continue # text = self.nodeFromIndex(index).toXml(doc).toxml() # stream.writeString(text) # # mimeData.setData("text/xml", encodedData) # return mimeData # # def dropMimeData(self, data, action, row, column, parent): # if action == Qt.Qt.IgnoreAction: # return True # if not data.hasFormat("text/xml"): # return False # # encodedData = data.data("text/xml") # stream = Qt.QDataStream(encodedData, Qt.QIODevice.ReadOnly) # newItems = Qt.QStringList() # rows = 0 # # while(not stream.atEnd()): # text = stream.readString() # newItems.append(text) # rows += 1 # # sequence = self.nodeFromIndex(parent) # # for text in newItems: # macroNode = macro.MacroNode() # macroNode.fromDoc(xml.dom.minidom.parseString(text)) # self.insertMacro(sequence, macroNode, row, False) # macros = [macro.name() for macro in macroNode.allMacros()] # if action == Qt.Qt.CopyAction: # self.emit(Qt.SIGNAL("macrosAdded"), macros, macroNode.allMotors()) # self.emit(Qt.SIGNAL("dataChanged")) # return True class MacroSequenceProxyModel(Qt.QSortFilterProxyModel): def __init__(self, parent=None): Qt.QSortFilterProxyModel.__init__(self, parent) self.setDynamicSortFilter(True) self.headers = ["Macro", "Parameters", "Progress", "Pause"] self.columns = 4 def __getattr__(self, name): return getattr(self.sourceModel(), name) def nodeFromIndex(self, index): sourceIndex = self.mapToSource(index) node = self.sourceModel().nodeFromIndex(sourceIndex) return node def createIdIndexDictionary(self): d = self.sourceModel().createIdIndexDictionary() for id, sourceIndex in d.iteritems(): proxyIndex = self.mapFromSource(sourceIndex) d[id] = Qt.QPersistentModelIndex(proxyIndex) return d def filterAcceptsRow(self, row, parentIndex): child = self.sourceModel().index(row, 0, parentIndex) node = self.sourceModel().nodeFromIndex(child) return isinstance(node, macro.MacroNode) class MacroParametersProxyModel(Qt.QSortFilterProxyModel): def __init__(self, parent=None): Qt.QSortFilterProxyModel.__init__(self, parent) self.columns = 2 self.headers = ["Parameter", "Value", "", "", "", ""] self._macroIndex = None def __getattr__(self, name): return getattr(self.sourceModel(), name) def headerData(self, section, orientation, role): if orientation == Qt.Qt.Horizontal and role == Qt.Qt.DisplayRole: return Qt.QVariant(self.headers[section]) return Qt.QVariant() def nodeFromIndex(self, index): sourceIndex = self.mapToSource(index) node = self.sourceModel().nodeFromIndex(sourceIndex) return node def setMacroIndex(self, macroIndex): self._macroIndex = macroIndex def macroIndex(self): return self._macroIndex def columnCount(self, parent): return self.columns def filterAcceptsRow(self, row, parentIndex): if self.macroIndex() == None: return False if self.macroIndex() == parentIndex: child = self.sourceModel().index(row, 0, parentIndex) node = self.sourceModel().nodeFromIndex(child) if not isinstance(node, macro.ParamNode): return False return True<|fim▁end|>
return len(branchNode)
<|file_name|>service.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # outgoing/service.py # Copyright (C) 2013-2017 LEAP # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ OutgoingMail module. The OutgoingMail class allows to send mail, and encrypts/signs it if needed. """ import re from StringIO import StringIO from copy import deepcopy from email.parser import Parser from email.encoders import encode_7or8bit from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from twisted.mail import smtp from twisted.internet import defer from twisted.python.failure import Failure from twisted.logger import Logger from leap.common.check import leap_assert_type, leap_assert from leap.common.events import emit_async, catalog from leap.bitmask.keymanager.errors import KeyNotFound, KeyAddressMismatch from leap.bitmask.mail.utils import validate_address from leap.bitmask.mail.rfc3156 import MultipartEncrypted from leap.bitmask.mail.rfc3156 import MultipartSigned from leap.bitmask.mail.rfc3156 import encode_base64_rec from leap.bitmask.mail.rfc3156 import RFC3156CompliantGenerator from leap.bitmask.mail.rfc3156 import PGPSignature from leap.bitmask.mail.rfc3156 import PGPEncrypted # TODO # [ ] rename this module to something else, service should be the implementor # of IService class OutgoingMail(object): """ Sends Outgoing Mail, encrypting and signing if needed. """ log = Logger() def __init__(self, from_address, keymanager, bouncer=None): """ Initialize the outgoing mail service. :param from_address: The sender address. :type from_address: str :param keymanager: A KeyManager for retrieving recipient's keys. :type keymanager: leap.common.keymanager.KeyManager """ # assert params leap_assert_type(from_address, (str, unicode)) leap_assert('@' in from_address) # XXX it can be a zope.proxy too # leap_assert_type(keymanager, KeyManager) self._from_address = from_address self._keymanager = keymanager self._bouncer = bouncer self._senders = [] def add_sender(self, sender): """ Add an ISender to the outgoing service """ self._senders.append(sender) def send_message(self, raw, recipient): """ Sends a message to a recipient. Maybe encrypts and signs. :param raw: The raw message :type raw: str :param recipient: The recipient for the message :type recipient: smtp.User :return: a deferred which delivers the message when fired """ d = self._maybe_encrypt_and_sign(raw, recipient) d.addCallback(self._route_msg, recipient, raw) d.addErrback(self.sendError, raw) return d def can_encrypt_for(self, recipient): def cb(_): return True def eb(failure): failure.trap(KeyNotFound) return False d = self._keymanager.get_key(recipient) d.addCallbacks(cb, eb) return d def sendSuccess(self, dest_addrstr): """ Callback for a successful send. """ fromaddr = self._from_address self.log.info('Message sent from %s to %s' % (fromaddr, dest_addrstr)) emit_async(catalog.SMTP_SEND_MESSAGE_SUCCESS, fromaddr, dest_addrstr) def sendError(self, failure, origmsg): """ Callback for an unsuccessful send. :param failure: The result from the last errback. :type failure: anything :param origmsg: the original, unencrypted, raw message, to be passed to the bouncer. :type origmsg: str """ # XXX: need to get the address from the original message to send signal # emit_async(catalog.SMTP_SEND_MESSAGE_ERROR, self._from_address, # self._user.dest.addrstr) # TODO when we implement outgoing queues/long-term-retries, we could # examine the error *here* and delay the notification if it's just a # temporal error. We might want to notify the permanent errors # differently. self.log.error('Error while sending: {0!r}'.format(failure)) if self._bouncer: self._bouncer.bounce_message( failure.getErrorMessage(), to=self._from_address, orig=origmsg) else: failure.raiseException() def _route_msg(self, encrypt_and_sign_result, recipient, raw): """ Sends the msg using the ESMTPSenderFactory. :param encrypt_and_sign_result: A tuple containing the 'maybe' encrypted message and the recipient :type encrypt_and_sign_result: tuple """ message, recipient = encrypt_and_sign_result msg = message.as_string(False) d = None for sender in self._senders: if sender.can_send(recipient.dest.addrstr): self.log.debug('Sending message to %s with: %s' % (recipient, str(sender))) d = sender.send(recipient, msg) break if d is None: return self.sendError(Failure(), raw) emit_async(catalog.SMTP_SEND_MESSAGE_START, self._from_address, recipient.dest.addrstr) d.addCallback(self.sendSuccess) d.addErrback(self.sendError, raw) return d def _maybe_encrypt_and_sign(self, raw, recipient, fetch_remote=True): """ Attempt to encrypt and sign the outgoing message. The behaviour of this method depends on: 1. the original message's content-type, and 2. the availability of the recipient's public key. If the original message's content-type is "multipart/encrypted", then the original message is not altered. For any other content-type, the method attempts to fetch the recipient's public key. If the recipient's public key is available, the message is encrypted and signed; otherwise it is only signed. Note that, if the C{encrypted_only} configuration is set to True and the recipient's public key is not available, then the recipient address would have been rejected in SMTPDelivery.validateTo(). The following table summarizes the overall behaviour of the gateway: +---------------------------------------------------+----------------+ | content-type | rcpt pubkey | enforce encr. | action | +---------------------+-------------+---------------+----------------+ | multipart/encrypted | any | any | pass | | other | available | any | encrypt + sign | | other | unavailable | yes | reject | | other | unavailable | no | sign | +---------------------+-------------+---------------+----------------+ :param raw: The raw message :type raw: str :param recipient: The recipient for the message :type: recipient: smtp.User :return: A Deferred that will be fired with a MIMEMultipart message and the original recipient Message :rtype: Deferred """ # pass if the original message's content-type is "multipart/encrypted" origmsg = Parser().parsestr(raw) if origmsg.get_content_type() == 'multipart/encrypted': return defer.succeed((origmsg, recipient)) from_address = validate_address(self._from_address) username, domain = from_address.split('@') to_address = validate_address(recipient.dest.addrstr) def maybe_encrypt_and_sign(message): d = self._encrypt_and_sign( message, to_address, from_address, fetch_remote=fetch_remote) d.addCallbacks(signal_encrypt_sign, if_key_not_found_send_unencrypted, errbackArgs=(message,)) return d def signal_encrypt_sign(newmsg): emit_async(catalog.SMTP_END_ENCRYPT_AND_SIGN, self._from_address, "%s,%s" % (self._from_address, to_address)) return newmsg, recipient def if_key_not_found_send_unencrypted(failure, message): failure.trap(KeyNotFound, KeyAddressMismatch) self.log.info('Will send unencrypted message to %s.' % to_address) emit_async(catalog.SMTP_START_SIGN, self._from_address, to_address) d = self._sign(message, from_address) d.addCallback(signal_sign) return d def signal_sign(newmsg): emit_async(catalog.SMTP_END_SIGN, self._from_address) return newmsg, recipient self.log.info("Will encrypt the message with %s and sign with %s." % (to_address, from_address)) emit_async(catalog.SMTP_START_ENCRYPT_AND_SIGN, self._from_address, "%s,%s" % (self._from_address, to_address)) d = self._attach_key(origmsg, from_address) d.addCallback(maybe_encrypt_and_sign) return d def _attach_key(self, origmsg, from_address): filename = "%s-email-key.asc" % (from_address,) def get_key_and_attach(): d = self._keymanager.get_key(from_address, fetch_remote=False) d.addCallback(attach_key) return d def attach_key(from_key): msg = origmsg if not origmsg.is_multipart(): msg = MIMEMultipart() for h, v in origmsg.items(): msg.add_header(h, v) msg.attach(MIMEText(origmsg.get_payload(decode=True), origmsg.get_content_subtype())) keymsg = MIMEApplication(from_key.key_data, _subtype='pgp-keys', _encoder=lambda x: x) keymsg.add_header('content-disposition', 'attachment', filename=filename) msg.attach(keymsg) return msg self.log.info("Will send %s public key as an attachment." % (from_address)) d = get_key_and_attach() d.addErrback(lambda _: origmsg) return d def _encrypt_and_sign(self, origmsg, encrypt_address, sign_address, fetch_remote=True): """ Create an RFC 3156 compliang PGP encrypted and signed message using C{encrypt_address} to encrypt and C{sign_address} to sign. :param origmsg: The original message :type origmsg: email.message.Message :param encrypt_address: The address used to encrypt the message. :type encrypt_address: str :param sign_address: The address used to sign the message. :type sign_address: str :return: A Deferred with the MultipartEncrypted message :rtype: Deferred """ # create new multipart/encrypted message with 'pgp-encrypted' protocol def encrypt(res): newmsg, origmsg = res d = self._keymanager.encrypt( origmsg.as_string(unixfrom=False), encrypt_address, sign=sign_address, fetch_remote=fetch_remote) d.addCallback(lambda encstr: (newmsg, encstr)) return d def create_encrypted_message(res): newmsg, encstr = res encmsg = MIMEApplication( encstr, _subtype='octet-stream', _encoder=encode_7or8bit) encmsg.add_header('content-disposition', 'attachment', filename='msg.asc') # create meta message metamsg = PGPEncrypted() metamsg.add_header('Content-Disposition', 'attachment') # attach pgp message parts to new message newmsg.attach(metamsg) newmsg.attach(encmsg) return newmsg d = self._fix_headers( origmsg, MultipartEncrypted('application/pgp-encrypted'), sign_address) d.addCallback(encrypt) d.addCallback(create_encrypted_message) return d def _sign(self, origmsg, sign_address): """ Create an RFC 3156 compliant PGP signed MIME message using C{sign_address}. :param origmsg: The original message :type origmsg: email.message.Message :param sign_address: The address used to sign the message. :type sign_address: str :return: A Deferred with the MultipartSigned message. :rtype: Deferred """ # apply base64 content-transfer-encoding encode_base64_rec(origmsg) # get message text with headers and replace \n for \r\n fp = StringIO() g = RFC3156CompliantGenerator( fp, mangle_from_=False, maxheaderlen=76) g.flatten(origmsg) msgtext = re.sub('\r?\n', '\r\n', fp.getvalue()) # make sure signed message ends with \r\n as per OpenPGP stantard. if origmsg.is_multipart(): if not msgtext.endswith("\r\n"): msgtext += "\r\n" def create_signed_message(res): (msg, _), signature = res sigmsg = PGPSignature(signature) # attach original message and signature to new message msg.attach(origmsg) msg.attach(sigmsg) return msg dh = self._fix_headers( origmsg, MultipartSigned('application/pgp-signature', 'pgp-sha512'), sign_address) ds = self._keymanager.sign( msgtext, sign_address, digest_algo='SHA512', clearsign=False, detach=True, binary=False) d = defer.gatherResults([dh, ds]) d.addCallback(create_signed_message) return d def _fix_headers(self, msg, newmsg, sign_address): """ Move some headers from C{origmsg} to C{newmsg}, delete unwanted headers from C{origmsg} and add new headers to C{newms}. Outgoing messages are either encrypted and signed or just signed before being sent. Because of that, they are packed inside new messages and some manipulation has to be made on their headers. Allowed headers for passing through: - From - Date - To - Subject - Reply-To - References - In-Reply-To - Cc Headers to be added: - Message-ID (i.e. should not use origmsg's Message-Id) - Received (this is added automatically by twisted smtp API) - OpenPGP (see #4447) Headers to be deleted: - User-Agent :param msg: The original message. :type msg: email.message.Message :param newmsg: The new message being created.<|fim▁hole|> :param sign_address: The address used to sign C{newmsg} :type sign_address: str :return: A Deferred with a touple: (new Message with the unencrypted headers, original Message with headers removed) :rtype: Deferred """ origmsg = deepcopy(msg) # move headers from origmsg to newmsg headers = origmsg.items() passthrough = [ 'from', 'date', 'to', 'subject', 'reply-to', 'references', 'in-reply-to', 'cc' ] headers = filter(lambda x: x[0].lower() in passthrough, headers) for hkey, hval in headers: newmsg.add_header(hkey, hval) del (origmsg[hkey]) # add a new message-id to newmsg newmsg.add_header('Message-Id', smtp.messageid()) # delete user-agent from origmsg del (origmsg['user-agent']) def add_openpgp_header(signkey): username, domain = sign_address.split('@') newmsg.add_header( 'OpenPGP', 'id=%s' % signkey.fingerprint, url='https://%s/key/%s' % (domain, username), preference='signencrypt') return newmsg, origmsg d = self._keymanager.get_key(sign_address, private=True) d.addCallback(add_openpgp_header) return d<|fim▁end|>
:type newmsg: email.message.Message
<|file_name|>match_on_vec_items.rs<|end_file_name|><|fim▁begin|>#![warn(clippy::match_on_vec_items)] fn match_with_wildcard() { let arr = vec![0, 1, 2, 3]; let range = 1..3; let idx = 1; // Lint, may panic match arr[idx] { 0 => println!("0"), 1 => println!("1"), _ => {}, } // Lint, may panic match arr[range] { [0, 1] => println!("0 1"), [1, 2] => println!("1 2"), _ => {}, } } fn match_without_wildcard() { let arr = vec![0, 1, 2, 3]; let range = 1..3; let idx = 2; // Lint, may panic match arr[idx] { 0 => println!("0"), 1 => println!("1"), num => {}, } // Lint, may panic match arr[range] { [0, 1] => println!("0 1"), [1, 2] => println!("1 2"), [ref sub @ ..] => {}, } } fn match_wildcard_and_action() { let arr = vec![0, 1, 2, 3]; let range = 1..3; let idx = 3; // Lint, may panic match arr[idx] { 0 => println!("0"), 1 => println!("1"), _ => println!("Hello, World!"), } // Lint, may panic match arr[range] { [0, 1] => println!("0 1"), [1, 2] => println!("1 2"), _ => println!("Hello, World!"), } } fn match_vec_ref() { let arr = &vec![0, 1, 2, 3]; let range = 1..3; let idx = 3; // Lint, may panic match arr[idx] { 0 => println!("0"), 1 => println!("1"), _ => {}, } // Lint, may panic match arr[range] { [0, 1] => println!("0 1"), [1, 2] => println!("1 2"), _ => {}, } } fn match_with_get() { let arr = vec![0, 1, 2, 3]; let range = 1..3; let idx = 3; // Ok match arr.get(idx) { Some(0) => println!("0"), Some(1) => println!("1"), _ => {}, } // Ok match arr.get(range) { Some(&[0, 1]) => println!("0 1"), Some(&[1, 2]) => println!("1 2"), _ => {}, } } fn match_with_array() { let arr = [0, 1, 2, 3];<|fim▁hole|> let range = 1..3; let idx = 3; // Ok match arr[idx] { 0 => println!("0"), 1 => println!("1"), _ => {}, } // Ok match arr[range] { [0, 1] => println!("0 1"), [1, 2] => println!("1 2"), _ => {}, } } fn match_with_endless_range() { let arr = vec![0, 1, 2, 3]; let range = ..; // Ok match arr[range] { [0, 1] => println!("0 1"), [1, 2] => println!("1 2"), [0, 1, 2, 3] => println!("0, 1, 2, 3"), _ => {}, } // Ok match arr[..] { [0, 1] => println!("0 1"), [1, 2] => println!("1 2"), [0, 1, 2, 3] => println!("0, 1, 2, 3"), _ => {}, } } fn main() { match_with_wildcard(); match_without_wildcard(); match_wildcard_and_action(); match_vec_ref(); match_with_get(); match_with_array(); match_with_endless_range(); }<|fim▁end|>
<|file_name|>qualitymodis.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # class to convert/process modis data # # (c) Copyright Ingmar Nitze 2013 # Authors: Ingmar Nitze, Luca Delucchi # Email: initze at ucc dot ie # Email: luca dot delucchi at iasma dot it # ################################################################## # # This MODIS Python class is licensed under the terms of GNU GPL 2. # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # ################################################################## """A class for the extraction and transformation of MODIS quality layers to specific information Classes: * :class:`QualityModis` """ from __future__ import print_function import os import numpy as np try: import osgeo.gdal as gdal import osgeo.gdal_array as gdal_array except ImportError: try: import gdal import gdal_array except ImportError: raise 'Python GDAL library not found, please install python-gdal' VALIDTYPES = {'13': map(str, range(1, 10)), '11': map(str, range(1, 6))} PRODUCTPROPS = {'MOD13Q1': ([2], ['QAGrp1']), 'MYD13Q1': ([2], ['QAGrp1']), 'MOD13A1': ([2], ['QAGrp1']), 'MYD13A1': ([2], ['QAGrp1']), 'MOD13A2': ([2], ['QAGrp1']), 'MYD13A2': ([2], ['QAGrp1']), 'MOD13A3': ([2], ['QAGrp1']), 'MYD13A3': ([2], ['QAGrp1']), 'MOD13C1': ([2], ['QAGrp1']), 'MYD13C1': ([2], ['QAGrp1']), 'MOD13C2': ([2], ['QAGrp1']), 'MYD13C2': ([2], ['QAGrp1']), 'MOD11A1': ([1, 5], ['QAGrp2', 'QAGrp2']), 'MYD11A1': ([1, 5], ['QAGrp2', 'QAGrp2']), 'MOD11A2': ([1, 5], ['QAGrp4', 'QAGrp4']), 'MYD11A2': ([1, 5], ['QAGrp4', 'QAGrp4']), 'MOD11B1': ([1, 5, -2], ['QAGrp2', 'QAGrp2', 'QAGrp3']), 'MYD11B1': ([1, 5, -2], ['QAGrp2', 'QAGrp2', 'QAGrp3']), 'MOD11C1': ([1, 5, -2], ['QAGrp2', 'QAGrp2', 'QAGrp3']), 'MYD11C1': ([1, 5, -2], ['QAGrp2', 'QAGrp2', 'QAGrp3']), 'MOD11C2': ([1, 6], ['QAGrp2', 'QAGrp2']), 'MYD11C2': ([1, 6], ['QAGrp2', 'QAGrp2']), 'MOD11C3': ([1, 6], ['QAGrp2', 'QAGrp2']), 'MYD11C3': ([1, 6], ['QAGrp2', 'QAGrp2'])} QAindices = {'QAGrp1': (16, [[-2, None], [-6, -2], [-8, -6], [-9, -8], [-10, -9], [-11, -10], [-14, -11], [-15, -14], [-16, -15]]), 'QAGrp2': (7, [[-2, None], [-3, -2], [-4, -3], [-6, -4], [-8, -6]]), 'QAGrp3': (7, [[-3, None], [-6, -3], [-7, -6]]), 'QAGrp4': (8, [[-2, None], [-4, -2], [-6, -4], [-8, -6]])} class QualityModis(): """A Class for the extraction and transformation of MODIS<|fim▁hole|> :param str infile: the full path to the hdf file :param str outfile: the full path to the parameter file """ def __init__(self, infile, outfile, qType=None, qLayer=None, pType=None): """Function to initialize the object""" self.infile = infile self.outfile = outfile self.qType = qType self.qLayer = qLayer self.qaGroup = None self.pType = pType def loadData(self): """loads the input file to the object""" os.path.isfile(self.infile) self.ds = gdal.Open(self.infile) def setProductType(self): """read productType from Metadata of hdf file""" if self.pType == None: self.productType = self.ds.GetMetadata()['SHORTNAME'] else: self.productType = self.pType def setProductGroup(self): """read productGroup from Metadata of hdf file""" self.productGroup = self.productType[3:5] def setQAGroup(self): """set QA dataset group type""" if self.productType in PRODUCTPROPS.keys(): self.qaGroup = PRODUCTPROPS[self.productType][1][int(self.qLayer)-1] else: print("Product version is currently not supported!") def setQALayer(self): """function sets the input path of the designated QA layer""" self.qaLayer = self.ds.GetSubDatasets()[PRODUCTPROPS[self.productType][0][int(self.qLayer)-1]][0] def loadQAArray(self): """loads the QA layer to the object""" self.qaArray = gdal_array.LoadFile(self.qaLayer) def qualityConvert(self, modisQaValue): """converts encoded Bit-Field values to designated QA information""" startindex = QAindices[self.qaGroup][1][int(self.qType)-1][0] endindex = QAindices[self.qaGroup][1][int(self.qType)-1][1] return int(np.binary_repr(modisQaValue, QAindices[self.qaGroup][0])[startindex: endindex], 2) def exportData(self): """writes calculated QA values to physical .tif file""" qaDS = gdal.Open(self.qaLayer) dr = gdal.GetDriverByName('GTiff') outds = dr.Create(self.outfile, self.ncols, self.nrows, 1, gdal.GDT_Byte) outds.SetProjection(qaDS.GetProjection()) outds.SetGeoTransform(qaDS.GetGeoTransform()) outds.GetRasterBand(1).WriteArray(self.qaOut) outds = None qaDS = None def run(self): """Function defines the entire process""" self.loadData() self.setProductType() self.setProductGroup() #self.setDSversion() self.setQAGroup() self.setQALayer() self.loadQAArray() self.nrows, self.ncols = self.qaArray.shape print("Conversion started !") self.qaOut = np.zeros_like(self.qaArray, dtype=np.int8) if self.productGroup in ['11', '13'] and self.qType in VALIDTYPES[self.productGroup] and self.qaGroup != None: for val in np.unique(self.qaArray): ind = np.where(self.qaArray == val) self.qaOut[ind] = self.qualityConvert(self.qaArray[ind][0]) self.exportData() print("Export finished!") else: print("This MODIS type is currently not supported.")<|fim▁end|>
quality layers to specific information
<|file_name|>memory_cache_http_server_unittest.py<|end_file_name|><|fim▁begin|># Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import os from telemetry.core import util from telemetry.core import memory_cache_http_server from telemetry.testing import tab_test_case class RequestHandler( memory_cache_http_server.MemoryCacheDynamicHTTPRequestHandler): def ResponseFromHandler(self, path): content = "Hello from handler" return self.MakeResponse(content, "text/html", False) class MemoryCacheHTTPServerTest(tab_test_case.TabTestCase): def setUp(self): super(MemoryCacheHTTPServerTest, self).setUp() self._test_filename = 'bear.webm' test_file = os.path.join(util.GetUnittestDataDir(), 'bear.webm') self._test_file_size = os.stat(test_file).st_size def testBasicHostingAndRangeRequests(self): self.Navigate('blank.html') x = self._tab.EvaluateJavaScript('document.body.innerHTML') x = x.strip() # Test basic html hosting. self.assertEqual(x, 'Hello world') file_size = self._test_file_size last_byte = file_size - 1<|fim▁hole|> self.CheckContentHeaders('100-', '100-%d' % last_byte, file_size - 100) # Test byte range request: explicit byte range. self.CheckContentHeaders('2-500', '2-500', '499') # Test byte range request: no start byte. self.CheckContentHeaders('-228', '%d-%d' % (file_size - 228, last_byte), '228') # Test byte range request: end byte less than start byte. self.CheckContentHeaders('100-5', '100-%d' % last_byte, file_size - 100) def CheckContentHeaders(self, content_range_request, content_range_response, content_length_response): self._tab.ExecuteJavaScript( """ var loaded = false; var xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function(e) { loaded = true; }; // Avoid cached content by appending unique URL param. xmlhttp.open('GET', {{ url }} + "?t=" + Date.now(), true); xmlhttp.setRequestHeader('Range', {{ range }}); xmlhttp.send(); """, url=self.UrlOfUnittestFile(self._test_filename), range='bytes=%s' % content_range_request) self._tab.WaitForJavaScriptCondition('loaded', timeout=5) content_range = self._tab.EvaluateJavaScript( 'xmlhttp.getResponseHeader("Content-Range");') content_range_response = 'bytes %s/%d' % (content_range_response, self._test_file_size) self.assertEqual(content_range, content_range_response) content_length = self._tab.EvaluateJavaScript( 'xmlhttp.getResponseHeader("Content-Length");') self.assertEqual(content_length, str(content_length_response)) def testAbsoluteAndRelativePathsYieldSameURL(self): test_file_rel_path = 'green_rect.html' test_file_abs_path = os.path.abspath( os.path.join(util.GetUnittestDataDir(), test_file_rel_path)) # It's necessary to bypass self.UrlOfUnittestFile since that # concatenates the unittest directory on to the incoming path, # causing the same code path to be taken in both cases. self._platform.SetHTTPServerDirectories(util.GetUnittestDataDir()) self.assertEqual(self._platform.http_server.UrlOf(test_file_rel_path), self._platform.http_server.UrlOf(test_file_abs_path)) def testDynamicHTTPServer(self): self.Navigate('test.html', handler_class=RequestHandler) x = self._tab.EvaluateJavaScript('document.body.innerHTML') self.assertEqual(x, 'Hello from handler')<|fim▁end|>
# Test byte range request: no end byte. self.CheckContentHeaders('0-', '0-%d' % last_byte, file_size) # Test byte range request: greater than zero start byte.
<|file_name|>ExceptionReplySubjectIdEmpty.java<|end_file_name|><|fim▁begin|>package com.x.bbs.assemble.control.jaxrs.replyinfo.exception; import com.x.base.core.project.exception.PromptException; public class ExceptionReplySubjectIdEmpty extends PromptException {<|fim▁hole|> public ExceptionReplySubjectIdEmpty() { super("主题ID为空,无法继续查询操作。" ); } }<|fim▁end|>
private static final long serialVersionUID = 1859164370743532895L;
<|file_name|>StatsAggregationBuilder.java<|end_file_name|><|fim▁begin|>/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.search.aggregations.metrics.stats; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.ObjectParser; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.search.aggregations.AggregationBuilder; import org.elasticsearch.search.aggregations.AggregatorFactories.Builder; import org.elasticsearch.search.aggregations.AggregatorFactory; import org.elasticsearch.search.aggregations.support.ValueType; import org.elasticsearch.search.aggregations.support.ValuesSource; import org.elasticsearch.search.aggregations.support.ValuesSource.Numeric; import org.elasticsearch.search.aggregations.support.ValuesSourceAggregationBuilder; import org.elasticsearch.search.aggregations.support.ValuesSourceConfig; import org.elasticsearch.search.aggregations.support.ValuesSourceParserHelper; import org.elasticsearch.search.aggregations.support.ValuesSourceType; import org.elasticsearch.search.SearchContext; import java.io.IOException; import java.util.Map; public class StatsAggregationBuilder extends ValuesSourceAggregationBuilder.LeafOnly<ValuesSource.Numeric, StatsAggregationBuilder> { public static final String NAME = "stats"; private static final ObjectParser<StatsAggregationBuilder, Void> PARSER; static { PARSER = new ObjectParser<>(StatsAggregationBuilder.NAME); ValuesSourceParserHelper.declareNumericFields(PARSER, true, true, false); } public static AggregationBuilder parse(String aggregationName, XContentParser parser) throws IOException { return PARSER.parse(parser, new StatsAggregationBuilder(aggregationName), null); } public StatsAggregationBuilder(String name) { super(name, ValuesSourceType.NUMERIC, ValueType.NUMERIC); } protected StatsAggregationBuilder(StatsAggregationBuilder clone, Builder factoriesBuilder, Map<String, Object> metaData) { super(clone, factoriesBuilder, metaData); } @Override public AggregationBuilder shallowCopy(Builder factoriesBuilder, Map<String, Object> metaData) { return new StatsAggregationBuilder(this, factoriesBuilder, metaData); } /** * Read from a stream. */ public StatsAggregationBuilder(StreamInput in) throws IOException {<|fim▁hole|> } @Override protected void innerWriteTo(StreamOutput out) { // Do nothing, no extra state to write to stream } @Override protected StatsAggregatorFactory innerBuild(SearchContext context, ValuesSourceConfig<Numeric> config, AggregatorFactory<?> parent, Builder subFactoriesBuilder) throws IOException { return new StatsAggregatorFactory(name, config, context, parent, subFactoriesBuilder, metaData); } @Override public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException { return builder; } @Override protected int innerHashCode() { return 0; } @Override protected boolean innerEquals(Object obj) { return true; } @Override public String getType() { return NAME; } }<|fim▁end|>
super(in, ValuesSourceType.NUMERIC, ValueType.NUMERIC);
<|file_name|>apiproxy_stub.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # Copyright 2007 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Base class for implementing API proxy stubs.""" <|fim▁hole|> import logging import random import threading from google.appengine.api import apiproxy_rpc from google.appengine.api import request_info from google.appengine.runtime import apiproxy_errors MAX_REQUEST_SIZE = 1 << 20 REQ_SIZE_EXCEEDS_LIMIT_MSG_TEMPLATE = ('The request to API call %s.%s() was too' ' large.') logging.getLogger('google.appengine.api.stubs').setLevel(logging.INFO) class APIProxyStub(object): """Base class for implementing API proxy stub classes. To implement an API proxy stub: - Extend this class. - Override `__init__` to pass in appropriate default service name. - Implement service methods as `_Dynamic_<method>(request, response)`. """ _ACCEPTS_REQUEST_ID = False THREADSAFE = False def __init__(self, service_name, max_request_size=MAX_REQUEST_SIZE, request_data=None): """Constructor. Args: service_name: Service name expected for all calls. max_request_size: `int`. Maximum allowable size of the incoming request. An `apiproxy_errors.RequestTooLargeError` will be raised if the inbound request exceeds this size. Default is 1 MB. Subclasses can override it. request_data: A `request_info.RequestInfo` instance used to look up state associated with the request that generated an API call. """ self.__service_name = service_name self.__max_request_size = max_request_size self.request_data = request_data or request_info._local_request_info self._mutex = threading.RLock() self.__error = None self.__error_dict = {} def CreateRPC(self): """Creates RPC object instance. Returns: An instance of RPC. """ return apiproxy_rpc.RPC(stub=self) def CheckRequest(self, service, call, request): """Check if a request meet some common restrictions. Args: service: Must be name as provided to `service_name` of constructor. call: A string representing the rpc to make. request: A protocol buffer of the type corresponding to `call`. """ assert service == self.__service_name, ('Expected "%s" service name, ' 'was "%s"' % (self.__service_name, service)) if request.ByteSize() > self.__max_request_size: raise apiproxy_errors.RequestTooLargeError( REQ_SIZE_EXCEEDS_LIMIT_MSG_TEMPLATE % (service, call)) messages = [] assert request.IsInitialized(messages), messages def MakeSyncCall(self, service, call, request, response, request_id=None): """The main RPC entry point. Args: service: Must be name as provided to `service_name` of constructor. call: A string representing the rpc to make. Must be part of the underlying services methods and impemented by `_Dynamic_<call>`. request: A protocol buffer of the type corresponding to `call`. response: A protocol buffer of the type corresponding to `call`. request_id: A unique string identifying the request associated with the API call. """ self.CheckRequest(service, call, request) exception_type, frequency = self.__error_dict.get(call, (None, None)) if exception_type and frequency: if random.random() <= frequency: raise exception_type if self.__error: if random.random() <= self.__error_rate: raise self.__error method = getattr(self, '_Dynamic_' + call) if self._ACCEPTS_REQUEST_ID: method(request, response, request_id) else: method(request, response) def SetError(self, error, method=None, error_rate=1): """Set an error condition that may be raised when calls made to stub. If a method is specified, the error will only apply to that call. The error rate is applied to the method specified or all calls if method is not set. Args: error: An instance of `apiproxy_errors.Error` or `None` for no error. method: A string representing the method that the error will affect. error_rate: a number from `[0, 1]` that sets the chance of the error, defaults to `1`. """ assert error is None or isinstance(error, apiproxy_errors.Error) if method and error: self.__error_dict[method] = error, error_rate else: self.__error_rate = error_rate self.__error = error def Synchronized(method): """Decorator to acquire a mutex around an `APIProxyStub` method. Args: method: An unbound method of `APIProxyStub` or a subclass. Returns: The `method`, altered such it acquires `self._mutex` throughout its execution. """ def WrappedMethod(self, *args, **kwargs): with self._mutex: return method(self, *args, **kwargs) return WrappedMethod<|fim▁end|>
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>pub mod mocknet_controller; pub mod bitcoin_regtest_controller; pub use self::mocknet_controller::{MocknetController}; pub use self::bitcoin_regtest_controller::{BitcoinRegtestController}; use super::operations::BurnchainOpSigner; use std::time::Instant; use stacks::burnchains::BurnchainStateTransition; use stacks::chainstate::burn::db::burndb::{BurnDB}; use stacks::chainstate::burn::{BlockSnapshot}; use stacks::chainstate::burn::operations::BlockstackOperationType; pub trait BurnchainController { fn start(&mut self) -> BurnchainTip; fn submit_operation(&mut self, operation: BlockstackOperationType, op_signer: &mut BurnchainOpSigner) -> bool; fn sync(&mut self) -> BurnchainTip; fn burndb_ref(&self) -> &BurnDB; fn burndb_mut(&mut self) -> &mut BurnDB; fn get_chain_tip(&mut self) -> BurnchainTip; #[cfg(test)] fn bootstrap_chain(&mut self, blocks_count: u64); } #[derive(Debug, Clone)] pub struct BurnchainTip { pub block_snapshot: BlockSnapshot, pub state_transition: BurnchainStateTransition, pub received_at: Instant, } impl BurnchainTip { pub fn get_winning_tx_index(&self) -> Option<u32> { let winning_tx_id = self.block_snapshot.winning_block_txid; let mut winning_tx_vtindex = None;<|fim▁hole|> if let BlockstackOperationType::LeaderBlockCommit(op) = op { if op.txid == winning_tx_id { winning_tx_vtindex = Some(op.vtxindex) } } } winning_tx_vtindex } }<|fim▁end|>
for op in self.state_transition.accepted_ops.iter() {
<|file_name|>pythonshell.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # Copyright © 2009-2010 Pierre Raybaut # Licensed under the terms of the MIT License # (see spyderlib/__init__.py for details) """External Python Shell widget: execute Python script in a separate process""" import sys import os import os.path as osp import socket from spyderlib.qt.QtGui import QApplication, QMessageBox, QSplitter, QMenu from spyderlib.qt.QtCore import QProcess, SIGNAL, Qt from spyderlib.qt.compat import getexistingdirectory # Local imports from spyderlib.utils.qthelpers import (get_icon, get_std_icon, add_actions, create_toolbutton, create_action, DialogManager) from spyderlib.utils.environ import RemoteEnvDialog from spyderlib.utils.programs import get_python_args from spyderlib.utils.misc import get_python_executable from spyderlib.baseconfig import (_, get_module_source_path, DEBUG, MAC_APP_NAME, running_in_mac_app) from spyderlib.widgets.shell import PythonShellWidget from spyderlib.widgets.externalshell.namespacebrowser import NamespaceBrowser from spyderlib.utils.bsdsocket import communicate, write_packet from spyderlib.widgets.externalshell.baseshell import (ExternalShellBase, add_pathlist_to_PYTHONPATH) from spyderlib.widgets.dicteditor import DictEditor from spyderlib.py3compat import (is_text_string, to_text_string, to_binary_string) class ExtPythonShellWidget(PythonShellWidget): def __init__(self, parent, history_filename, profile=False): PythonShellWidget.__init__(self, parent, history_filename, profile) self.path = [] def set_externalshell(self, externalshell): # ExternalShellBase instance: self.externalshell = externalshell def clear_terminal(self): """Reimplement ShellBaseWidget method""" self.clear() self.emit(SIGNAL("execute(QString)"), "\n") def execute_lines(self, lines): """ Execute a set of lines as multiple command lines: multiple lines of text to be executed as single commands """ for line in lines.splitlines(): stripped_line = line.strip() if stripped_line.startswith('#'): continue self.write(line+os.linesep, flush=True) self.execute_command(line) # Workaround for Issue 502 # Emmiting wait_for_ready_read was making the console hang # in Mac OS X if sys.platform.startswith("darwin"): import time time.sleep(0.025) else: self.emit(SIGNAL("wait_for_ready_read()")) self.flush() #------ Code completion / Calltips def ask_monitor(self, command, settings=[]): sock = self.externalshell.introspection_socket if sock is None: return try: return communicate(sock, command, settings=settings) except socket.error: # Process was just closed pass except MemoryError: # Happens when monitor is not ready on slow machines pass def get_dir(self, objtxt): """Return dir(object)""" return self.ask_monitor("__get_dir__('%s')" % objtxt) def get_globals_keys(self): """Return shell globals() keys""" return self.ask_monitor("get_globals_keys()") def get_cdlistdir(self): """Return shell current directory list dir""" return self.ask_monitor("getcdlistdir()") def iscallable(self, objtxt): """Is object callable?""" return self.ask_monitor("__iscallable__('%s')" % objtxt) def get_arglist(self, objtxt): """Get func/method argument list""" return self.ask_monitor("__get_arglist__('%s')" % objtxt) def get__doc__(self, objtxt): """Get object __doc__""" return self.ask_monitor("__get__doc____('%s')" % objtxt) def get_doc(self, objtxt): """Get object documentation dictionary""" return self.ask_monitor("__get_doc__('%s')" % objtxt) def get_source(self, objtxt): """Get object source""" return self.ask_monitor("__get_source__('%s')" % objtxt) def is_defined(self, objtxt, force_import=False): """Return True if object is defined""" return self.ask_monitor("isdefined('%s', force_import=%s)" % (objtxt, force_import)) def get_module_completion(self, objtxt): """Return module completion list associated to object name""" return self.ask_monitor("getmodcomplist('%s', %s)" % \ (objtxt, self.path)) def get_cwd(self): """Return shell current working directory""" return self.ask_monitor("getcwd()") def set_cwd(self, dirname): """Set shell current working directory""" return self.ask_monitor("setcwd(r'%s')" % dirname) def get_env(self): """Return environment variables: os.environ""" return self.ask_monitor("getenv()") def set_env(self, env): """Set environment variables via os.environ""" return self.ask_monitor('setenv()', settings=[env]) def get_syspath(self): """Return sys.path[:]""" return self.ask_monitor("getsyspath()") def set_spyder_breakpoints(self): """Set Spyder breakpoints into debugging session""" return self.ask_monitor("set_spyder_breakpoints()") class ExternalPythonShell(ExternalShellBase): """External Shell widget: execute Python script in a separate process""" SHELL_CLASS = ExtPythonShellWidget def __init__(self, parent=None, fname=None, wdir=None, interact=False, debug=False, path=[], python_args='', ipykernel=False, arguments='', stand_alone=None, umr_enabled=True, umr_namelist=[], umr_verbose=True, pythonstartup=None, pythonexecutable=None, monitor_enabled=True, mpl_backend=None, ets_backend='qt4', qt_api=None, pyqt_api=0, ignore_sip_setapi_errors=False, merge_output_channels=False, colorize_sys_stderr=False, autorefresh_timeout=3000, autorefresh_state=True, light_background=True, menu_actions=None, show_buttons_inside=True, show_elapsed_time=True): assert qt_api in (None, 'pyqt', 'pyside') self.namespacebrowser = None # namespace browser widget! self.dialog_manager = DialogManager() self.stand_alone = stand_alone # stand alone settings (None: plugin) self.interact = interact self.is_ipykernel = ipykernel self.pythonstartup = pythonstartup self.pythonexecutable = pythonexecutable self.monitor_enabled = monitor_enabled self.mpl_backend = mpl_backend self.ets_backend = ets_backend self.qt_api = qt_api self.pyqt_api = pyqt_api self.ignore_sip_setapi_errors = ignore_sip_setapi_errors self.merge_output_channels = merge_output_channels self.colorize_sys_stderr = colorize_sys_stderr self.umr_enabled = umr_enabled self.umr_namelist = umr_namelist self.umr_verbose = umr_verbose self.autorefresh_timeout = autorefresh_timeout self.autorefresh_state = autorefresh_state self.namespacebrowser_button = None self.cwd_button = None self.env_button = None self.syspath_button = None self.terminate_button = None self.notification_thread = None ExternalShellBase.__init__(self, parent=parent, fname=fname, wdir=wdir, history_filename='history.py', light_background=light_background, menu_actions=menu_actions, show_buttons_inside=show_buttons_inside, show_elapsed_time=show_elapsed_time) if self.pythonexecutable is None: self.pythonexecutable = get_python_executable() self.python_args = None if python_args: assert is_text_string(python_args) self.python_args = python_args assert is_text_string(arguments) self.arguments = arguments self.connection_file = None if self.is_ipykernel: self.interact = False # Running our custom startup script for IPython kernels: # (see spyderlib/widgets/externalshell/start_ipython_kernel.py) self.fname = get_module_source_path( 'spyderlib.widgets.externalshell', 'start_ipython_kernel.py') self.shell.set_externalshell(self) self.toggle_globals_explorer(False) self.interact_action.setChecked(self.interact) self.debug_action.setChecked(debug) self.introspection_socket = None self.is_interpreter = fname is None if self.is_interpreter: self.terminate_button.hide() # Additional python path list self.path = path self.shell.path = path def set_introspection_socket(self, introspection_socket): self.introspection_socket = introspection_socket if self.namespacebrowser is not None: settings = self.namespacebrowser.get_view_settings() communicate(introspection_socket, 'set_remote_view_settings()', settings=[settings]) def set_autorefresh_timeout(self, interval): if self.introspection_socket is not None: try: communicate(self.introspection_socket, "set_monitor_timeout(%d)" % interval) except socket.error: pass def closeEvent(self, event): self.quit_monitor() ExternalShellBase.closeEvent(self, event) def get_toolbar_buttons(self): ExternalShellBase.get_toolbar_buttons(self) if self.namespacebrowser_button is None \ and self.stand_alone is not None: self.namespacebrowser_button = create_toolbutton(self, text=_("Variables"), icon=get_icon('dictedit.png'), tip=_("Show/hide global variables explorer"), toggled=self.toggle_globals_explorer, text_beside_icon=True) if self.terminate_button is None: self.terminate_button = create_toolbutton(self, text=_("Terminate"), icon=get_icon('stop.png'), tip=_("Attempts to stop the process. The process\n" "may not exit as a result of clicking this\n" "button (it is given the chance to prompt\n" "the user for any unsaved files, etc).")) buttons = [] if self.namespacebrowser_button is not None: buttons.append(self.namespacebrowser_button) buttons += [self.run_button, self.terminate_button, self.kill_button, self.options_button] return buttons def get_options_menu(self): ExternalShellBase.get_options_menu(self) self.interact_action = create_action(self, _("Interact")) self.interact_action.setCheckable(True) self.debug_action = create_action(self, _("Debug")) self.debug_action.setCheckable(True) self.args_action = create_action(self, _("Arguments..."), triggered=self.get_arguments) run_settings_menu = QMenu(_("Run settings"), self) add_actions(run_settings_menu, (self.interact_action, self.debug_action, self.args_action)) self.cwd_button = create_action(self, _("Working directory"), icon=get_std_icon('DirOpenIcon'), tip=_("Set current working directory"), triggered=self.set_current_working_directory) self.env_button = create_action(self, _("Environment variables"), icon=get_icon('environ.png'), triggered=self.show_env) self.syspath_button = create_action(self, _("Show sys.path contents"), icon=get_icon('syspath.png'), triggered=self.show_syspath) actions = [run_settings_menu, self.show_time_action, None, self.cwd_button, self.env_button, self.syspath_button] if self.menu_actions is not None: actions += [None]+self.menu_actions return actions def is_interpreter(self): """Return True if shellwidget is a Python interpreter""" return self.is_interpreter def get_shell_widget(self): if self.stand_alone is None: return self.shell else: self.namespacebrowser = NamespaceBrowser(self) settings = self.stand_alone self.namespacebrowser.set_shellwidget(self) self.namespacebrowser.setup(**settings) self.connect(self.namespacebrowser, SIGNAL('collapse()'), lambda: self.toggle_globals_explorer(False)) # Shell splitter self.splitter = splitter = QSplitter(Qt.Vertical, self) self.connect(self.splitter, SIGNAL('splitterMoved(int, int)'), self.splitter_moved) splitter.addWidget(self.shell) splitter.setCollapsible(0, False) splitter.addWidget(self.namespacebrowser) splitter.setStretchFactor(0, 1) splitter.setStretchFactor(1, 0) splitter.setHandleWidth(5) splitter.setSizes([2, 1]) return splitter def get_icon(self): return get_icon('python.png') def set_buttons_runnning_state(self, state): ExternalShellBase.set_buttons_runnning_state(self, state) self.interact_action.setEnabled(not state and not self.is_interpreter) self.debug_action.setEnabled(not state and not self.is_interpreter) self.args_action.setEnabled(not state and not self.is_interpreter) if state: if self.arguments: argstr = _("Arguments: %s") % self.arguments else: argstr = _("No argument") else: argstr = _("Arguments...") self.args_action.setText(argstr) self.terminate_button.setVisible(not self.is_interpreter and state) if not state: self.toggle_globals_explorer(False) for btn in (self.cwd_button, self.env_button, self.syspath_button): btn.setEnabled(state and self.monitor_enabled) if self.namespacebrowser_button is not None: self.namespacebrowser_button.setEnabled(state) def set_namespacebrowser(self, namespacebrowser): """ Set namespace browser *widget* Note: this method is not used in stand alone mode """ self.namespacebrowser = namespacebrowser self.configure_namespacebrowser() def configure_namespacebrowser(self): """Connect the namespace browser to the notification thread""" if self.notification_thread is not None: self.connect(self.notification_thread, SIGNAL('refresh_namespace_browser()'), self.namespacebrowser.refresh_table) signal = self.notification_thread.sig_process_remote_view signal.connect(lambda data: self.namespacebrowser.process_remote_view(data)) def create_process(self): self.shell.clear() self.process = QProcess(self) if self.merge_output_channels: self.process.setProcessChannelMode(QProcess.MergedChannels) else: self.process.setProcessChannelMode(QProcess.SeparateChannels) self.connect(self.shell, SIGNAL("wait_for_ready_read()"), lambda: self.process.waitForReadyRead(250)) # Working directory if self.wdir is not None: self.process.setWorkingDirectory(self.wdir) #-------------------------Python specific------------------------------- # Python arguments p_args = ['-u'] if DEBUG >= 3: p_args += ['-v'] p_args += get_python_args(self.fname, self.python_args, self.interact_action.isChecked(), self.debug_action.isChecked(), self.arguments) env = [to_text_string(_path) for _path in self.process.systemEnvironment()] if self.pythonstartup: env.append('PYTHONSTARTUP=%s' % self.pythonstartup) # Set standard input/output encoding for Python consoles # (IPython handles it on its own) # See http://stackoverflow.com/q/26312400/438386, specifically # the comments of Martijn Pieters if not self.is_ipykernel: env.append('PYTHONIOENCODING=UTF-8') # Monitor if self.monitor_enabled: env.append('SPYDER_SHELL_ID=%s' % id(self)) env.append('SPYDER_AR_TIMEOUT=%d' % self.autorefresh_timeout) env.append('SPYDER_AR_STATE=%r' % self.autorefresh_state) from spyderlib.widgets.externalshell import introspection introspection_server = introspection.start_introspection_server() introspection_server.register(self) notification_server = introspection.start_notification_server() self.notification_thread = notification_server.register(self) self.connect(self.notification_thread, SIGNAL('pdb(QString,int)'), lambda fname, lineno: self.emit(SIGNAL('pdb(QString,int)'), fname, lineno)) self.connect(self.notification_thread, SIGNAL('new_ipython_kernel(QString)'), lambda args: self.emit(SIGNAL('create_ipython_client(QString)'), args)) self.connect(self.notification_thread, SIGNAL('open_file(QString,int)'), lambda fname, lineno: self.emit(SIGNAL('open_file(QString,int)'), fname, lineno)) if self.namespacebrowser is not None: self.configure_namespacebrowser() env.append('SPYDER_I_PORT=%d' % introspection_server.port) env.append('SPYDER_N_PORT=%d' % notification_server.port) # External modules options env.append('ETS_TOOLKIT=%s' % self.ets_backend) if self.mpl_backend: env.append('MATPLOTLIB_BACKEND=%s' % self.mpl_backend) if self.qt_api: env.append('QT_API=%s' % self.qt_api) env.append('COLORIZE_SYS_STDERR=%s' % self.colorize_sys_stderr) # # Socket-based alternative (see input hook in sitecustomize.py): # if self.install_qt_inputhook: # from PyQt4.QtNetwork import QLocalServer # self.local_server = QLocalServer() # self.local_server.listen(str(id(self))) if self.pyqt_api: env.append('PYQT_API=%d' % self.pyqt_api) env.append('IGNORE_SIP_SETAPI_ERRORS=%s' % self.ignore_sip_setapi_errors) # User Module Deleter if self.is_interpreter: env.append('UMR_ENABLED=%r' % self.umr_enabled) env.append('UMR_NAMELIST=%s' % ','.join(self.umr_namelist)) env.append('UMR_VERBOSE=%r' % self.umr_verbose) env.append('MATPLOTLIB_ION=True') else: if self.interact: env.append('MATPLOTLIB_ION=True') else: env.append('MATPLOTLIB_ION=False') # IPython kernel env.append('IPYTHON_KERNEL=%r' % self.is_ipykernel) # Add sitecustomize path to path list pathlist = [] scpath = osp.dirname(osp.abspath(__file__)) pathlist.append(scpath) # Adding Spyder path pathlist += self.path # Adding path list to PYTHONPATH environment variable add_pathlist_to_PYTHONPATH(env, pathlist) #-------------------------Python specific------------------------------- self.connect(self.process, SIGNAL("readyReadStandardOutput()"), self.write_output) self.connect(self.process, SIGNAL("readyReadStandardError()"), self.write_error) self.connect(self.process, SIGNAL("finished(int,QProcess::ExitStatus)"), self.finished) self.connect(self, SIGNAL('finished()'), self.dialog_manager.close_all) self.connect(self.terminate_button, SIGNAL("clicked()"), self.process.terminate) self.connect(self.kill_button, SIGNAL("clicked()"), self.process.kill) #-------------------------Python specific------------------------------- # Fixes for our Mac app: # 1. PYTHONPATH and PYTHONHOME are set while bootstrapping the app, # but their values are messing sys.path for external interpreters # (e.g. EPD) so we need to remove them from the environment. # 2. Set PYTHONPATH again but without grabbing entries defined in the # environment (Fixes Issue 1321) # 3. Remove PYTHONOPTIMIZE from env so that we can have assert # statements working with our interpreters (See Issue 1281) if running_in_mac_app(): env.append('SPYDER_INTERPRETER=%s' % self.pythonexecutable) if MAC_APP_NAME not in self.pythonexecutable: env = [p for p in env if not (p.startswith('PYTHONPATH') or \ p.startswith('PYTHONHOME'))] # 1. add_pathlist_to_PYTHONPATH(env, pathlist, drop_env=True) # 2. env = [p for p in env if not p.startswith('PYTHONOPTIMIZE')] # 3. self.process.setEnvironment(env) self.process.start(self.pythonexecutable, p_args)<|fim▁hole|> running = self.process.waitForStarted(3000) self.set_running_state(running) if not running: if self.is_ipykernel: self.emit(SIGNAL("ipython_kernel_start_error(QString)"), _("The kernel failed to start!! That's all we know... " "Please close this console and open a new one.")) else: QMessageBox.critical(self, _("Error"), _("A Python console failed to start!")) else: self.shell.setFocus() self.emit(SIGNAL('started()')) return self.process def finished(self, exit_code, exit_status): """Reimplement ExternalShellBase method""" if self.is_ipykernel and exit_code == 1: self.emit(SIGNAL("ipython_kernel_start_error(QString)"), self.shell.get_text_with_eol()) ExternalShellBase.finished(self, exit_code, exit_status) self.introspection_socket = None #=============================================================================== # Input/Output #=============================================================================== def write_error(self): if os.name == 'nt': #---This is apparently necessary only on Windows (not sure though): # emptying standard output buffer before writing error output self.process.setReadChannel(QProcess.StandardOutput) if self.process.waitForReadyRead(1): self.write_output() self.shell.write_error(self.get_stderr()) QApplication.processEvents() def send_to_process(self, text): if not self.is_running(): return if not is_text_string(text): text = to_text_string(text) if self.mpl_backend == 'Qt4Agg' and os.name == 'nt' and \ self.introspection_socket is not None: communicate(self.introspection_socket, "toggle_inputhook_flag(True)") # # Socket-based alternative (see input hook in sitecustomize.py): # while self.local_server.hasPendingConnections(): # self.local_server.nextPendingConnection().write('go!') if any([text == cmd for cmd in ['%ls', '%pwd', '%scientific']]) or \ any([text.startswith(cmd) for cmd in ['%cd ', '%clear ']]): text = 'evalsc(r"%s")\n' % text if not text.endswith('\n'): text += '\n' self.process.write(to_binary_string(text, 'utf8')) self.process.waitForBytesWritten(-1) # Eventually write prompt faster (when hitting Enter continuously) # -- necessary/working on Windows only: if os.name == 'nt': self.write_error() def keyboard_interrupt(self): if self.introspection_socket is not None: communicate(self.introspection_socket, "thread.interrupt_main()") def quit_monitor(self): if self.introspection_socket is not None: try: write_packet(self.introspection_socket, "thread.exit()") except socket.error: pass #=============================================================================== # Globals explorer #=============================================================================== def toggle_globals_explorer(self, state): if self.stand_alone is not None: self.splitter.setSizes([1, 1 if state else 0]) self.namespacebrowser_button.setChecked(state) if state and self.namespacebrowser is not None: self.namespacebrowser.refresh_table() def splitter_moved(self, pos, index): self.namespacebrowser_button.setChecked( self.splitter.sizes()[1] ) #=============================================================================== # Misc. #=============================================================================== def set_current_working_directory(self): """Set current working directory""" cwd = self.shell.get_cwd() self.emit(SIGNAL('redirect_stdio(bool)'), False) directory = getexistingdirectory(self, _("Select directory"), cwd) if directory: self.shell.set_cwd(directory) self.emit(SIGNAL('redirect_stdio(bool)'), True) def show_env(self): """Show environment variables""" get_func = self.shell.get_env set_func = self.shell.set_env self.dialog_manager.show(RemoteEnvDialog(get_func, set_func)) def show_syspath(self): """Show sys.path contents""" editor = DictEditor() editor.setup(self.shell.get_syspath(), title="sys.path", readonly=True, width=600, icon='syspath.png') self.dialog_manager.show(editor)<|fim▁end|>
#-------------------------Python specific-------------------------------
<|file_name|>tx.py<|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. # from qpid.client import Client, Closed from qpid.queue import Empty from qpid.content import Content from qpid.testlib import TestBase class TxTests(TestBase): """ Tests for 'methods' on the amqp tx 'class' """ def test_commit(self): """ Test that commited publishes are delivered and commited acks are not re-delivered """ channel = self.channel queue_a, queue_b, queue_c = self.perform_txn_work(channel, "tx-commit-a", "tx-commit-b", "tx-commit-c") channel.tx_commit() #check results for i in range(1, 5): msg = queue_c.get(timeout=self.recv_timeout()) self.assertEqual("TxMessage %d" % i, msg.content.body) msg = queue_b.get(timeout=self.recv_timeout()) self.assertEqual("TxMessage 6", msg.content.body) msg = queue_a.get(timeout=self.recv_timeout()) self.assertEqual("TxMessage 7", msg.content.body) for q in [queue_a, queue_b, queue_c]:<|fim▁hole|> try: extra = q.get(timeout=self.recv_timeout_negative()) self.fail("Got unexpected message: " + extra.content.body) except Empty: None #cleanup channel.basic_ack(delivery_tag=0, multiple=True) channel.tx_commit() def test_auto_rollback(self): """ Test that a channel closed with an open transaction is effectively rolled back """ channel = self.channel queue_a, queue_b, queue_c = self.perform_txn_work(channel, "tx-autorollback-a", "tx-autorollback-b", "tx-autorollback-c") for q in [queue_a, queue_b, queue_c]: try: extra = q.get(timeout=self.recv_timeout_negative()) self.fail("Got unexpected message: " + extra.content.body) except Empty: None channel.tx_rollback() #check results for i in range(1, 5): msg = queue_a.get(timeout=self.recv_timeout()) self.assertEqual("Message %d" % i, msg.content.body) msg = queue_b.get(timeout=self.recv_timeout()) self.assertEqual("Message 6", msg.content.body) msg = queue_c.get(timeout=self.recv_timeout()) self.assertEqual("Message 7", msg.content.body) for q in [queue_a, queue_b, queue_c]: try: extra = q.get(timeout=self.recv_timeout_negative()) self.fail("Got unexpected message: " + extra.content.body) except Empty: None #cleanup channel.basic_ack(delivery_tag=0, multiple=True) channel.tx_commit() def test_rollback(self): """ Test that rolled back publishes are not delivered and rolled back acks are re-delivered """ channel = self.channel queue_a, queue_b, queue_c = self.perform_txn_work(channel, "tx-rollback-a", "tx-rollback-b", "tx-rollback-c") for q in [queue_a, queue_b, queue_c]: try: extra = q.get(timeout=self.recv_timeout_negative()) self.fail("Got unexpected message: " + extra.content.body) except Empty: None channel.tx_rollback() #check results for i in range(1, 5): msg = queue_a.get(timeout=self.recv_timeout()) self.assertEqual("Message %d" % i, msg.content.body) msg = queue_b.get(timeout=self.recv_timeout()) self.assertEqual("Message 6", msg.content.body) msg = queue_c.get(timeout=self.recv_timeout()) self.assertEqual("Message 7", msg.content.body) for q in [queue_a, queue_b, queue_c]: try: extra = q.get(timeout=self.recv_timeout_negative()) self.fail("Got unexpected message: " + extra.content.body) except Empty: None #cleanup channel.basic_ack(delivery_tag=0, multiple=True) channel.tx_commit() def perform_txn_work(self, channel, name_a, name_b, name_c): """ Utility method that does some setup and some work under a transaction. Used for testing both commit and rollback """ #setup: channel.queue_declare(queue=name_a, exclusive=True) channel.queue_declare(queue=name_b, exclusive=True) channel.queue_declare(queue=name_c, exclusive=True) key = "my_key_" + name_b topic = "my_topic_" + name_c channel.queue_bind(queue=name_b, exchange="amq.direct", routing_key=key) channel.queue_bind(queue=name_c, exchange="amq.topic", routing_key=topic) for i in range(1, 5): channel.basic_publish(routing_key=name_a, content=Content("Message %d" % i)) channel.basic_publish(routing_key=key, exchange="amq.direct", content=Content("Message 6")) channel.basic_publish(routing_key=topic, exchange="amq.topic", content=Content("Message 7")) channel.tx_select() #consume and ack messages sub_a = channel.basic_consume(queue=name_a, no_ack=False) queue_a = self.client.queue(sub_a.consumer_tag) for i in range(1, 5): msg = queue_a.get(timeout=self.recv_timeout()) self.assertEqual("Message %d" % i, msg.content.body) channel.basic_ack(delivery_tag=msg.delivery_tag, multiple=True) sub_b = channel.basic_consume(queue=name_b, no_ack=False) queue_b = self.client.queue(sub_b.consumer_tag) msg = queue_b.get(timeout=self.recv_timeout()) self.assertEqual("Message 6", msg.content.body) channel.basic_ack(delivery_tag=msg.delivery_tag) sub_c = channel.basic_consume(queue=name_c, no_ack=False) queue_c = self.client.queue(sub_c.consumer_tag) msg = queue_c.get(timeout=self.recv_timeout()) self.assertEqual("Message 7", msg.content.body) channel.basic_ack(delivery_tag=msg.delivery_tag) #publish messages for i in range(1, 5): channel.basic_publish(routing_key=topic, exchange="amq.topic", content=Content("TxMessage %d" % i)) channel.basic_publish(routing_key=key, exchange="amq.direct", content=Content("TxMessage 6")) channel.basic_publish(routing_key=name_a, content=Content("TxMessage 7")) return queue_a, queue_b, queue_c def test_commit_overlapping_acks(self): """ Test that logically 'overlapping' acks do not cause errors on commit """ channel = self.channel channel.queue_declare(queue="commit-overlapping", exclusive=True) for i in range(1, 10): channel.basic_publish(routing_key="commit-overlapping", content=Content("Message %d" % i)) channel.tx_select() sub = channel.basic_consume(queue="commit-overlapping", no_ack=False) queue = self.client.queue(sub.consumer_tag) for i in range(1, 10): msg = queue.get(timeout=self.recv_timeout()) self.assertEqual("Message %d" % i, msg.content.body) if i in [3, 6, 10]: channel.basic_ack(delivery_tag=msg.delivery_tag) channel.tx_commit() #check all have been acked: try: extra = queue.get(timeout=self.recv_timeout_negative()) self.fail("Got unexpected message: " + extra.content.body) except Empty: None<|fim▁end|>
<|file_name|>test_edgeql_casts.py<|end_file_name|><|fim▁begin|># # This source file is part of the EdgeDB open source project. # # Copyright 2018-present MagicStack Inc. and the EdgeDB authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import itertools import os.path import edgedb from edb.testbase import server as tb class TestEdgeQLCasts(tb.QueryTestCase): '''Testing symmetry and validity of casts. Scalar casting is symmetric in the sense that if casting scalar type X into Y is valid then it is also valid to cast Y into X. Some casts are lossless. A cast from X into Y is lossless if all the relevant details of the value of type X can be unambiguously represented by a value of type Y. Examples of lossless casts: - any scalar can be losslessly cast into a str - int16 and int32 can be losslessly cast into int64 - int16 can be losslessly cast into float32 - any numeric type can be losslessly cast into a decimal Sometimes only specific values (a subset of the entire domain of the scalar) can be cast losslessly: - 2147299968 can be cast losslessly into a float32, but not 2147299969 - decimal 2.5 can be cast losslessly into a float32, but not decimal 2.5000000001 Consider two types X and Y with corresponding values x and y. If x can be losslessly cast into Y, then casting it back is also lossless: x = <X><Y>x ''' # FIXME: a special schema should be used here since we need to # cover all known scalars and even some arrays and tuples. SCHEMA = os.path.join(os.path.dirname(__file__), 'schemas', 'casts.esdl') SETUP = os.path.join(os.path.dirname(__file__), 'schemas', 'casts_setup.edgeql') # NOTE: nothing can be cast into bytes async def test_edgeql_casts_bytes_01(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r'cannot cast'): await self.con.execute(""" SELECT <bytes>True; """) async def test_edgeql_casts_bytes_02(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r'cannot cast'): await self.con.execute(""" SELECT <bytes>uuid_generate_v1mc(); """) async def test_edgeql_casts_bytes_03(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r'cannot cast'): await self.con.execute(""" SELECT <bytes>'Hello'; """) async def test_edgeql_casts_bytes_04(self): async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'expected JSON string or null'): await self.con.query_single("""SELECT <bytes>to_json('1');"""), self.assertEqual( await self.con.query_single(r''' SELECT <bytes>to_json('"aGVsbG8="'); '''), b'hello', ) async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid symbol'): await self.con.query_single(""" SELECT <bytes>to_json('"not base64!"'); """) async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid base64 end sequence'): await self.con.query_single(""" SELECT <bytes>to_json('"a"'); """) async def test_edgeql_casts_bytes_05(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r'cannot cast'): await self.con.execute(""" SELECT <bytes>datetime_current(); """) async def test_edgeql_casts_bytes_06(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r'cannot cast'): await self.con.execute(""" SELECT <bytes>cal::to_local_datetime('2018-05-07T20:01:22.306916'); """) async def test_edgeql_casts_bytes_07(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r'cannot cast'): await self.con.execute(""" SELECT <bytes>cal::to_local_date('2018-05-07'); """) async def test_edgeql_casts_bytes_08(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r'cannot cast'): await self.con.execute(""" SELECT <bytes>cal::to_local_time('20:01:22.306916'); """) async def test_edgeql_casts_bytes_09(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r'cannot cast'): await self.con.execute(""" SELECT <bytes>to_duration(hours:=20); """) async def test_edgeql_casts_bytes_10(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r'cannot cast'): await self.con.execute(""" SELECT <bytes>to_int16('2'); """) async def test_edgeql_casts_bytes_11(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r'cannot cast'): await self.con.execute(""" SELECT <bytes>to_int32('2'); """) async def test_edgeql_casts_bytes_12(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r'cannot cast'): await self.con.execute(""" SELECT <bytes>to_int64('2'); """) async def test_edgeql_casts_bytes_13(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r'cannot cast'): await self.con.execute(""" SELECT <bytes>to_float32('2'); """) async def test_edgeql_casts_bytes_14(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r'cannot cast'): await self.con.execute(""" SELECT <bytes>to_float64('2'); """) async def test_edgeql_casts_bytes_15(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r'cannot cast'): await self.con.execute(""" SELECT <bytes>to_decimal('2'); """) async def test_edgeql_casts_bytes_16(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r'cannot cast'): await self.con.execute(""" SELECT <bytes>to_bigint('2'); """) # NOTE: casts are idempotent async def test_edgeql_casts_idempotence_01(self): await self.assert_query_result( r'''SELECT <bool><bool>True IS bool;''', [True], ) await self.assert_query_result( r'''SELECT <bytes><bytes>b'Hello' IS bytes;''', [True], ) await self.assert_query_result( r'''SELECT <str><str>'Hello' IS str;''', [True], ) await self.assert_query_result( r'''SELECT <json><json>to_json('1') IS json;''', [True], ) await self.assert_query_result( r'''SELECT <uuid><uuid>uuid_generate_v1mc() IS uuid;''', [True], ) await self.assert_query_result( r'''SELECT <datetime><datetime>datetime_current() IS datetime;''', [True], ) await self.assert_query_result( r''' SELECT <cal::local_datetime><cal::local_datetime> cal::to_local_datetime( '2018-05-07T20:01:22.306916') IS cal::local_datetime; ''', [True], ) await self.assert_query_result( r''' SELECT <cal::local_date><cal::local_date>cal::to_local_date( '2018-05-07') IS cal::local_date; ''', [True], ) await self.assert_query_result( r''' SELECT <cal::local_time><cal::local_time>cal::to_local_time( '20:01:22.306916') IS cal::local_time; ''', [True], ) await self.assert_query_result( r''' SELECT <duration><duration>to_duration( hours:=20) IS duration; ''', [True], ) await self.assert_query_result( r'''SELECT <int16><int16>to_int16('12345') IS int16;''', [True], ) await self.assert_query_result( r'''SELECT <int32><int32>to_int32('1234567890') IS int32;''', [True], ) await self.assert_query_result( r'''SELECT <int64><int64>to_int64('1234567890123') IS int64;''', [True], ) await self.assert_query_result( r'''SELECT <float32><float32>to_float32('2.5') IS float32;''', [True], ) await self.assert_query_result( r'''SELECT <float64><float64>to_float64('2.5') IS float64;''', [True], ) await self.assert_query_result( r''' SELECT <bigint><bigint>to_bigint( '123456789123456789123456789') IS bigint; ''', [True], ) await self.assert_query_result( r''' SELECT <decimal><decimal>to_decimal( '123456789123456789123456789.123456789123456789123456789') IS decimal; ''', [True], ) async def test_edgeql_casts_idempotence_02(self): await self.assert_query_result( r'''SELECT <bool><bool>True = True;''', [True], ) await self.assert_query_result( r'''SELECT <bytes><bytes>b'Hello' = b'Hello';''', [True], ) await self.assert_query_result( r'''SELECT <str><str>'Hello' = 'Hello';''', [True], ) await self.assert_query_result( r'''SELECT <json><json>to_json('1') = to_json('1');''', [True], ) await self.assert_query_result( r''' WITH U := uuid_generate_v1mc() SELECT <uuid><uuid>U = U; ''', [True], ) await self.assert_query_result( r''' SELECT <datetime><datetime>datetime_of_statement() = datetime_of_statement(); ''', [True], ) await self.assert_query_result( r''' SELECT <cal::local_datetime><cal::local_datetime> cal::to_local_datetime('2018-05-07T20:01:22.306916') = cal::to_local_datetime('2018-05-07T20:01:22.306916'); ''', [True], ) await self.assert_query_result( r''' SELECT <cal::local_date><cal::local_date> cal::to_local_date('2018-05-07') = cal::to_local_date('2018-05-07'); ''', [True], ) await self.assert_query_result( r''' SELECT <cal::local_time><cal::local_time>cal::to_local_time( '20:01:22.306916') = cal::to_local_time('20:01:22.306916'); ''', [True], ) await self.assert_query_result( r''' SELECT <duration><duration>to_duration(hours:=20) = to_duration(hours:=20); ''', [True], ) await self.assert_query_result( r'''SELECT <int16><int16>to_int16('12345') = 12345;''', [True], ) await self.assert_query_result( r'''SELECT <int32><int32>to_int32('1234567890') = 1234567890;''', [True], ) await self.assert_query_result( r''' SELECT <int64><int64>to_int64('1234567890123') = 1234567890123; ''', [True], ) await self.assert_query_result( r'''SELECT <float32><float32>to_float32('2.5') = 2.5;''', [True], ) await self.assert_query_result( r'''SELECT <float64><float64>to_float64('2.5') = 2.5;''', [True], ) await self.assert_query_result( r''' SELECT <bigint><bigint>to_bigint( '123456789123456789123456789') = to_bigint( '123456789123456789123456789'); ''', [True], ) await self.assert_query_result( r''' SELECT <decimal><decimal>to_decimal( '123456789123456789123456789.123456789123456789123456789') = to_decimal( '123456789123456789123456789.123456789123456789123456789'); ''', [True], ) async def test_edgeql_casts_str_01(self): # Casting to str and back is lossless for every scalar (if # legal). It's still not legal to cast bytes into str or some # of the json values. await self.assert_query_result( r'''SELECT <bool><str>True = True;''', [True], ) await self.assert_query_result( r'''SELECT <bool><str>False = False;''', [True], # only JSON strings can be cast into EdgeQL str ) await self.assert_query_result( r'''SELECT <json><str>to_json('"Hello"') = to_json('"Hello"');''', [True], ) await self.assert_query_result( r''' WITH U := uuid_generate_v1mc() SELECT <uuid><str>U = U; ''', [True], ) await self.assert_query_result( r''' SELECT <datetime><str>datetime_of_statement() = datetime_of_statement(); ''', [True], ) await self.assert_query_result( r''' SELECT <cal::local_datetime><str>cal::to_local_datetime( '2018-05-07T20:01:22.306916') = cal::to_local_datetime('2018-05-07T20:01:22.306916'); ''', [True], ) await self.assert_query_result( r''' SELECT <cal::local_date><str>cal::to_local_date('2018-05-07') = cal::to_local_date('2018-05-07'); ''', [True], ) await self.assert_query_result( r''' SELECT <cal::local_time><str> cal::to_local_time('20:01:22.306916') = cal::to_local_time('20:01:22.306916'); ''', [True], ) await self.assert_query_result( r''' SELECT <duration><str>to_duration(hours:=20) = to_duration(hours:=20); ''', [True], ) await self.assert_query_result( r'''SELECT <int16><str>to_int16('12345') = 12345;''', [True], ) await self.assert_query_result( r'''SELECT <int32><str>to_int32('1234567890') = 1234567890;''', [True], ) await self.assert_query_result( r''' SELECT <int64><str>to_int64( '1234567890123') = 1234567890123; ''', [True], ) await self.assert_query_result( r'''SELECT <float32><str>to_float32('2.5') = 2.5;''', [True], ) await self.assert_query_result( r'''SELECT <float64><str>to_float64('2.5') = 2.5;''', [True], ) await self.assert_query_result( r''' SELECT <bigint><str>to_bigint( '123456789123456789123456789') = to_bigint( '123456789123456789123456789'); ''', [True], ) await self.assert_query_result( r''' SELECT <decimal><str>to_decimal( '123456789123456789123456789.123456789123456789123456789') = to_decimal( '123456789123456789123456789.123456789123456789123456789'); ''', [True], ) async def test_edgeql_casts_str_02(self): # Certain strings can be cast into other types losslessly, # making them "canonical" string representations of those # values. await self.assert_query_result( r''' WITH x := {'true', 'false'} SELECT <str><bool>x = x; ''', [True, True], ) await self.assert_query_result( r''' WITH x := {'True', 'False', 'TRUE', 'FALSE', ' TrUe '} SELECT <str><bool>x = x; ''', [False, False, False, False, False], ) await self.assert_query_result( r''' WITH x := {'True', 'False', 'TRUE', 'FALSE', 'TrUe'} SELECT <str><bool>x = str_lower(x); ''', [True, True, True, True, True], ) for variant in {'😈', 'yes', '1', 'no', 'on', 'OFF', 't', 'f', 'tr', 'fa'}: async with self.assertRaisesRegexTx( edgedb.InvalidValueError, fr"invalid syntax for std::bool: '{variant}'"): await self.con.query_single(f'SELECT <bool>"{variant}"') self.assertTrue( await self.con.query_single('SELECT <bool>" TruE "')) self.assertFalse( await self.con.query_single('SELECT <bool>" FalsE "')) async def test_edgeql_casts_str_03(self): # str to json is always lossless await self.assert_query_result( r''' WITH x := {'any', 'arbitrary', '♠gibberish♠'} SELECT <str><json>x = x; ''', [True, True, True], ) async def test_edgeql_casts_str_04(self): # canonical uuid representation as a string is using lowercase await self.assert_query_result( r''' WITH x := 'd4288330-eea3-11e8-bc5f-7faf132b1d84' SELECT <str><uuid>x = x; ''', [True], ) await self.assert_query_result( # non-canonical r''' WITH x := { 'D4288330-EEA3-11E8-BC5F-7FAF132B1D84', 'D4288330-Eea3-11E8-Bc5F-7Faf132B1D84', 'D4288330-eea3-11e8-bc5f-7faf132b1d84', } SELECT <str><uuid>x = x; ''', [False, False, False], ) await self.assert_query_result( r''' WITH x := { 'D4288330-EEA3-11E8-BC5F-7FAF132B1D84', 'D4288330-Eea3-11E8-Bc5F-7Faf132B1D84', 'D4288330-eea3-11e8-bc5f-7faf132b1d84', } SELECT <str><uuid>x = str_lower(x); ''', [True, True, True], ) async def test_edgeql_casts_str_05(self): # Canonical date and time str representations must follow ISO # 8601. This test assumes that the server is configured to be # in UTC time zone. await self.assert_query_result( r''' WITH x := '2018-05-07T20:01:22.306916+00:00' SELECT <str><datetime>x = x; ''', [True], ) await self.assert_query_result( # validating that these are all in fact the same datetime r''' WITH x := { '2018-05-07T15:01:22.306916-05:00', '2018-05-07T15:01:22.306916-05', '2018-05-07T20:01:22.306916Z', '2018-05-07T20:01:22.306916+0000', '2018-05-07T20:01:22.306916+00', # the '-' and ':' separators may be omitted '20180507T200122.306916+00', # acceptable RFC 3339 '2018-05-07 20:01:22.306916+00:00', '2018-05-07t20:01:22.306916z', } SELECT <datetime>x = <datetime>'2018-05-07T20:01:22.306916+00:00'; ''', [True, True, True, True, True, True, True, True], ) async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax'): await self.con.query_single( 'SELECT <datetime>"2018-05-07;20:01:22.306916+00:00"') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax'): await self.con.query_single( 'SELECT <datetime>"2018-05-07T20:01:22.306916"') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax'): await self.con.query_single( 'SELECT <datetime>"2018-05-07T20:01:22.306916 1000"') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax'): await self.con.query_single( 'SELECT <datetime>"2018-05-07T20:01:22.306916 US/Central"') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax'): await self.con.query_single( 'SELECT <datetime>"2018-05-07T20:01:22.306916 +GMT1"') async def test_edgeql_casts_str_06(self): # Canonical date and time str representations must follow ISO # 8601. This test assumes that the server is configured to be # in UTC time zone. await self.assert_query_result( r''' WITH x := '2018-05-07T20:01:22.306916' SELECT <str><cal::local_datetime>x = x; ''', [True], ) await self.assert_query_result( # validating that these are all in fact the same datetime r''' WITH x := { # the '-' and ':' separators may be omitted '20180507T200122.306916', # acceptable RFC 3339 '2018-05-07 20:01:22.306916', '2018-05-07t20:01:22.306916', } SELECT <cal::local_datetime>x = <cal::local_datetime>'2018-05-07T20:01:22.306916'; ''', [True, True, True], ) async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( 'SELECT <cal::local_datetime>"2018-05-07;20:01:22.306916"') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( ''' SELECT <cal::local_datetime>"2018-05-07T20:01:22.306916+01:00" ''') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( 'SELECT <cal::local_datetime>"2018-05-07T20:01:22.306916 GMT"') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( ''' SELECT <cal::local_datetime>"2018-05-07T20:01:22.306916 GMT0" ''') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( '''SELECT <cal::local_datetime> "2018-05-07T20:01:22.306916 US/Central" ''') async def test_edgeql_casts_str_07(self): # Canonical date and time str representations must follow ISO # 8601. await self.assert_query_result( r''' WITH x := '2018-05-07' SELECT <str><cal::local_date>x = x; ''', [True], ) await self.assert_query_result( # validating that these are all in fact the same date r''' WITH x := { # the '-' separators may be omitted '20180507', } SELECT <cal::local_date>x = <cal::local_date>'2018-05-07'; ''', [True], ) async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( 'SELECT <cal::local_date>"2018-05-07T20:01:22.306916"') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( 'SELECT <cal::local_date>"2018/05/07"') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( 'SELECT <cal::local_date>"2018.05.07"') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( 'SELECT <cal::local_date>"2018-05-07+01:00"') async def test_edgeql_casts_str_08(self): # Canonical date and time str representations must follow ISO # 8601. await self.assert_query_result( r''' WITH x := '20:01:22.306916' SELECT <str><cal::local_time>x = x; ''', [True], ) await self.assert_query_result( r''' WITH x := { '20:01', '20:01:00', # the ':' separators may be omitted '2001', '200100', } SELECT <cal::local_time>x = <cal::local_time>'20:01:00'; ''', [True, True, True, True], ) async with self.assertRaisesRegexTx( edgedb.InvalidValueError, 'invalid input syntax for type cal::local_time'): await self.con.query_single( "SELECT <cal::local_time>'2018-05-07 20:01:22'") async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( 'SELECT <cal::local_time>"20:01:22.306916+01:00"') async def test_edgeql_casts_str_09(self): # Canonical duration await self.assert_query_result( r''' WITH x := 'PT20H1M22.306916S' SELECT <str><duration>x = x; ''', [True], ) await self.assert_query_result( # non-canonical r''' WITH x := { '20:01:22.306916', '20h 1m 22.306916s', '20 hours 1 minute 22.306916 seconds', '72082.306916', # the duration in seconds '0.834285959675926 days', } SELECT <str><duration>x = x; ''', [False, False, False, False, False], ) await self.assert_query_result( # validating that these are all in fact the same duration r''' WITH x := { '20:01:22.306916', '20h 1m 22.306916s', '20 hours 1 minute 22.306916 seconds', '72082.306916', # the duration in seconds '0.834285959675926 days', } SELECT <duration>x = <duration>'PT20H1M22.306916S'; ''', [True, True, True, True, True], ) async def test_edgeql_casts_str_10(self): # valid casts from str to any integer is lossless, as long as # there's no whitespace, which is trimmed await self.assert_query_result( r''' WITH x := {'-20', '0', '7', '12345'} SELECT <str><int16>x = x; ''', [True, True, True, True], ) await self.assert_query_result( r''' WITH x := {'-20', '0', '7', '12345'} SELECT <str><int32>x = x; ''', [True, True, True, True], ) await self.assert_query_result( r''' WITH x := {'-20', '0', '7', '12345'} SELECT <str><int64>x = x; ''', [True, True, True, True], ) await self.assert_query_result( # with whitespace r''' WITH x := { ' 42', '42 ', ' 42 ', } SELECT <str><int16>x = x; ''', [False, False, False], ) await self.assert_query_result( # validating that these are all in fact the same value r''' WITH x := { ' 42', '42 ', ' 42 ', } SELECT <int16>x = 42; ''', [True, True, True], ) async def test_edgeql_casts_str_11(self): # There's too many ways of representing floats. Outside of # trivial 1-2 digit cases, relying on any str being # "canonical" is not safe, making most casts from str to float # lossy. await self.assert_query_result( r''' WITH x := {'-20', '0', '7.2'} SELECT <str><float32>x = x; ''', [True, True, True], ) await self.assert_query_result( r''' WITH x := {'-20', '0', '7.2'} SELECT <str><float64>x = x; ''', [True, True, True], ) await self.assert_query_result( # non-canonical r''' WITH x := { '0.0000000001234', '1234E-13', '0.1234e-9', } SELECT <str><float32>x = x; ''', [False, False, False], ) await self.assert_query_result( r''' WITH x := { '0.0000000001234', '1234E-13', '0.1234e-9', } SELECT <str><float64>x = x; ''', [False, False, False], ) await self.assert_query_result( # validating that these are all in fact the same value r''' WITH x := { '0.0000000001234', '1234E-13', '0.1234e-9', } SELECT <float64>x = 1234e-13; ''', [True, True, True], ) async def test_edgeql_casts_str_12(self): # The canonical string representation of decimals is without # use of scientific notation. await self.assert_query_result( r''' WITH x := { '-20', '0', '7.2', '0.0000000001234', '1234.00000001234' } SELECT <str><decimal>x = x; ''', [True, True, True, True, True], ) await self.assert_query_result( # non-canonical r''' WITH x := { '1234E-13', '0.1234e-9', } SELECT <str><decimal>x = x; ''', [False, False], ) await self.assert_query_result( # validating that these are all in fact the same date r''' WITH x := { '1234E-13', '0.1234e-9', } SELECT <decimal>x = <decimal>'0.0000000001234'; ''', [True, True], ) async def test_edgeql_casts_str_13(self): # Casting to str and back is lossless for every scalar (if # legal). It's still not legal to cast bytes into str or some # of the json values. await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <uuid><str>T.id = T.id; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <bool><str>T.p_bool = T.p_bool; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <str><str>T.p_str = T.p_str; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <datetime><str>T.p_datetime = T.p_datetime; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <cal::local_datetime><str>T.p_local_datetime = T.p_local_datetime; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <cal::local_date><str>T.p_local_date = T.p_local_date; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <cal::local_time><str>T.p_local_time = T.p_local_time; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <duration><str>T.p_duration = T.p_duration; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <int16><str>T.p_int16 = T.p_int16; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <int32><str>T.p_int32 = T.p_int32; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <int64><str>T.p_int64 = T.p_int64; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <float32><str>T.p_float32 = T.p_float32; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <float64><str>T.p_float64 = T.p_float64; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <bigint><str>T.p_bigint = T.p_bigint; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <decimal><str>T.p_decimal = T.p_decimal; ''', [True], ) async def test_edgeql_casts_numeric_01(self): # Casting to decimal and back should be lossless for any other # integer type. for numtype in {'bigint', 'decimal'}: await self.assert_query_result( # technically we're already casting a literal int64 # to int16 first f''' WITH x := <int16>{{-32768, -32767, -100, 0, 13, 32766, 32767}} SELECT <int16><{numtype}>x = x; ''', [True, True, True, True, True, True, True], ) await self.assert_query_result( # technically we're already casting a literal int64 # to int32 first f''' WITH x := <int32>{{-2147483648, -2147483647, -65536, -100, 0, 13, 32768, 2147483646, 2147483647}} SELECT <int32><{numtype}>x = x; ''', [True, True, True, True, True, True, True, True, True], ) await self.assert_query_result( f''' WITH x := <int64>{{ -9223372036854775808, -9223372036854775807, -4294967296, -65536, -100, 0, 13, 65536, 4294967296, 9223372036854775806, 9223372036854775807 }} SELECT <int64><{numtype}>x = x; ''', [True, True, True, True, True, True, True, True, True, True, True], ) async def test_edgeql_casts_numeric_02(self): # Casting to decimal and back should be lossless for any other # float type of low precision (a couple of digits less than # the maximum possible float precision). await self.assert_query_result( # technically we're already casting a literal int64 or # float64 to float32 first r''' WITH x := <float32>{-3.31234e+38, -1.234e+12, -1.234e-12, -100, 0, 13, 1.234e-12, 1.234e+12, 3.4e+38} SELECT <float32><decimal>x = x; ''', [True, True, True, True, True, True, True, True, True], ) await self.assert_query_result( r''' WITH x := <float64>{-1.61234e+308, -1.234e+42, -1.234e-42, -100, 0, 13, 1.234e-42, 1.234e+42, 1.7e+308} SELECT <float64><decimal>x = x; ''', [True, True, True, True, True, True, True, True, True], ) async def test_edgeql_casts_numeric_03(self): # It is especially dangerous to cast an int32 into float32 and # back because float32 cannot losslessly represent the entire # range of int32, but it can represent some of it, so no # obvious errors would be raised (as any int32 value is # technically withing valid range of float32), but the value # could be mangled. await self.assert_query_result( # ints <= 2^24 can be represented exactly in a float32 r''' WITH x := <int32>{16777216, 16777215, 16777214, 1677721, 167772, 16777} SELECT <int32><float32>x = x; ''', [True, True, True, True, True, True], ) await self.assert_query_result( # max int32 -100, -1000 r''' WITH x := <int32>{2147483548, 2147482648} SELECT <int32><float32>x = x; ''', [False, False], ) await self.assert_query_result( r''' WITH x := <int32>{2147483548, 2147482648} SELECT <int32><float32>x; ''', [2147483520, 2147482624], ) async def test_edgeql_casts_numeric_04(self): await self.assert_query_result( # ints <= 2^24 can be represented exactly in a float32 r''' WITH x := <int32>{16777216, 16777215, 16777214, 1677721, 167772, 16777} SELECT <int32><float64>x = x; ''', [True, True, True, True, True, True], ) await self.assert_query_result( # max int32 -1, -2, -3, -10, -100, -1000 r''' WITH x := <int32>{2147483647, 2147483646, 2147483645, 2147483638, 2147483548, 2147482648} SELECT <int32><float64>x = x; ''', [True, True, True, True, True, True], ) async def test_edgeql_casts_numeric_05(self): # Due to the sparseness of float values large integers may not # be representable exactly if they require better precision # than float provides. await self.assert_query_result( r''' # 2^31 -1, -2, -3, -10 WITH x := <int32>{2147483647, 2147483646, 2147483645, 2147483638} # 2147483647 is the max int32 SELECT x <= <int32>2147483647; ''', [True, True, True, True], ) async with self.assertRaisesRegexTx( edgedb.NumericOutOfRangeError, r"std::int32 out of range"): async with self.con.transaction(): await self.con.execute(""" SELECT <int32><float32><int32>2147483647; """) async with self.assertRaisesRegexTx( edgedb.NumericOutOfRangeError, r"std::int32 out of range"): async with self.con.transaction(): await self.con.execute(""" SELECT <int32><float32><int32>2147483646; """) async with self.assertRaisesRegexTx( edgedb.NumericOutOfRangeError, r"std::int32 out of range"): async with self.con.transaction(): await self.con.execute(""" SELECT <int32><float32><int32>2147483645; """) async with self.assertRaisesRegexTx( edgedb.NumericOutOfRangeError, r"std::int32 out of range"): async with self.con.transaction(): await self.con.execute(""" SELECT <int32><float32><int32>2147483638; """) async def test_edgeql_casts_numeric_06(self): await self.assert_query_result( r'''SELECT <int16>1;''', [1], ) await self.assert_query_result( r'''SELECT <int32>1;''', [1], ) await self.assert_query_result( r'''SELECT <int64>1;''', [1], ) await self.assert_query_result( r'''SELECT <float32>1;''', [1.0], ) await self.assert_query_result( r'''SELECT <float64>1;''', [1.0], ) await self.assert_query_result( r'''SELECT <bigint>1;''', [1], ) await self.assert_query_result( r'''SELECT <decimal>1;''', [1], ) async def test_edgeql_casts_numeric_07(self): numerics = ['int16', 'int32', 'int64', 'float32', 'float64', 'bigint', 'decimal'] for t1, t2 in itertools.product(numerics, numerics): await self.assert_query_result( f''' SELECT <{t1}><{t2}>1; ''', [1], ) async def test_edgeql_casts_collections_01(self): await self.assert_query_result( r'''SELECT <array<str>>[1, 2, 3];''', [['1', '2', '3']], ) await self.assert_query_result( r'''WITH X := [1, 2, 3] SELECT <array<str>> X;''', [['1', '2', '3']], ) await self.assert_query_result( r'''SELECT <tuple<str, float64>> (1, '2');''', [['1', 2.0]], ) await self.assert_query_result( r'''WITH X := (1, '2') SELECT <tuple<str, float64>> X;''', [['1', 2.0]], ) await self.assert_query_result( r'''SELECT <array<tuple<str, float64>>> [(1, '2')];''', [[['1', 2.0]]], ) await self.assert_query_result( r'''WITH X := [(1, '2')] SELECT <array<tuple<str, float64>>> X;''', [[['1', 2.0]]], ) await self.assert_query_result( r'''SELECT <tuple<array<float64>>> (['1'],);''', [[[1.0]]], ) async def test_edgeql_casts_collections_02(self): await self.assert_query_result( R''' WITH std AS MODULE math, foo := (SELECT [1, 2, 3]) SELECT <array<str>>foo; ''', [['1', '2', '3']], ) await self.assert_query_result( R''' WITH std AS MODULE math, foo := (SELECT [<int32>1, <int32>2, <int32>3]) SELECT <array<str>>foo; ''', [['1', '2', '3']], ) await self.assert_query_result( R''' WITH std AS MODULE math, foo := (SELECT [(1,), (2,), (3,)]) SELECT <array<tuple<str>>>foo; ''', [[['1'], ['2'], ['3']]], ) # casting into an abstract scalar should be illegal async def test_edgeql_casts_illegal_01(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r"cannot cast into generic.*'anytype'"): await self.con.execute(""" SELECT <anytype>123; """) async def test_edgeql_casts_illegal_02(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r"cannot cast into generic.*anyscalar'"): await self.con.execute(""" SELECT <anyscalar>123; """) async def test_edgeql_casts_illegal_03(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r"cannot cast into generic.*anyreal'"): await self.con.execute(""" SELECT <anyreal>123; """) async def test_edgeql_casts_illegal_04(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r"cannot cast into generic.*anyint'"): await self.con.execute(""" SELECT <anyint>123; """) async def test_edgeql_casts_illegal_05(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r'cannot cast.*'): await self.con.execute(""" SELECT <anyfloat>123; """) async def test_edgeql_casts_illegal_06(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r"cannot cast into generic.*sequence'"): await self.con.execute(""" SELECT <sequence>123; """) async def test_edgeql_casts_illegal_07(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r"cannot cast into generic.*anytype'"): await self.con.execute(""" SELECT <array<anytype>>[123]; """) async def test_edgeql_casts_illegal_08(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r"cannot cast into generic.*'anytype'"): await self.con.execute(""" SELECT <tuple<int64, anytype>>(123, 123); """) async def test_edgeql_casts_illegal_09(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r"cannot cast.*std::Object.*use.*IS schema::Object.*"): await self.con.execute(""" SELECT <schema::Object>std::Object; """) # NOTE: json is a special type as it has its own type system. A # json value can be JSON array, object, boolean, number, string or # null. All of these JSON types have their own semantics. Casting # into json converts data into one of those specific JSON types. # Any of the EdgeDB numeric types (derived from anyreal) are cast # into JSON number, str is cast into JSON string, bool is cast # into JSON bool. Other EdgeDB scalars (like datetime) are cast # into JSON string that represents that value (similar to casting # to str first). Thus json values also have some type information # and when casting back to EdgeDB scalars this type information is # used to determine the valid casts (e.g. it's illegal to cast a # JSON string "true" into a bool). # # Casting to json is lossless (in the same way and for the same # reason as casting into str). async def test_edgeql_casts_json_01(self): await self.assert_query_result( r'''SELECT <bool><json>True = True;''', [True], ) await self.assert_query_result( r'''SELECT <bool><json>False = False;''', [True], ) await self.assert_query_result( r'''SELECT <str><json>"Hello" = 'Hello';''', [True], ) await self.assert_query_result( r''' WITH U := uuid_generate_v1mc() SELECT <uuid><json>U = U; ''', [True], ) await self.assert_query_result( r''' SELECT <datetime><json>datetime_of_statement() = datetime_of_statement(); ''', [True], ) await self.assert_query_result( r''' SELECT <cal::local_datetime><json>cal::to_local_datetime( '2018-05-07T20:01:22.306916') = cal::to_local_datetime('2018-05-07T20:01:22.306916'); ''', [True], ) await self.assert_query_result( r''' SELECT <cal::local_date><json>cal::to_local_date('2018-05-07') = cal::to_local_date('2018-05-07'); ''', [True], ) await self.assert_query_result( r''' SELECT <cal::local_time><json> cal::to_local_time('20:01:22.306916') = cal::to_local_time('20:01:22.306916'); ''', [True], ) await self.assert_query_result( r''' SELECT <duration><json>to_duration(hours:=20) = to_duration(hours:=20); ''', [True], ) await self.assert_query_result( r'''SELECT <int16><json>to_int16('12345') = 12345;''', [True], ) await self.assert_query_result( r'''SELECT <int32><json>to_int32('1234567890') = 1234567890;''', [True], ) await self.assert_query_result( r''' SELECT <int64><json>to_int64( '1234567890123') = 1234567890123; ''', [True], ) await self.assert_query_result( r'''SELECT <float32><json>to_float32('2.5') = 2.5;''', [True], ) await self.assert_query_result( r'''SELECT <float64><json>to_float64('2.5') = 2.5;''', [True], ) await self.assert_query_result( r''' SELECT <bigint><json>to_bigint( '123456789123456789123456789') = to_bigint( '123456789123456789123456789'); ''', [True], ) await self.assert_query_result( r''' SELECT <decimal><json>to_decimal( '123456789123456789123456789.123456789123456789123456789') = to_decimal( '123456789123456789123456789.123456789123456789123456789'); ''', [True], ) async def test_edgeql_casts_json_02(self): await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <bool><json>T.p_bool = T.p_bool; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <str><json>T.p_str = T.p_str; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <datetime><json>T.p_datetime = T.p_datetime; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <cal::local_datetime><json>T.p_local_datetime = T.p_local_datetime; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <cal::local_date><json>T.p_local_date = T.p_local_date; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <cal::local_time><json>T.p_local_time = T.p_local_time; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <duration><json>T.p_duration = T.p_duration; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <int16><json>T.p_int16 = T.p_int16; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <int32><json>T.p_int32 = T.p_int32; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <int64><json>T.p_int64 = T.p_int64; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <float32><json>T.p_float32 = T.p_float32; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <float64><json>T.p_float64 = T.p_float64; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <bigint><json>T.p_bigint = T.p_bigint; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello') SELECT <decimal><json>T.p_decimal = T.p_decimal; ''', [True], ) async def test_edgeql_casts_json_03(self): await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello'), J := (SELECT JSONTest FILTER .j_str = <json>'Hello') SELECT <bool>J.j_bool = T.p_bool; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello'), J := (SELECT JSONTest FILTER .j_str = <json>'Hello') SELECT <str>J.j_str = T.p_str; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello'), J := (SELECT JSONTest FILTER .j_str = <json>'Hello') SELECT <datetime>J.j_datetime = T.p_datetime; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello'), J := (SELECT JSONTest FILTER .j_str = <json>'Hello') SELECT <cal::local_datetime>J.j_local_datetime = T.p_local_datetime; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello'), J := (SELECT JSONTest FILTER .j_str = <json>'Hello') SELECT <cal::local_date>J.j_local_date = T.p_local_date; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello'), J := (SELECT JSONTest FILTER .j_str = <json>'Hello') SELECT <cal::local_time>J.j_local_time = T.p_local_time; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello'), J := (SELECT JSONTest FILTER .j_str = <json>'Hello') SELECT <duration>J.j_duration = T.p_duration; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello'), J := (SELECT JSONTest FILTER .j_str = <json>'Hello') SELECT <int16>J.j_int16 = T.p_int16; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello'), J := (SELECT JSONTest FILTER .j_str = <json>'Hello') SELECT <int32>J.j_int32 = T.p_int32; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello'), J := (SELECT JSONTest FILTER .j_str = <json>'Hello') SELECT <int64>J.j_int64 = T.p_int64; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello'), J := (SELECT JSONTest FILTER .j_str = <json>'Hello') SELECT <float32>J.j_float32 = T.p_float32; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello'), J := (SELECT JSONTest FILTER .j_str = <json>'Hello') SELECT <float64>J.j_float64 = T.p_float64; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello'), J := (SELECT JSONTest FILTER .j_str = <json>'Hello') SELECT <bigint>J.j_bigint = T.p_bigint; ''', [True], ) await self.assert_query_result( r''' WITH T := (SELECT Test FILTER .p_str = 'Hello'), J := (SELECT JSONTest FILTER .j_str = <json>'Hello') SELECT <decimal>J.j_decimal = T.p_decimal; ''', [True], ) async def test_edgeql_casts_json_04(self): self.assertEqual( await self.con.query(''' select <json>( select schema::Type{name} filter .name = 'std::bool' ) '''), edgedb.Set(('{"name": "std::bool"}',)) ) async def test_edgeql_casts_json_05(self): self.assertEqual( await self.con.query( 'select <json>{(1, 2), (3, 4)}'), ['[1, 2]', '[3, 4]']) self.assertEqual( await self.con.query( 'select <json>{(a := 1, b := 2), (a := 3, b := 4)}'), ['{"a": 1, "b": 2}', '{"a": 3, "b": 4}']) self.assertEqual( await self.con.query( 'select <json>{[1, 2], [3, 4]}'), ['[1, 2]', '[3, 4]']) self.assertEqual( await self.con.query( 'select <json>{[(1, 2)], [(3, 4)]}'), ['[[1, 2]]', '[[3, 4]]']) async def test_edgeql_casts_json_06(self): self.assertEqual( await self.con.query_json( 'select <json>{(1, 2), (3, 4)}'), '[[1, 2], [3, 4]]') self.assertEqual( await self.con.query_json( 'select <json>{[1, 2], [3, 4]}'), '[[1, 2], [3, 4]]') self.assertEqual( await self.con.query_json( 'select <json>{[(1, 2)], [(3, 4)]}'), '[[[1, 2]], [[3, 4]]]') async def test_edgeql_casts_json_07(self): # This is the same suite of tests as for str. The point is # that when it comes to casting into various date and time # types JSON strings and regular strings should behave # identically. # # Canonical date and time str representations must follow ISO # 8601. This test assumes that the server is configured to be # in UTC time zone. await self.assert_query_result( r''' WITH x := <json>'2018-05-07T20:01:22.306916+00:00' SELECT <json><datetime>x = x; ''', [True], ) await self.assert_query_result( # validating that these are all in fact the same datetime r''' WITH x := <json>{ '2018-05-07T15:01:22.306916-05:00', '2018-05-07T15:01:22.306916-05', '2018-05-07T20:01:22.306916Z', '2018-05-07T20:01:22.306916+0000', '2018-05-07T20:01:22.306916+00', # the '-' and ':' separators may be omitted '20180507T200122.306916+00', # acceptable RFC 3339 '2018-05-07 20:01:22.306916+00:00', '2018-05-07t20:01:22.306916z', } SELECT <datetime>x = <datetime><json>'2018-05-07T20:01:22.306916+00:00'; ''', [True, True, True, True, True, True, True, True], ) async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax'): await self.con.query_single( 'SELECT <datetime><json>"2018-05-07;20:01:22.306916+00:00"') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax'): await self.con.query_single( 'SELECT <datetime><json>"2018-05-07T20:01:22.306916"') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax'): await self.con.query_single( 'SELECT <datetime><json>"2018-05-07T20:01:22.306916 1000"') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax'): await self.con.query_single( '''SELECT <datetime><json> "2018-05-07T20:01:22.306916 US/Central" ''') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax'): await self.con.query_single( 'SELECT <datetime><json>"2018-05-07T20:01:22.306916 +GMT1"') async def test_edgeql_casts_json_08(self): # This is the same suite of tests as for str. The point is # that when it comes to casting into various date and time # types JSON strings and regular strings should behave # identically. # # Canonical date and time str representations must follow ISO # 8601. This test assumes that the server is configured to be # in UTC time zone. await self.assert_query_result( r''' WITH x := <json>'2018-05-07T20:01:22.306916' SELECT <json><cal::local_datetime>x = x; ''', [True], ) await self.assert_query_result( # validating that these are all in fact the same datetime r''' WITH x := <json>{ # the '-' and ':' separators may be omitted '20180507T200122.306916', # acceptable RFC 3339 '2018-05-07 20:01:22.306916', '2018-05-07t20:01:22.306916', } SELECT <cal::local_datetime>x = <cal::local_datetime><json>'2018-05-07T20:01:22.306916'; ''', [True, True, True], ) async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( '''SELECT <cal::local_datetime><json>"2018-05-07;20:01:22.306916" ''') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( '''SELECT <cal::local_datetime><json> "2018-05-07T20:01:22.306916+01:00" ''') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( '''SELECT <cal::local_datetime><json> "2018-05-07T20:01:22.306916 GMT"''') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( '''SELECT <cal::local_datetime><json> "2018-05-07T20:01:22.306916 GMT0"''') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( '''SELECT <cal::local_datetime><json> "2018-05-07T20:01:22.306916 US/Central" ''') async def test_edgeql_casts_json_09(self): # This is the same suite of tests as for str. The point is # that when it comes to casting into various date and time # types JSON strings and regular strings should behave # identically. # # Canonical date and time str representations must follow ISO # 8601. await self.assert_query_result( r''' WITH x := <json>'2018-05-07' SELECT <json><cal::local_date>x = x; ''', [True], ) await self.assert_query_result( # validating that these are all in fact the same date r''' # the '-' separators may be omitted WITH x := <json>'20180507' SELECT <cal::local_date>x = <cal::local_date><json>'2018-05-07'; ''', [True], ) async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( 'SELECT <cal::local_date><json>"2018-05-07T20:01:22.306916"') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( 'SELECT <cal::local_date><json>"2018/05/07"') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( 'SELECT <cal::local_date><json>"2018.05.07"') async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( 'SELECT <cal::local_date><json>"2018-05-07+01:00"') async def test_edgeql_casts_json_10(self): # This is the same suite of tests as for str. The point is # that when it comes to casting into various date and time # types JSON strings and regular strings should behave # identically. # # Canonical date and time str representations must follow ISO # 8601. await self.assert_query_result( r''' WITH x := <json>'20:01:22.306916' SELECT <json><cal::local_time>x = x; ''', [True], ) await self.assert_query_result( r''' WITH x := <json>{ '20:01', '20:01:00', # the ':' separators may be omitted '2001', '200100', } SELECT <cal::local_time>x = <cal::local_time>'20:01:00'; ''', [True, True, True, True], ) async with self.assertRaisesRegexTx( edgedb.InvalidValueError, 'invalid input syntax for type cal::local_time'): await self.con.query_single( "SELECT <cal::local_time><json>'2018-05-07 20:01:22'") async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid input syntax for type'): await self.con.query_single( 'SELECT <cal::local_time><json>"20:01:22.306916+01:00"') async def test_edgeql_casts_json_11(self): await self.assert_query_result( r"SELECT <array<int64>><json>[1, 1, 2, 3, 5]", [[1, 1, 2, 3, 5]] ) async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'expected JSON number or null; got JSON string'): await self.con.query_single( r"SELECT <array<int64>><json>['asdf']") async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'expected JSON number or null; got JSON string'): await self.con.query_single( r"SELECT <array<int64>>to_json('[1, 2, \"asdf\"]')") async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid null value in cast'): await self.con.query_single( r"SELECT <array<int64>>[to_json('1'), to_json('null')]") async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid null value in cast'): await self.con.query_single( r"SELECT <array<int64>>to_json('[1, 2, null]')") async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid null value in cast'): await self.con.query_single( r"SELECT <array<int64>><array<json>>to_json('[1, 2, null]')") async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'cannot extract elements from a scalar'): await self.con.query_single( r"SELECT <array<int64>><json>'asdf'") async def test_edgeql_casts_json_12(self): self.assertEqual( await self.con.query( r""" SELECT <tuple<a: int64, b: int64>> to_json('{"a": 1, "b": 2}') """ ), [edgedb.NamedTuple(a=1, b=2)], ) await self.assert_query_result( r""" SELECT <tuple<a: int64, b: int64>> to_json({'{"a": 3000, "b": -1}', '{"a": 1, "b": 12}'}); """, [{"a": 3000, "b": -1}, {"a": 1, "b": 12}], ) await self.assert_query_result( r""" SELECT <tuple<int64, int64>> to_json({'[3000, -1]', '[1, 12]'}) """, [[3000, -1], [1, 12]], ) self.assertEqual( await self.con.query( r""" SELECT <tuple<int64, int64>> to_json({'[3000, -1]', '[1, 12]'}) """ ), [(3000, -1), (1, 12)], ) self.assertEqual( await self.con.query( r""" SELECT <tuple<json, json>> to_json({'[3000, -1]', '[1, 12]'}) """ ), [('3000', '-1'), ('1', '12')], ) self.assertEqual( await self.con.query( r""" SELECT <tuple<json, json>> to_json({'[3000, -1]', '[1, null]'}) """ ), [('3000', '-1'), ('1', 'null')], ) self.assertEqual( await self.con.query_single( r""" SELECT <tuple<int64, tuple<a: int64, b: int64>>> to_json('[3000, {"a": 1, "b": 2}]') """ ), (3000, edgedb.NamedTuple(a=1, b=2)) ) self.assertEqual( await self.con.query_single( r""" SELECT <tuple<int64, array<tuple<a: int64, b: str>>>> to_json('[3000, [{"a": 1, "b": "foo"}, {"a": 12, "b": "bar"}]]') """ ), (3000, [edgedb.NamedTuple(a=1, b="foo"), edgedb.NamedTuple(a=12, b="bar")]) ) async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'expected JSON number or null; got JSON string'): await self.con.query( r""" SELECT <tuple<a: int64, b: int64>> to_json('{"a": 1, "b": "2"}') """ ) # This isn't really the best error message for this. async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid null value in cast'): await self.con.query( r"""SELECT <tuple<a: int64, b: int64>>to_json('{"a": 1}')""" ) async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid null value in cast'): await self.con.query( r"""SELECT <tuple<int64, int64>>to_json('[3000]')""" ) async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid null value in cast'): await self.con.query( r""" SELECT <tuple<a: int64, b: int64>> to_json('[3000, 1000]') """ ) async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid null value in cast'): await self.con.query( r"""SELECT <tuple<a: int64, b: int64>> to_json('"test"')""" ) async with self.assertRaisesRegexTx( edgedb.InvalidValueError, r'invalid null value in cast'): await self.con.query( r"""SELECT <tuple<json, json>> to_json('[3000]')""" ) async def test_edgeql_casts_assignment_01(self): async with self._run_and_rollback(): await self.con.execute(r""" # int64 is assignment castable or implicitly castable # into any other numeric type INSERT ScalarTest { p_int16 := 1, p_int32 := 1, p_int64 := 1, p_float32 := 1, p_float64 := 1, p_bigint := 1, p_decimal := 1, }; """) await self.assert_query_result( r""" SELECT ScalarTest { p_int16, p_int32, p_int64, p_float32, p_float64, p_bigint, p_decimal, }; """, [{ 'p_int16': 1, 'p_int32': 1, 'p_int64': 1, 'p_float32': 1, 'p_float64': 1, 'p_bigint': 1, 'p_decimal': 1, }], ) async def test_edgeql_casts_assignment_02(self): async with self._run_and_rollback(): await self.con.execute(r"""<|fim▁hole|> p_float32 := 1.5, }; """) await self.assert_query_result( r""" SELECT ScalarTest { p_float32, }; """, [{ 'p_float32': 1.5, }], ) async def test_edgeql_casts_assignment_03(self): async with self._run_and_rollback(): # in particular, bigint and decimal are not assignment-castable # into any other numeric type for typename in ['int16', 'int32', 'int64', 'float32', 'float64']: for numtype in {'bigint', 'decimal'}: query = f''' INSERT ScalarTest {{ p_{typename} := <{numtype}>3, p_{numtype} := 1001, }}; ''' async with self.assertRaisesRegexTx( edgedb.QueryError, r'invalid target for property', msg=query): await self.con.execute(query + f''' # clean up, so other tests can proceed DELETE ( SELECT ScalarTest FILTER .p_{numtype} = 1001 ); ''') async def test_edgeql_casts_custom_scalar_01(self): await self.assert_query_result( ''' SELECT <custom_str_t>'ABC' ''', ['ABC'] ) async with self.assertRaisesRegexTx( edgedb.ConstraintViolationError, 'invalid custom_str_t'): await self.con.query( "SELECT <custom_str_t>'123'") async def test_edgeql_casts_prohibit_tuple_query_params_01(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r'cannot pass tuples as query parameters', ): await self.con.query( r''' SELECT Test { id, num := (<tuple<int64, float64, str, bytes>>$tup).0, st := (<tuple<int64, float64, str, bytes>>$tup).2, }; ''', tup=(0, 1.0, "str", b"bytes"), ) async def test_edgeql_casts_prohibit_tuple_query_params_02(self): async with self.assertRaisesRegexTx( edgedb.QueryError, r'cannot pass collections with tuple elements' r' as query parameters', ): await self.con.query( r"SELECT <array<tuple<int64, str>>>$0;", [(0, 'zero'), (1, 'one')], ) async def test_edgeql_cast_empty_set_to_array_01(self): await self.assert_query_result( r''' SELECT <array<Object>>{}; ''', [], )<|fim▁end|>
# float64 is assignment castable to float32 INSERT ScalarTest {
<|file_name|>test_ffi_backend.py<|end_file_name|><|fim▁begin|>import py, sys, platform import pytest from testing import backend_tests, test_function, test_ownlib from cffi import FFI import _cffi_backend class TestFFI(backend_tests.BackendTests, test_function.TestFunction, test_ownlib.TestOwnLib): TypeRepr = "<ctype '%s'>" @staticmethod def Backend(): return _cffi_backend def test_not_supported_bitfield_in_result(self): ffi = FFI(backend=self.Backend()) ffi.cdef("struct foo_s { int a,b,c,d,e; int x:1; };") e = py.test.raises(NotImplementedError, ffi.callback, "struct foo_s foo(void)", lambda: 42) assert str(e.value) == ("<struct foo_s(*)(void)>: " "cannot pass as argument or return value a struct with bit fields") def test_inspecttype(self): ffi = FFI(backend=self.Backend()) assert ffi.typeof("long").kind == "primitive" assert ffi.typeof("long(*)(long, long**, ...)").cname == ( "long(*)(long, long * *, ...)") assert ffi.typeof("long(*)(long, long**, ...)").ellipsis is True def test_new_handle(self): ffi = FFI(backend=self.Backend()) o = [2, 3, 4] p = ffi.new_handle(o) assert ffi.typeof(p) == ffi.typeof("void *") assert ffi.from_handle(p) is o assert ffi.from_handle(ffi.cast("char *", p)) is o py.test.raises(RuntimeError, ffi.from_handle, ffi.NULL) class TestBitfield: def check(self, source, expected_ofs_y, expected_align, expected_size): # NOTE: 'expected_*' is the numbers expected from GCC. # The numbers expected from MSVC are not explicitly written # in this file, and will just be taken from the compiler. ffi = FFI() ffi.cdef("struct s1 { %s };" % source) ctype = ffi.typeof("struct s1") # verify the information with gcc ffi1 = FFI() ffi1.cdef(""" static const int Gofs_y, Galign, Gsize; struct s1 *try_with_value(int fieldnum, long long value); """) fnames = [name for name, cfield in ctype.fields if name and cfield.bitsize > 0] setters = ['case %d: s.%s = value; break;' % iname for iname in enumerate(fnames)] lib = ffi1.verify(""" struct s1 { %s }; struct sa { char a; struct s1 b; }; #define Gofs_y offsetof(struct s1, y) #define Galign offsetof(struct sa, b) #define Gsize sizeof(struct s1) struct s1 *try_with_value(int fieldnum, long long value) { static struct s1 s; memset(&s, 0, sizeof(s)); switch (fieldnum) { %s } return &s; } """ % (source, ' '.join(setters))) if sys.platform == 'win32': expected_ofs_y = lib.Gofs_y expected_align = lib.Galign expected_size = lib.Gsize else: assert (lib.Gofs_y, lib.Galign, lib.Gsize) == ( expected_ofs_y, expected_align, expected_size) # the real test follows assert ffi.offsetof("struct s1", "y") == expected_ofs_y assert ffi.alignof("struct s1") == expected_align assert ffi.sizeof("struct s1") == expected_size # compare the actual storage of the two for name, cfield in ctype.fields: if cfield.bitsize < 0 or not name: continue if int(ffi.cast(cfield.type, -1)) == -1: # signed min_value = -(1 << (cfield.bitsize-1)) max_value = (1 << (cfield.bitsize-1)) - 1 else: min_value = 0 max_value = (1 << cfield.bitsize) - 1 for t in [1, 2, 4, 8, 16, 128, 2813, 89728, 981729, -1,-2,-4,-8,-16,-128,-2813,-89728,-981729]: if min_value <= t <= max_value: self._fieldcheck(ffi, lib, fnames, name, t) def _fieldcheck(self, ffi, lib, fnames, name, value): s = ffi.new("struct s1 *") setattr(s, name, value) assert getattr(s, name) == value raw1 = ffi.buffer(s)[:] t = lib.try_with_value(fnames.index(name), value) raw2 = ffi.buffer(t, len(raw1))[:] assert raw1 == raw2 def test_bitfield_basic(self): self.check("int a; int b:9; int c:20; int y;", 8, 4, 12) self.check("int a; short b:9; short c:7; int y;", 8, 4, 12) self.check("int a; short b:9; short c:9; int y;", 8, 4, 12) def test_bitfield_reuse_if_enough_space(self): self.check("int a:2; char y;", 1, 4, 4) self.check("int a:1; char b ; int c:1; char y;", 3, 4, 4) self.check("int a:1; char b:8; int c:1; char y;", 3, 4, 4) self.check("char a; int b:9; char y;", 3, 4, 4) self.check("char a; short b:9; char y;", 4, 2, 6) self.check("int a:2; char b:6; char y;", 1, 4, 4) self.check("int a:2; char b:7; char y;", 2, 4, 4) self.check("int a:2; short b:15; char c:2; char y;", 5, 4, 8) self.check("int a:2; char b:1; char c:1; char y;", 1, 4, 4) @pytest.mark.skipif("platform.machine().startswith('arm')") def test_bitfield_anonymous_no_align(self): L = FFI().alignof("long long") self.check("char y; int :1;", 0, 1, 2) self.check("char x; int z:1; char y;", 2, 4, 4) self.check("char x; int :1; char y;", 2, 1, 3) self.check("char x; long long z:48; char y;", 7, L, 8) self.check("char x; long long :48; char y;", 7, 1, 8) self.check("char x; long long z:56; char y;", 8, L, 8 + L) self.check("char x; long long :56; char y;", 8, 1, 9) self.check("char x; long long z:57; char y;", L + 8, L, L + 8 + L) self.check("char x; long long :57; char y;", L + 8, 1, L + 9) @pytest.mark.skipif("not platform.machine().startswith('arm')") def test_bitfield_anonymous_align_arm(self): L = FFI().alignof("long long") self.check("char y; int :1;", 0, 4, 4) self.check("char x; int z:1; char y;", 2, 4, 4) self.check("char x; int :1; char y;", 2, 4, 4) self.check("char x; long long z:48; char y;", 7, L, 8) self.check("char x; long long :48; char y;", 7, 8, 8) self.check("char x; long long z:56; char y;", 8, L, 8 + L)<|fim▁hole|> @pytest.mark.skipif("platform.machine().startswith('arm')") def test_bitfield_zero(self): L = FFI().alignof("long long") self.check("char y; int :0;", 0, 1, 4) self.check("char x; int :0; char y;", 4, 1, 5) self.check("char x; int :0; int :0; char y;", 4, 1, 5) self.check("char x; long long :0; char y;", L, 1, L + 1) self.check("short x, y; int :0; int :0;", 2, 2, 4) self.check("char x; int :0; short b:1; char y;", 5, 2, 6) self.check("int a:1; int :0; int b:1; char y;", 5, 4, 8) @pytest.mark.skipif("not platform.machine().startswith('arm')") def test_bitfield_zero_arm(self): L = FFI().alignof("long long") self.check("char y; int :0;", 0, 4, 4) self.check("char x; int :0; char y;", 4, 4, 8) self.check("char x; int :0; int :0; char y;", 4, 4, 8) self.check("char x; long long :0; char y;", L, 8, L + 8) self.check("short x, y; int :0; int :0;", 2, 4, 4) self.check("char x; int :0; short b:1; char y;", 5, 4, 8) self.check("int a:1; int :0; int b:1; char y;", 5, 4, 8) def test_error_cases(self): ffi = FFI() py.test.raises(TypeError, 'ffi.cdef("struct s1 { float x:1; };"); ffi.new("struct s1 *")') py.test.raises(TypeError, 'ffi.cdef("struct s2 { char x:0; };"); ffi.new("struct s2 *")') py.test.raises(TypeError, 'ffi.cdef("struct s3 { char x:9; };"); ffi.new("struct s3 *")') def test_struct_with_typedef(self): ffi = FFI() ffi.cdef("typedef struct { float x; } foo_t;") p = ffi.new("foo_t *", [5.2]) assert repr(p).startswith("<cdata 'foo_t *' ") def test_struct_array_no_length(self): ffi = FFI() ffi.cdef("struct foo_s { int x; int a[]; };") p = ffi.new("struct foo_s *", [100, [200, 300, 400]]) assert p.x == 100 assert ffi.typeof(p.a) is ffi.typeof("int *") # no length available assert p.a[0] == 200 assert p.a[1] == 300 assert p.a[2] == 400 @pytest.mark.skipif("sys.platform != 'win32'") def test_getwinerror(self): ffi = FFI() code, message = ffi.getwinerror(1155) assert code == 1155 assert message == ("No application is associated with the " "specified file for this operation") ffi.cdef("void SetLastError(int);") lib = ffi.dlopen("Kernel32.dll") lib.SetLastError(2) code, message = ffi.getwinerror() assert code == 2 assert message == "The system cannot find the file specified" code, message = ffi.getwinerror(-1) assert code == 2 assert message == "The system cannot find the file specified"<|fim▁end|>
self.check("char x; long long :56; char y;", 8, L, 8 + L) self.check("char x; long long z:57; char y;", L + 8, L, L + 8 + L) self.check("char x; long long :57; char y;", L + 8, L, L + 8 + L)
<|file_name|>stdio-is-blocking.rs<|end_file_name|><|fim▁begin|>// run-pass // ignore-emscripten no processes // ignore-sgx no processes use std::env; use std::io::prelude::*; use std::process::Command; use std::thread; const THREADS: usize = 20; const WRITES: usize = 100; const WRITE_SIZE: usize = 1024 * 32; fn main() { let args = env::args().collect::<Vec<_>>(); if args.len() == 1 { parent(); } else { child(); } } fn parent() { let me = env::current_exe().unwrap(); let mut cmd = Command::new(me); cmd.arg("run-the-test"); let output = cmd.output().unwrap(); assert!(output.status.success()); assert_eq!(output.stderr.len(), 0); assert_eq!(output.stdout.len(), WRITES * THREADS * WRITE_SIZE); for byte in output.stdout.iter() { assert_eq!(*byte, b'a'); } } fn child() { let threads = (0..THREADS).map(|_| { thread::spawn(|| { let buf = [b'a'; WRITE_SIZE]; for _ in 0..WRITES { write_all(&buf); } }) }).collect::<Vec<_>>(); for thread in threads { thread.join().unwrap(); } } #[cfg(unix)]<|fim▁hole|> use std::fs::File; use std::mem; use std::os::unix::prelude::*; let mut file = unsafe { File::from_raw_fd(1) }; let res = file.write_all(buf); mem::forget(file); res.unwrap(); } #[cfg(windows)] fn write_all(buf: &[u8]) { use std::fs::File; use std::mem; use std::os::windows::raw::*; use std::os::windows::prelude::*; const STD_OUTPUT_HANDLE: u32 = (-11i32) as u32; extern "system" { fn GetStdHandle(handle: u32) -> HANDLE; } let mut file = unsafe { let handle = GetStdHandle(STD_OUTPUT_HANDLE); assert!(!handle.is_null()); File::from_raw_handle(handle) }; let res = file.write_all(buf); mem::forget(file); res.unwrap(); }<|fim▁end|>
fn write_all(buf: &[u8]) {
<|file_name|>http.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*- import logging from model_utils import Choices from simptools.wrappers.http import HttpClient, HttpRequest from requests.exceptions import ConnectionError from payway.merchants.models import Merchant __author__ = 'Razzhivin Alexander' __email__ = '[email protected]' RESPONSE_STATUS = Choices( ('OK', 'OK'), ) class MerchantHttpRequest(HttpRequest): def __init__(self, merchant, order): self.merchant = merchant self.order = order if self.merchant.result_url_method == Merchant.URL_METHODS.GET: self.__set_GET() else:<|fim▁hole|> self.POST = self.__request() def __set_GET(self, *args, **kwargs): self.GET = self.__request() def __request(self): return { 'url': self.merchant.result_url, 'data': { 'uid': self.order.uid, 'is_paid': self.order.is_paid, 'sum': self.order.sum.amount, 'sum_currency': self.order.sum_currency, 'description': self.order.description, } } class MerchantHttpClient(HttpClient): @classmethod def notify(cls, merchant, order): result = '' try: request = MerchantHttpRequest(merchant, order) response = cls.execute(request) result = response.text except ConnectionError: logging.warn('Problems when connecting to merchant {0}'.format(merchant.result_url)) return result<|fim▁end|>
self.__set_POST() def __set_POST(self, *args, **kwargs):
<|file_name|>Champernownes_constant.py<|end_file_name|><|fim▁begin|>import time output = '' i=1 start_time = time.time()<|fim▁hole|> i += 1 print(int(output[9]) * int(output[99]) * int(output[999]) * int(output[9999]) * int(output[99999]) * int(output[999999])) print("--- %s seconds ---" % (time.time() - start_time))<|fim▁end|>
while len(output)<1000001: output +=str(i)
<|file_name|>html_emitter.py<|end_file_name|><|fim▁begin|>""" Copyright 2015 Google, 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. Implements an HTML documentation emitter for YANG modules """ import os import re from xml.etree import ElementTree as ET from jinja2 import Environment, FileSystemLoader from .doc_emitter import DocEmitter from .yangdoc_defs import YangDocDefs from . import html_helper from . import yangpath class HTMLEmitter(DocEmitter): def genModuleDoc(self, mod, ctx): """HTML emitter for top-level module documentation given a ModuleDoc object""" ht = html_helper.HTMLHelper() # TODO: this is far too hardcoded mod_div = ht.open_tag("div", newline=True) # module name mod_div += ht.h1(mod.module_name, {"class": "module-name", "id": ("mod-" + ht.gen_html_id(mod.module_name))},2,True) if 'version' in mod.module.attrs: mod_div += ht.h4("openconfig-version: " + mod.module.attrs['version'], {"class": "module-header"},2,True) # module description header mod_div += ht.h4("Description", {"class": "module-desc-header"},2,True) # module description text paragraphs = text_to_paragraphs(mod.module.attrs['desc']) for para in paragraphs: mod_div += ht.para(para, {"class": "module-desc-text"},2,True) mod_div += ht.h4("Imports", {"class": "module-header"},2,True) mod_div += "<p class=\"module-desc-text\">" for i in mod.module.attrs['imports']: mod_div += "%s<br>\n" % i mod_div += "</p>\n" mod_div += ht.close_tag(newline=True) # initialize and store in the module docs self.moduledocs[mod.module_name] = {} self.moduledocs[mod.module_name]['module'] = mod_div self.moduledocs[mod.module_name]['data'] = "" # handle typedefs if len(mod.typedefs) > 0: types_div = ht.open_tag("div", newline=True) types_div += ht.h3("Defined types", {"class": "module-types-header", "id": mod.module_name + "-defined-types"},2,True) for (typename, td) in mod.typedefs.items(): types_div += ht.h4(typename,{"class": "module-type-name","id": "type-" + ht.gen_html_id(typename)},2,True) types_div += ht.para(ht.add_tag("span","description:" + ht.br(newline=True), {"class": "module-type-text-label"}) + td.attrs['desc'],{"class": "module-type-text"},2,True) types_div += gen_type_info(td.typedoc, 2) for prop in YangDocDefs.type_leaf_properties: if prop in td.attrs: types_div += ht.para(ht.add_tag("span", prop,{"class": "module-type-text-label"}) + ": " + td.attrs[prop],{"class": "module-type-text"},2,True) types_div += ht.close_tag(newline=True) else: # module doesn't have any typedefs types_div = "" # store the typedef docs self.moduledocs[mod.module_name]['typedefs'] = types_div # handle identities if len(mod.identities) > 0: idents_div = ht.open_tag("div", newline=True) idents_div += ht.h3("Identities", {"class": "module-types-header", "id": mod.module_name + "-identities"},2,True) for base_id in mod.base_identities: idents_div += ht.h4("base: " + base_id,{"class": "module-type-name","id":"ident-" + ht.gen_html_id(base_id)},2,True) idents_div += ht.para(ht.add_tag("span","description:" + ht.br(newline=True), {"class": "module-type-text-label"}) + mod.identities[base_id].attrs['desc'],{"class": "module-type-text"},2,True) # collect all of the identities that have base_id as # their base # TODO(aashaikh): this needs to be updated to handle nested identities / multiple inheritance derived = { key:value for key,value in mod.identities.items() if value.attrs['base'] == base_id } # emit the identities derived from the current base for (idname, id) in derived.items(): idents_div += ht.h4(idname,{"class": "module-type-name","id":"ident-" + ht.gen_html_id(idname)},2,True) idents_div += ht.para(ht.add_tag("span","description:",{"class": "module-type-text-label"}) + ht.br(newline=True) + id.attrs['desc'],{"class":"module-type-text"},2,True) idents_div += ht.para(ht.add_tag("span", "base identity: ",{"class": "module-type-text-label"}) + ht.add_tag("a", id.attrs['base'],{"href":"#ident-"+ht.gen_html_id(id.attrs['base'])}), {"class":"module-type-text"},2,True) idents_div += ht.close_tag(newline=True)<|fim▁hole|> # store the identity docs self.moduledocs[mod.module_name]['identities'] = idents_div gen_nav_tree(self, mod, 0) def genStatementDoc(self, statement, ctx, level=1): """HTML emitter for module data node given a StatementDoc object""" if ctx.opts.no_structure and statement.keyword in ctx.skip_keywords: return ht = html_helper.HTMLHelper() s_div = ht.open_tag("div", {"class":"statement-section"}, newline=True) if ctx.opts.strip_namespace: pathstr = yangpath.strip_namespace(statement.attrs['path']) else: pathstr = statement.attrs['path'] # for 'skipped' nodes, just print the path if statement.keyword in self.path_only: s_div += ht.h4(pathstr,None,level,True) s_div += ht.close_tag(newline=True) return s_div # statement path and name (prefix, last) = yangpath.remove_last(pathstr) prefix_name = ht.add_tag("span", prefix + "/", {"class": "statement-path"}) statement_name = prefix_name + ht.br(level,True) + statement.name s_div += ht.h4(statement_name, {"class": "statement-name","id":statement.attrs['id']},level,True) # node description if 'desc' in statement.attrs: s_div += ht.para(ht.add_tag("span", "description",{"class": "statement-info-label"}) + ":<br />" + statement.attrs['desc'],{"class": "statement-info-text"},level,True) s_div += ht.close_tag(newline=True) # check for additional properties notes = "" if statement.attrs['is_key']: notes += " (list key)" if statement.attrs['config']: notes += " (rw)" else: notes += " (ro)" keyword = statement.keyword + notes s_div += ht.para(ht.add_tag("span", "nodetype",{"class": "statement-info-label"}) + ": " + keyword,{"class": "statement-info-text"},level,True) # s_div += ht.para(ht.add_tag("span", "path",{"class":"statement-info-label"}) + ": " + pathstr,{"class":"statement-info-text"},level,True) # handle list nodes if statement.attrs['is_list']: list_keys = "" for key in statement.attrs['keys']: list_keys += " [" + ht.add_tag("a", key[0], {"href":"#" + key[1]}) + "]" s_div += ht.para(ht.add_tag("span", "list keys",{"class": "statement-info-label"}) + ": " + list_keys,{"class": "statement-info-text"},level,True) if statement.typedoc: s_div += gen_type_info(statement.typedoc, level) for prop in YangDocDefs.type_leaf_properties: if prop in statement.attrs: s_div += ht.para(ht.add_tag("span", prop, {"class": "statement-info-label"}) + ": " + statement.attrs[prop],{"class": "statement-info-text"},level,True) # add this statement to the collection of data self.moduledocs[statement.module_doc.module_name]['data'] += s_div def emitDocs(self, ctx, section=None): """Return the HTML output for all modules, or single section if specified""" ht = html_helper.HTMLHelper() docs = [] navs = [] navids = [] # create the documentation elements for each module for module_name in self.moduledocs: # check if the module has no data nodes if 'data' not in self.moduledocs[module_name]: self.moduledocs[module_name]['data'] = "" else: # create the header for the data elements hdr = ht.h3("Data elements", {"class": "module-types-header", "id": module_name + "-data"},2,True) self.moduledocs[module_name]['data'] = hdr + self.moduledocs[module_name]['data'] if section is not None: return self.moduledocs[module_name][section] else: docs.append(self.moduledocs[module_name]['module'] + self.moduledocs[module_name]['typedefs'] + self.moduledocs[module_name]['identities'] + self.moduledocs[module_name]['data']) navs.append(self.moduledocs[module_name]['navlist']) navids.append(self.moduledocs[module_name]['navid']) if ctx.opts.doc_title is None: # just use the name of the first module returned by the dict if no title # is supplied doc_title = list(self.moduledocs.keys())[0] else: doc_title = ctx.opts.doc_title s = populate_template(doc_title, docs, navs, navids) return s def gen_type_info(typedoc, level=1): """Create and return documentation based on the type. Expands compound types.""" ht = html_helper.HTMLHelper() s = "" # emit type-specific attributes typename = typedoc.typename s += ht.para(ht.add_tag("span", "type",{"class": "statement-info-label"}) + ": " + typename,{"class": "statement-info-text"},level,True) if typename == 'enumeration': s += " "*level + "<ul>\n" for (enum, desc) in typedoc.attrs['enums'].items(): s += " "*level + "<li>" + enum + "<br />" + desc + "</li>\n" s += " "*level + "</ul>\n" elif typename == 'string': if 'pattern' in typedoc.attrs['restrictions']: s += " "*level + "<ul>\n" s += " "*level + "<li>pattern:<br>\n" s += " "*level + typedoc.attrs['restrictions']['pattern'] + "\n</li>\n" s += " "*level + "</ul>\n" elif typename in YangDocDefs.integer_types: if 'range' in typedoc.attrs['restrictions']: s += " "*level + "<ul>\n" s += " "*level + "<li>range:\n" s += " "*level + typedoc.attrs['restrictions']['range'] + "\n</li>\n" s += " "*level + "</ul>\n" elif typename == 'identityref': s += " "*level + "<ul>\n" s += " "*level + "<li>base: " + typedoc.attrs['base'] + "</li>\n" s += " "*level + "</ul>\n" elif typename == 'leafref': s += " "*level + "<ul>\n" s += " "*level + "<li>path reference: " + typedoc.attrs['leafref_path'] + "</li>\n" s += " "*level + "</ul>\n" elif typename == 'union': s += " "*level + "<ul>\n" for childtype in typedoc.childtypes: s += " "*level + gen_type_info(childtype) s += " "*level + "</ul>\n" else: pass return s def populate_template(title, docs, navs, nav_ids): """Populate HTML templates with the documentation content""" template_path = os.path.dirname(__file__) + "/../templates" j2_env = Environment(loader=FileSystemLoader(template_path), trim_blocks=True) template = j2_env.get_template('yangdoc.html') return template.render({'title': title, 'htmldocs': docs, 'menus': navs, 'menu_ids': nav_ids }) def gen_nav_tree(emitter, root_mod, level=0): """Generate a list structure to serve as navigation for the module. root_mod is a top-level ModuleDoc object""" ht = html_helper.HTMLHelper() nav = "<ul id=\"%s\">\n" % ("tree-" + ht.gen_html_id(root_mod.module_name)) # module link nav += "<li><a class=\"menu-module-name\" href=\"%s\">%s</a></li>\n" % ("#mod-" + ht.gen_html_id(root_mod.module_name), root_mod.module_name) # generate links for types and identities if len(root_mod.typedefs) > 0: nav += "<li><a href=\"%s\">%s</a>\n" % ("#" + ht.gen_html_id(root_mod.module_name) + "-defined-types", "Defined types") types = root_mod.typedefs.keys() nav += " <ul>\n" for typename in types: nav += " <li><a href=\"%s\">%s</a></li>\n" % ("#type-"+ht.gen_html_id(typename), typename) nav += " </ul>\n" nav += "</li>\n" if len(root_mod.identities) > 0: nav += "<li><a href=\"%s\">%s</a>\n" % ("#" + ht.gen_html_id(root_mod.module_name) + "-identities", "Identities") nav += " <ul>\n" for base_id in root_mod.base_identities: derived = { key:value for key,value in root_mod.identities.items() if value.attrs['base'] == base_id } nav += " <li><a href=\"%s\">%s</a>\n" % ("#ident-" + ht.gen_html_id(base_id), base_id) nav += " <ul>\n" for idname in derived.keys(): nav += " <li><a href=\"%s\">%s</a></li>\n" % ("#ident-" + ht.gen_html_id(idname), idname) nav += " </ul>\n" nav += " </li>\n" nav += " </ul>\n" nav += "</li>\n" # generate links for data nodes top = root_mod.module level = 0 # nav += "<li><a href=\"%s\">%s</a>\n" % ("#" + ht.gen_html_id(root_mod.module_name) + "-data", "Data elements") if len(top.children) > 0: nav += "<li><a href=\"#%s-data\">%s</a>\n" % (root_mod.module_name, "Data elements") nav += "<ul>\n" for child in top.children: nav += gen_nav(child, root_mod, level) nav += "</li>\n" nav += "</ul>\n" nav += "</ul>\n" # store the navigation list emitter.moduledocs[root_mod.module_name]['navlist'] = nav emitter.moduledocs[root_mod.module_name]['navid'] = "tree-" + ht.gen_html_id(root_mod.module_name) #modtop.nav += "</ul>" # top.nav += "<li>" + statement.name + "</li>\n" def gen_nav(node, root_mod, level = 0): """Add the list item for node (StatementDoc object)""" # print "nav: %s %s (%d)" % (node.keyword, node.name, len(node.children)) current_level = level nav = "" if len(node.children) > 0: # print the current node (opening li element) nav += " "*level + " <li>" + "<a href=\"#" + node.attrs['id'] + "\">" + node.name + "</a>\n" # start new list for the children nav += " "*level + " <ul>\n" level += 1 for child in node.children: nav += gen_nav (child, root_mod, level) # close list of children nav += " "*current_level + " </ul>\n" nav += " "*current_level + "</li>\n" else: # no children -- just print the current node and return nav += " "*current_level + " <li>" "<a href=\"#" + node.attrs['id'] + "\">" + node.name + "</a>\n" return nav def text_to_paragraphs(textblock): """Simple conversion of text into paragraphs based (naively) on blank lines -- intended to use with long, multi-paragraph descriptions""" paras = textblock.split("\n\n") return paras<|fim▁end|>
else: # module doesn't have any identities idents_div = ""
<|file_name|>pref.go<|end_file_name|><|fim▁begin|>// Code generated by goagen v1.1.0, command line: // $ goagen // --design=github.com/tikasan/eventory/design // --out=$(GOPATH) // --version=v1.1.0-dirty // // API "eventory": Models // // The content of this file is auto-generated, DO NOT MODIFY package models import ( "time" "github.com/goadesign/goa" "github.com/jinzhu/gorm" "github.com/tikasan/eventory/app" "golang.org/x/net/context" ) // 都道府県 type Pref struct { ID int `gorm:"primary_key"` // primary key Events []Event // has many Events Name string UserFollowPrefs []UserFollowPref // has many UserFollowPrefs CreatedAt time.Time // timestamp DeletedAt *time.Time // nullable timestamp (soft delete) UpdatedAt time.Time // timestamp } // TableName overrides the table name settings in Gorm to force a specific table name // in the database. func (m Pref) TableName() string { return "prefs" } // PrefDB is the implementation of the storage interface for // Pref. type PrefDB struct { Db *gorm.DB } // NewPrefDB creates a new storage type. func NewPrefDB(db *gorm.DB) *PrefDB { return &PrefDB{Db: db} } // DB returns the underlying database. func (m *PrefDB) DB() interface{} { return m.Db } // PrefStorage represents the storage interface. type PrefStorage interface { DB() interface{} List(ctx context.Context) ([]*Pref, error) Get(ctx context.Context, id int) (*Pref, error) Add(ctx context.Context, pref *Pref) error Update(ctx context.Context, pref *Pref) error Delete(ctx context.Context, id int) error ListPref(ctx context.Context) []*app.Pref OnePref(ctx context.Context, id int) (*app.Pref, error) } // TableName overrides the table name settings in Gorm to force a specific table name // in the database. func (m *PrefDB) TableName() string { return "prefs" } // CRUD Functions // Get returns a single Pref as a Database Model // This is more for use internally, and probably not what you want in your controllers func (m *PrefDB) Get(ctx context.Context, id int) (*Pref, error) { defer goa.MeasureSince([]string{"goa", "db", "pref", "get"}, time.Now()) var native Pref<|fim▁hole|> if err == gorm.ErrRecordNotFound { return nil, err } return &native, err } // List returns an array of Pref func (m *PrefDB) List(ctx context.Context) ([]*Pref, error) { defer goa.MeasureSince([]string{"goa", "db", "pref", "list"}, time.Now()) var objs []*Pref err := m.Db.Table(m.TableName()).Find(&objs).Error if err != nil && err != gorm.ErrRecordNotFound { return nil, err } return objs, nil } // Add creates a new record. func (m *PrefDB) Add(ctx context.Context, model *Pref) error { defer goa.MeasureSince([]string{"goa", "db", "pref", "add"}, time.Now()) err := m.Db.Create(model).Error if err != nil { goa.LogError(ctx, "error adding Pref", "error", err.Error()) return err } return nil } // Update modifies a single record. func (m *PrefDB) Update(ctx context.Context, model *Pref) error { defer goa.MeasureSince([]string{"goa", "db", "pref", "update"}, time.Now()) obj, err := m.Get(ctx, model.ID) if err != nil { goa.LogError(ctx, "error updating Pref", "error", err.Error()) return err } err = m.Db.Model(obj).Updates(model).Error return err } // Delete removes a single record. func (m *PrefDB) Delete(ctx context.Context, id int) error { defer goa.MeasureSince([]string{"goa", "db", "pref", "delete"}, time.Now()) var obj Pref err := m.Db.Delete(&obj, id).Error if err != nil { goa.LogError(ctx, "error deleting Pref", "error", err.Error()) return err } return nil }<|fim▁end|>
err := m.Db.Table(m.TableName()).Where("id = ?", id).Find(&native).Error
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any // later version. // This program is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use builtin::Builtin; use native; use std::collections::{BTreeMap, HashMap}; use util::{Address, U256, BytesRef}; pub trait Engine: Sync + Send { /// The name of this engine. fn name(&self) -> &str; /// Builtin-contracts we would like to see in the chain. /// (In principle these are just hints for the engine since that has the last word on them.) fn builtins(&self) -> &BTreeMap<Address, Builtin>; // TODO: builtin contract routing - to do this properly, it will require removing the built-in configuration-reading logic // from Spec into here and removing the Spec::builtins field. /// Determine whether a particular address is a builtin contract. fn is_builtin(&self, a: &Address) -> bool { self.builtins().contains_key(a) } /// Determine the code execution cost of the builtin contract with address `a`. /// Panics if `is_builtin(a)` is not true. fn cost_of_builtin(&self, a: &Address, input: &[u8]) -> U256 { self.builtins().get(a).expect("queried cost of nonexistent builtin").cost(input.len()) } /// Execution the builtin contract `a` on `input` and return `output`.<|fim▁hole|> } fn register(&mut self, addr: Address, contract: Box<native::Contract>); fn unregister(&mut self, addr: Address) -> Option<Box<native::Contract>>; fn get_native_contract(&self, addr: &Address) -> Option<&Box<native::Contract>>; } /// An engine which does not provide any consensus mechanism and does not seal blocks. pub struct NullEngine { builtins: BTreeMap<Address, Builtin>, contracts: HashMap<Address, Box<native::Contract>>, } impl NullEngine { /// Returns new instance of NullEngine with default VM Factory pub fn new(builtins: BTreeMap<Address, Builtin>) -> Self { let mut engine = NullEngine { builtins: builtins, contracts: HashMap::new(), }; engine.register(Address::from(0x400), Box::new(native::NowPay::new())); engine } } impl Default for NullEngine { fn default() -> Self { Self::new(Default::default()) } } impl Engine for NullEngine { fn name(&self) -> &str { "NullEngine" } fn builtins(&self) -> &BTreeMap<Address, Builtin> { &self.builtins } fn register(&mut self, addr: Address, contract: Box<native::Contract>) { self.contracts.insert(addr, contract); } fn unregister(&mut self, addr: Address) -> Option<Box<native::Contract>> { self.contracts.remove(&addr) } fn get_native_contract(&self, addr: &Address) -> Option<&Box<native::Contract>> { self.contracts.get(addr) } }<|fim▁end|>
/// Panics if `is_builtin(a)` is not true. fn execute_builtin(&self, a: &Address, input: &[u8], output: &mut BytesRef) { self.builtins().get(a).expect("attempted to execute nonexistent builtin").execute(input, output);
<|file_name|>bitcoin_bs.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="bs" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Phicoin</source> <translation>O Phicoinu</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Phicoin&lt;/b&gt; version</source> <translation>&lt;b&gt;Phicoin&lt;/b&gt; verzija</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The Phicoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adresar</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Phicoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Phicoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Phicoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Phicoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>(no label)</source> <translation type="unfinished"/> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR LITECOINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation type="unfinished"/> </message> <message> <location line="-56"/> <source>Phicoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your phicoins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation type="unfinished"/> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation type="unfinished"/> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Quit application</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Show information about Phicoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a Phicoin address</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Modify configuration options for Phicoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>Phicoin</source> <translation type="unfinished"/> </message> <message> <location line="-530"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About Phicoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your Phicoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Phicoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Phicoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Phicoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message><|fim▁hole|> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Phicoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Phicoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Phicoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Phicoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start Phicoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start Phicoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the Phicoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the Phicoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Phicoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show Phicoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Phicoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Phicoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start phicoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the Phicoin-Qt help message to get a list with possible Phicoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>Phicoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Phicoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the Phicoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Phicoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Phicoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Phicoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Phicoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Phicoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter Phicoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Phicoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Amount</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation type="unfinished"/> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <source>Today</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This week</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Last month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This year</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Range...</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>To yourself</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Other</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Min amount</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Phicoin version</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Send command to -server or phicoind</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <source>List commands</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Options:</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Specify configuration file (default: phicoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Specify pid file (default: phicoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=phicoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Phicoin Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Phicoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Phicoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>SSL options: (see the Phicoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+165"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation type="unfinished"/> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Phicoin</source> <translation type="unfinished"/> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Phicoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Phicoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="-57"/> <source>Done loading</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS><|fim▁end|>
<|file_name|>setting_dealingThread.java<|end_file_name|><|fim▁begin|>package server.thread.systemSettingsThread; import java.io.IOException; import java.io.ObjectInputStream; import java.net.Socket; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; <|fim▁hole|> import common.message.mainInfo; import common.message.node_public; import common.message.systemSettings; /** * 2011年10月 * * 山东科技大学信息学院 版权所有 * * 联系邮箱:[email protected] * * Copyright © 1999-2012, sdust, All Rights Reserved * * @author 王昌帅 * */ public class setting_dealingThread extends Thread { Socket client; systemSettings settings; Statement state1; public setting_dealingThread(Socket s_client) throws IOException, SQLException { this.state1 = serverMain.con1.createStatement(); this.client = s_client; // start(); } public void run() { try { ObjectInputStream oin = new ObjectInputStream(client.getInputStream()); settings = (systemSettings) oin.readObject(); String sql_update = "update whetherCanAdd set can = " + settings.whetherCanAdd + " where qq = '" + settings.qq + "';"; state1.execute(sql_update); state1.close(); String text = new String("您的设置已生效"); sendSystemMessageThread sender = new sendSystemMessageThread(settings.qq, text); client.close(); } catch (Exception e) { e.printStackTrace(); } } }<|fim▁end|>
import server.serverMain.serverMain; import server.thread.systemMessageThread.sendSystemMessageThread;
<|file_name|>edmsetup.py<|end_file_name|><|fim▁begin|>import sys import click import os import subprocess from packageinfo import BUILD, VERSION, NAME if "WM_PROJECT" not in os.environ: print("To run this command you must source edmenv.sh first") sys.exit(1) # The version of the buildcommon to checkout. BUILDCOMMONS_VERSION="v0.1" def bootstrap_devenv(): try: os.makedirs(".devenv") except OSError: pass if not os.path.exists(".devenv/buildrecipes-common"): subprocess.check_call([ "git", "clone", "-b", BUILDCOMMONS_VERSION, "http://github.com/simphony/buildrecipes-common.git", ".devenv/buildrecipes-common" ]) sys.path.insert(0, ".devenv/buildrecipes-common") bootstrap_devenv() import buildcommons as common # noqa workspace = common.workspace() common.edmenv_setup() @click.group() def cli(): pass @cli.command() def egg(): common.local_repo_to_edm_egg(".", name=NAME, version=VERSION, build=BUILD) with common.cd("openfoam-interface/internal-interface/wrapper"): common.run("python edmsetup.py egg") @cli.command() def upload_egg(): egg_path = "endist/{NAME}-{VERSION}-{BUILD}.egg".format( NAME=NAME, VERSION=VERSION, BUILD=BUILD) click.echo("Uploading {} to EDM repo".format(egg_path)) common.upload_egg(egg_path) with common.cd("openfoam-interface/internal-interface/wrapper"): try: common.run("python edmsetup.py upload_egg") except subprocess.CalledProcessError as e: print("Error during egg upload of submodule: {}. Continuing.".format(e))<|fim▁hole|>@cli.command() def clean(): click.echo("Cleaning") common.clean(["endist", ".devenv"]) cli()<|fim▁end|>
click.echo("Done")
<|file_name|>DeleteOrganization.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- ############################################################################### # # DeleteOrganization # Deletes an existing organization.<|fim▁hole|># # Copyright 2014, Temboo 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 temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class DeleteOrganization(Choreography): def __init__(self, temboo_session): """ Create a new instance of the DeleteOrganization Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ super(DeleteOrganization, self).__init__(temboo_session, '/Library/Zendesk/Organizations/DeleteOrganization') def new_input_set(self): return DeleteOrganizationInputSet() def _make_result_set(self, result, path): return DeleteOrganizationResultSet(result, path) def _make_execution(self, session, exec_id, path): return DeleteOrganizationChoreographyExecution(session, exec_id, path) class DeleteOrganizationInputSet(InputSet): """ An InputSet with methods appropriate for specifying the inputs to the DeleteOrganization Choreo. The InputSet object is used to specify input parameters when executing this Choreo. """ def set_Email(self, value): """ Set the value of the Email input for this Choreo. ((required, string) The email address you use to login to your Zendesk account.) """ super(DeleteOrganizationInputSet, self)._set_input('Email', value) def set_ID(self, value): """ Set the value of the ID input for this Choreo. ((required, string) ID of the organization to delete.) """ super(DeleteOrganizationInputSet, self)._set_input('ID', value) def set_Password(self, value): """ Set the value of the Password input for this Choreo. ((required, password) Your Zendesk password.) """ super(DeleteOrganizationInputSet, self)._set_input('Password', value) def set_Server(self, value): """ Set the value of the Server input for this Choreo. ((required, string) Your Zendesk domain and subdomain (e.g., temboocare.zendesk.com).) """ super(DeleteOrganizationInputSet, self)._set_input('Server', value) class DeleteOrganizationResultSet(ResultSet): """ A ResultSet with methods tailored to the values returned by the DeleteOrganization Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. """ def getJSONFromString(self, str): return json.loads(str) def get_Response(self): """ Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Zendesk.) """ return self._output.get('Response', None) def get_ResponseStatusCode(self): """ Retrieve the value for the "ResponseStatusCode" output from this Choreo execution. ((integer) The response status code returned from Zendesk.) """ return self._output.get('ResponseStatusCode', None) class DeleteOrganizationChoreographyExecution(ChoreographyExecution): def _make_result_set(self, response, path): return DeleteOrganizationResultSet(response, path)<|fim▁end|>
# # Python versions 2.6, 2.7, 3.x
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- import logging # isort:skip log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from .doc import curdoc from .export import export_png, export_svgs from .notebook import install_jupyter_hooks, install_notebook_hook, push_notebook from .output import output_file, output_notebook, reset_output from .saving import save from .showing import show #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- __all__ = ( 'curdoc', 'export_png', 'export_svgs', 'install_notebook_hook', 'push_notebook', 'output_file', 'output_notebook', 'save', 'show', ) #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- #-----------------------------------------------------------------------------<|fim▁hole|># Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- install_jupyter_hooks() del install_jupyter_hooks<|fim▁end|>
# Dev API #----------------------------------------------------------------------------- #-----------------------------------------------------------------------------
<|file_name|>0061_change_zip_code_sort_order.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from south.v2 import DataMigration class Migration(DataMigration): def forwards(self, orm): orm.Boundary.objects.filter(category='Zip Code').update(sort_order=5) def backwards(self, orm): pass models = { u'auth.group': {<|fim▁hole|> 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'treemap.audit': { 'Meta': {'object_name': 'Audit'}, 'action': ('django.db.models.fields.IntegerField', [], {}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_value': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'db_index': 'True'}), 'field': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.Instance']", 'null': 'True', 'blank': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'db_index': 'True'}), 'model_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'db_index': 'True'}), 'previous_value': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}), 'ref': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.Audit']", 'null': 'True'}), 'requires_auth': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.User']"}) }, u'treemap.benefitcurrencyconversion': { 'Meta': {'object_name': 'BenefitCurrencyConversion'}, 'co2_lb_to_currency': ('django.db.models.fields.FloatField', [], {}), 'currency_symbol': ('django.db.models.fields.CharField', [], {'max_length': '5'}), 'electricity_kwh_to_currency': ('django.db.models.fields.FloatField', [], {}), 'h20_gal_to_currency': ('django.db.models.fields.FloatField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'natural_gas_kbtu_to_currency': ('django.db.models.fields.FloatField', [], {}), 'nox_lb_to_currency': ('django.db.models.fields.FloatField', [], {}), 'o3_lb_to_currency': ('django.db.models.fields.FloatField', [], {}), 'pm10_lb_to_currency': ('django.db.models.fields.FloatField', [], {}), 'sox_lb_to_currency': ('django.db.models.fields.FloatField', [], {}), 'voc_lb_to_currency': ('django.db.models.fields.FloatField', [], {}) }, u'treemap.boundary': { 'Meta': {'object_name': 'Boundary'}, 'category': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'geom': ('django.contrib.gis.db.models.fields.MultiPolygonField', [], {'srid': '3857', 'db_column': "u'the_geom_webmercator'"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'sort_order': ('django.db.models.fields.IntegerField', [], {}) }, u'treemap.fieldpermission': { 'Meta': {'unique_together': "((u'model_name', u'field_name', u'role', u'instance'),)", 'object_name': 'FieldPermission'}, 'field_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.Instance']"}), 'model_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'permission_level': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'role': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.Role']"}) }, u'treemap.instance': { 'Meta': {'object_name': 'Instance'}, 'basemap_data': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'basemap_type': ('django.db.models.fields.CharField', [], {'default': "u'google'", 'max_length': '255'}), 'boundaries': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['treemap.Boundary']", 'null': 'True', 'blank': 'True'}), 'bounds': ('django.contrib.gis.db.models.fields.MultiPolygonField', [], {'srid': '3857'}), 'config': ('treemap.json_field.JSONField', [], {'blank': 'True'}), 'default_role': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'default_role'", 'to': u"orm['treemap.Role']"}), 'eco_benefits_conversion': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.BenefitCurrencyConversion']", 'null': 'True', 'blank': 'True'}), 'geo_rev': ('django.db.models.fields.IntegerField', [], {'default': '1'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'itree_region_default': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'logo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'url_name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'users': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['treemap.User']", 'null': 'True', 'through': u"orm['treemap.InstanceUser']", 'blank': 'True'}) }, u'treemap.instanceuser': { 'Meta': {'object_name': 'InstanceUser'}, 'admin': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.Instance']"}), 'reputation': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'role': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.Role']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.User']"}) }, u'treemap.itreecodeoverride': { 'Meta': {'unique_together': "((u'instance_species', u'region'),)", 'object_name': 'ITreeCodeOverride'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance_species': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.Species']"}), 'itree_code': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'region': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.ITreeRegion']"}) }, u'treemap.itreeregion': { 'Meta': {'object_name': 'ITreeRegion'}, 'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40'}), 'geometry': ('django.contrib.gis.db.models.fields.MultiPolygonField', [], {'srid': '3857'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, u'treemap.mapfeature': { 'Meta': {'object_name': 'MapFeature'}, 'address_city': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'address_street': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'address_zip': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}), 'feature_type': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'geom': ('django.contrib.gis.db.models.fields.PointField', [], {'srid': '3857', 'db_column': "u'the_geom_webmercator'"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.Instance']"}), 'readonly': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'udfs': ('treemap.udf.UDFField', [], {'db_index': 'True', 'blank': 'True'}) }, u'treemap.plot': { 'Meta': {'object_name': 'Plot', '_ormbases': [u'treemap.MapFeature']}, 'length': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), u'mapfeature_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['treemap.MapFeature']", 'unique': 'True', 'primary_key': 'True'}), 'owner_orig_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'width': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, u'treemap.reputationmetric': { 'Meta': {'object_name': 'ReputationMetric'}, 'action': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'approval_score': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'denial_score': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'direct_write_score': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.Instance']"}), 'model_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'treemap.role': { 'Meta': {'object_name': 'Role'}, 'default_permission': ('django.db.models.fields.IntegerField', [], {'default': '0'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.Instance']", 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'rep_thresh': ('django.db.models.fields.IntegerField', [], {}) }, u'treemap.species': { 'Meta': {'object_name': 'Species'}, 'bloom_period': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'common_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'cultivar': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'fact_sheet': ('django.db.models.fields.URLField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'fall_conspicuous': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}), 'flower_conspicuous': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}), 'fruit_period': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'gender': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'genus': ('django.db.models.fields.CharField', [], {'max_length': '255'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.Instance']"}), 'max_dbh': ('django.db.models.fields.IntegerField', [], {'default': '200'}), 'max_height': ('django.db.models.fields.IntegerField', [], {'default': '800'}), 'native_status': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}), 'other': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'otm_code': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'palatable_human': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}), 'plant_guide': ('django.db.models.fields.URLField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'species': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'udfs': ('treemap.udf.UDFField', [], {'db_index': 'True', 'blank': 'True'}), 'wildlife_value': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}) }, u'treemap.staticpage': { 'Meta': {'object_name': 'StaticPage'}, 'content': ('django.db.models.fields.TextField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.Instance']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'treemap.tree': { 'Meta': {'object_name': 'Tree'}, 'canopy_height': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'date_planted': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'date_removed': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'diameter': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'height': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.Instance']"}), 'plot': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.Plot']"}), 'readonly': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'species': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.Species']", 'null': 'True', 'blank': 'True'}), 'udfs': ('treemap.udf.UDFField', [], {'db_index': 'True', 'blank': 'True'}) }, u'treemap.treephoto': { 'Meta': {'object_name': 'TreePhoto'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.Instance']"}), 'thumbnail': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'tree': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.Tree']"}) }, u'treemap.user': { 'Meta': {'object_name': 'User'}, 'allow_email_contact': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'firstname': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'lastname': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255', 'blank': 'True'}), 'organization': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'photo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'thumbnail': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'treemap.userdefinedcollectionvalue': { 'Meta': {'object_name': 'UserDefinedCollectionValue'}, 'data': ('django_hstore.fields.DictionaryField', [], {}), 'field_definition': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.UserDefinedFieldDefinition']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model_id': ('django.db.models.fields.IntegerField', [], {}) }, u'treemap.userdefinedfielddefinition': { 'Meta': {'object_name': 'UserDefinedFieldDefinition'}, 'datatype': ('django.db.models.fields.TextField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['treemap.Instance']"}), 'iscollection': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'model_type': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) } } complete_apps = ['treemap'] symmetrical = True<|fim▁end|>
'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
<|file_name|>MBeanInvocationHandlerImpl.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.wso2.andes.server.management; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.security.AccessControlContext; import java.security.AccessController; import java.util.Set; import javax.management.Attribute; import javax.management.JMException; import javax.management.MBeanInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanServer; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.remote.JMXConnectionNotification; import javax.management.remote.JMXPrincipal; import javax.management.remote.MBeanServerForwarder; import javax.security.auth.Subject; import org.apache.log4j.Logger; import org.wso2.andes.server.logging.actors.ManagementActor; import org.wso2.andes.server.logging.messages.ManagementConsoleMessages; import org.wso2.andes.server.registry.ApplicationRegistry; import org.wso2.andes.server.security.SecurityManager; import org.wso2.andes.server.security.access.Operation; /** * This class can be used by the JMXConnectorServer as an InvocationHandler for the mbean operations. It delegates * JMX access decisions to the SecurityPlugin. */ public class MBeanInvocationHandlerImpl implements InvocationHandler, NotificationListener { private static final Logger _logger = Logger.getLogger(MBeanInvocationHandlerImpl.class);<|fim▁hole|> private MBeanServer _mbs; private static ManagementActor _logActor; public static MBeanServerForwarder newProxyInstance() { final InvocationHandler handler = new MBeanInvocationHandlerImpl(); final Class<?>[] interfaces = new Class[] { MBeanServerForwarder.class }; _logActor = new ManagementActor(ApplicationRegistry.getInstance().getRootMessageLogger()); Object proxy = Proxy.newProxyInstance(MBeanServerForwarder.class.getClassLoader(), interfaces, handler); return MBeanServerForwarder.class.cast(proxy); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final String methodName = getMethodName(method, args); if (methodName.equals("getMBeanServer")) { return _mbs; } if (methodName.equals("setMBeanServer")) { if (args[0] == null) { throw new IllegalArgumentException("Null MBeanServer"); } if (_mbs != null) { throw new IllegalArgumentException("MBeanServer object already initialized"); } _mbs = (MBeanServer) args[0]; return null; } // Retrieve Subject from current AccessControlContext AccessControlContext acc = AccessController.getContext(); Subject subject = Subject.getSubject(acc); try { // Allow operations performed locally on behalf of the connector server itself if (subject == null) { return method.invoke(_mbs, args); } if (args == null || DELEGATE.equals(args[0])) { return method.invoke(_mbs, args); } // Restrict access to "createMBean" and "unregisterMBean" to any user if (methodName.equals("createMBean") || methodName.equals("unregisterMBean")) { _logger.debug("User trying to create or unregister an MBean"); throw new SecurityException("Access denied: " + methodName); } // Allow querying available object names if (methodName.equals("queryNames")) { return method.invoke(_mbs, args); } // Retrieve JMXPrincipal from Subject Set<JMXPrincipal> principals = subject.getPrincipals(JMXPrincipal.class); if (principals == null || principals.isEmpty()) { throw new SecurityException("Access denied: no JMX principal"); } // Save the subject SecurityManager.setThreadSubject(subject); // Get the component, type and impact, which may be null String type = getType(method, args); String vhost = getVirtualHost(method, args); int impact = getImpact(method, args); // Get the security manager for the virtual host (if set) SecurityManager security; if (vhost == null) { security = ApplicationRegistry.getInstance().getSecurityManager(); } else { security = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost(vhost).getSecurityManager(); } if (isAccessMethod(methodName) || impact == MBeanOperationInfo.INFO) { // Check for read-only method invocation permission if (!security.authoriseMethod(Operation.ACCESS, type, methodName)) { throw new SecurityException("Permission denied: Access " + methodName); } } else if (isUpdateMethod(methodName)) { // Check for setting properties permission if (!security.authoriseMethod(Operation.UPDATE, type, methodName)) { throw new SecurityException("Permission denied: Update " + methodName); } } else { // Check for invoking/executing method action/operation permission if (!security.authoriseMethod(Operation.EXECUTE, type, methodName)) { throw new SecurityException("Permission denied: Execute " + methodName); } } // Actually invoke the method return method.invoke(_mbs, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } } private String getType(Method method, Object[] args) { if (args[0] instanceof ObjectName) { ObjectName object = (ObjectName) args[0]; String type = object.getKeyProperty("type"); return type; } return null; } private String getVirtualHost(Method method, Object[] args) { if (args[0] instanceof ObjectName) { ObjectName object = (ObjectName) args[0]; String vhost = object.getKeyProperty("VirtualHost"); if(vhost != null) { try { //if the name is quoted in the ObjectName, unquote it vhost = ObjectName.unquote(vhost); } catch(IllegalArgumentException e) { //ignore, this just means the name is not quoted //and can be left unchanged } } return vhost; } return null; } private String getMethodName(Method method, Object[] args) { String methodName = method.getName(); // if arguments are set, try and work out real method name if (args != null && args.length >= 1 && args[0] instanceof ObjectName) { if (methodName.equals("getAttribute")) { methodName = "get" + (String) args[1]; } else if (methodName.equals("setAttribute")) { methodName = "set" + ((Attribute) args[1]).getName(); } else if (methodName.equals("invoke")) { methodName = (String) args[1]; } } return methodName; } private int getImpact(Method method, Object[] args) { //handle invocation of other methods on mbeans if ((args[0] instanceof ObjectName) && (method.getName().equals("invoke"))) { //get invoked method name String mbeanMethod = (args.length > 1) ? (String) args[1] : null; if (mbeanMethod == null) { return -1; } try { //Get the impact attribute MBeanInfo mbeanInfo = _mbs.getMBeanInfo((ObjectName) args[0]); if (mbeanInfo != null) { MBeanOperationInfo[] opInfos = mbeanInfo.getOperations(); for (MBeanOperationInfo opInfo : opInfos) { if (opInfo.getName().equals(mbeanMethod)) { return opInfo.getImpact(); } } } } catch (JMException ex) { _logger.error("Unable to determine mbean impact for method : " + mbeanMethod, ex); } } return -1; } private boolean isAccessMethod(String methodName) { //handle standard get/query/is methods from MBeanServer return (methodName.startsWith("query") || methodName.startsWith("get") || methodName.startsWith("is")); } private boolean isUpdateMethod(String methodName) { //handle standard set methods from MBeanServer return methodName.startsWith("set"); } public void handleNotification(Notification notification, Object handback) { assert notification instanceof JMXConnectionNotification; // only RMI Connections are serviced here, Local API atta // rmi://169.24.29.116 guest 3 String[] connectionData = ((JMXConnectionNotification) notification).getConnectionId().split(" "); String user = connectionData[1]; if (notification.getType().equals(JMXConnectionNotification.OPENED)) { _logActor.message(ManagementConsoleMessages.OPEN(user)); } else if (notification.getType().equals(JMXConnectionNotification.CLOSED) || notification.getType().equals(JMXConnectionNotification.FAILED)) { _logActor.message(ManagementConsoleMessages.CLOSE()); } } }<|fim▁end|>
private final static String DELEGATE = "JMImplementation:type=MBeanServerDelegate";
<|file_name|>dewgetaway2.java<|end_file_name|><|fim▁begin|>/* * Author: patiphat mana-u-krid (dew) * E-Mail: [email protected] * facebook: https://www.facebook.com/dewddminecraft */ package dewddgetaway; import java.util.Random; import java.util.Stack; import org.bukkit.Bukkit; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.plugin.java.JavaPlugin; public class dewgetaway2 implements Listener { class chatx implements Runnable { Player p = null; String message = ""; public void run() { String m[] = message.split("\\s+"); if (m[0].equalsIgnoreCase("/dewgetawayrun")) { staticarea.dslb.loaddewsetlistblockfile(); isruntick = !isruntick; dprint.r.printAll("isruntick = " + Boolean.toString(isruntick)); getawayticktock time = new getawayticktock(); time.setName("getaway"); time.start(); return; } if (m[0].equalsIgnoreCase("/dewgetaway")) { if (m.length == 1) { // it's mean toggle your self if (p.hasPermission(pgetaway) == false) { p.sendMessage("you don't have permission " + pgetaway); return; } int getid = getfreeselect(p.getName()); nn.isrun[getid] = !nn.isrun[getid]; p.sendMessage(nn.playername[getid] + " getaway mode = " + Boolean.toString(nn.isrun[getid])); } else if (m.length == 2) { // it's mean have player name if (p.hasPermission(pgetaway) == false) { p.sendMessage("you don't have permission " + pgetaway); return; } if (m[1].equalsIgnoreCase(p.getName()) == false) { if (p.hasPermission(pgetawayother) == false) { p.sendMessage("you don't have permission " + pgetaway); return; } } if (m[1].equalsIgnoreCase("@a") == true) { // it's mean toggle everyone for (Player p2 : Bukkit.getOnlinePlayers()) { int getid = getfreeselect(p2.getName()); nn.isrun[getid] = !nn.isrun[getid]; p.sendMessage(nn.playername[getid] + " getaway mode = " + Boolean.toString(nn.isrun[getid])); } } else { // find that player for (Player p2 : Bukkit.getOnlinePlayers()) { if (p2.getName().toLowerCase() .indexOf(m[1].toLowerCase()) > -1) { int getid = getfreeselect(p2.getName()); nn.isrun[getid] = !nn.isrun[getid]; p.sendMessage(nn.playername[getid] + " getaway mode = " + Boolean.toString(nn.isrun[getid])); break; } } return; } } else if (m.length == 3) { // it's mean player 0|1 if (p.hasPermission(pgetaway) == false) { p.sendMessage("you don't have permission " + pgetaway); return; } if (m[1].equalsIgnoreCase(p.getName()) == false) { if (p.hasPermission(pgetawayother) == false) { p.sendMessage("you don't have permission " + pgetaway); return; } } if (m[2].equalsIgnoreCase("0") == false && m[2].equalsIgnoreCase("1") == false) { p.sendMessage("argument 3 must be 0 or 1"); return; } boolean togglemode = false; if (m[2].equalsIgnoreCase("1") == true) togglemode = true; if (m[1].equalsIgnoreCase("@a") == true) { // it's mean toggle everyone for (Player p2 : Bukkit.getOnlinePlayers()) { int getid = getfreeselect(p2.getName()); nn.isrun[getid] = togglemode; p.sendMessage(nn.playername[getid] + " getaway mode = " + Boolean.toString(nn.isrun[getid])); } return; } else { // find that player for (Player p2 : Bukkit.getOnlinePlayers()) { if (p2.getName().toLowerCase() .indexOf(m[1].toLowerCase()) > -1) { int getid = getfreeselect(p2.getName()); nn.isrun[getid] = togglemode; p.sendMessage(nn.playername[getid] + " getaway mode = " + Boolean.toString(nn.isrun[getid])); break; } } return; } } } } } class ddata { public String playername[]; public boolean isrun[]; } class getawaytick2 implements Runnable { public void run() { long starttime = System.currentTimeMillis(); long endtime = 0; // loop everyone // printAll("tick"); for (int i = 0; i < ddatamax; i++) { if (nn.isrun[i] == true) { // printAll("found nn = true at " + i); if (nn.playername[i].equalsIgnoreCase("") == false) { // printAll(" nn name empty == false at " + i); // search that player Player p2 = null; for (Player p3 : Bukkit.getOnlinePlayers()) { if (p3.getName().equalsIgnoreCase(nn.playername[i])) { p2 = p3; break; } } if (p2 == null) { // printAll("p2 = null " + i); continue; } // printAll("foundn p2"); double td = 0; Block b = null; Block b2 = null; for (int x = -ra; x <= ra; x++) { for (int y = -ra; y <= ra; y++) { for (int z = -ra; z <= ra; z++) { endtime = System.currentTimeMillis(); if (endtime - starttime > 250) return; if (dewddtps.tps.getTPS() < 18) { return; } b = p2.getLocation().getBlock() .getRelative(x, y, z); // b2 is looking td = distance3d(b.getX(), b.getY(), b.getZ(), p2.getLocation().getBlockX(), p2 .getLocation().getBlockY(), p2.getLocation().getBlockZ()); // printAll("radi td " + td); if (td > ra) { continue; } // check this block // b = // p2.getLocation().getBlock().getRelative(x,y,z); boolean bll = blockdewset(b.getTypeId()); if (bll == false) { continue; } // check sign for (int nx = -1; nx <= 1; nx++) { for (int ny = -1; ny <= 1; ny++) { for (int nz = -1; nz <= 1; nz++) { if (b.getRelative(nx, ny, nz) .getTypeId() == 0) { continue; } if (b.getRelative(nx, ny, nz) .getTypeId() == 63 || b.getRelative(nx, ny, nz) .getTypeId() == 68 || b.getRelative(nx, ny, nz) .getType() .isBlock() == false || blockdewset(b .getRelative( nx, ny, nz) .getTypeId()) == false) { bll = false; if (bll == false) { break; } } if (bll == false) { break; } } } if (bll == false) { break; } } if (bll == false) { continue; } // printAll("adding " + b.getX() + "," + // b.getY() + "," + b.getZ()); // move it b2 = getran(b, 1); saveb xx = new saveb(); xx.b1id = b.getTypeId(); xx.b1data = b.getData(); xx.b1x = b.getX(); xx.b1y = b.getY(); xx.b1z = b.getZ(); xx.b2id = b2.getTypeId(); xx.b2data = b2.getData(); xx.b2x = b2.getX(); xx.b2y = b2.getY(); xx.b2z = b2.getZ(); xx.w = b.getWorld().getName(); bd.push(xx); // added queue // switch that block b.setTypeId(xx.b2id); b.setData(xx.b2data); b2.setTypeId(xx.b1id); b2.setData(xx.b1data); } } } // if found player // search neary block at player it's sholud be move // or not // if yes add to queue // and loop again to should it's roll back or not // We should't use quere // We should use array } } } // after add quere dprint.r.printC("bd size = " + bd.size()); for (int gx = 0; gx <= 300; gx++) { // this is rollback block if (bd.size() == 0) { bd.trimToSize(); return; } endtime = System.currentTimeMillis(); if (endtime - starttime > 250) return; if (dewddtps.tps.getTPS() < 18) { return; } // printC("before peek " + bd.size()); saveb ttt = bd.peek(); // printC("after peek " + bd.size()); Block b3 = Bukkit.getWorld(ttt.w).getBlockAt(ttt.b1x, ttt.b1y, ttt.b1z); Block b4 = Bukkit.getWorld(ttt.w).getBlockAt(ttt.b2x, ttt.b2y, ttt.b2z); boolean isp = false; isp = isplayernearblock(b3, ra) || isplayernearblock(b4, ra); if (isp == true) { return; } ttt = bd.pop(); b3 = Bukkit.getWorld(ttt.w).getBlockAt(ttt.b1x, ttt.b1y, ttt.b1z); b4 = Bukkit.getWorld(ttt.w).getBlockAt(ttt.b2x, ttt.b2y, ttt.b2z); b4.setTypeId(ttt.b2id); b4.setData(ttt.b2data); b3.setTypeId(ttt.b1id); b3.setData(ttt.b1data); } // if not player near rollback // check // is't there have player near that block ? } } class getawayticktock extends Thread { public void run() { while (isruntick == true) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } getawaytick2 eee = new getawaytick2(); Bukkit.getScheduler().scheduleSyncDelayedTask(ac, eee); } } } class saveb { public int b1id = 0; public byte b1data = 0; public int b1x = 0; public int b1y = 0; public int b1z = 0; public int b2id = 0; public byte b2data = 0; public int b2x = 0; public int b2y = 0; public int b2z = 0; public String w = ""; } boolean isruntick = false; JavaPlugin ac = null; <|fim▁hole|> ddata nn = new ddata(); String pgetaway = "dewdd.getaway.use"; String pgetawayother = "dewdd.getaway.use.other"; Stack<saveb> bd = new Stack<saveb>(); // Queue<saveb> bd= new LinkedList<saveb>(); Random rnd = new Random(); public dewgetaway2() { nn.playername = new String[ddatamax]; nn.isrun = new boolean[ddatamax]; for (int i = 0; i < ddatamax; i++) { nn.playername[i] = ""; nn.isrun[i] = false; } } public boolean blockdewset(int blockid) { return staticarea.dslb.isdewset(blockid) && staticarea.dslb.isdewinventoryblock(blockid) == false && blockid != 0 && blockid != 8 && blockid != 9 && blockid != 10 && blockid != 11; } public int distance2d(int x1, int z1, int x2, int z2) { double t1 = Math.pow(x1 - x2, 2); double t2 = Math.pow(z1 - z2, 2); double t3 = Math.pow(t1 + t2, 0.5); int t4 = (int) t3; return t4; } public double distance3d(int x1, int y1, int z1, int x2, int y2, int z2) { double t1 = Math.pow(x1 - x2, 2); double t2 = Math.pow(z1 - z2, 2); double t3 = Math.pow(y1 - y2, 2); double t5 = Math.pow(t1 + t2 + t3, 0.5); return t5; } @EventHandler public void eventja(PlayerCommandPreprocessEvent event) { chatx a = new chatx(); a.p = event.getPlayer(); a.message = event.getMessage(); Bukkit.getScheduler().scheduleSyncDelayedTask(ac, a); } public int getfreeselect(String sname) { // clean exited player boolean foundx = false; for (int i = 0; i < ddatamax; i++) { foundx = false; for (Player pr : Bukkit.getOnlinePlayers()) { if (nn.playername[i].equalsIgnoreCase(pr.getName())) { foundx = true; break; } } if (foundx == false) { nn.playername[i] = ""; nn.isrun[i] = false; } } // clean for (int i = 0; i < ddatamax; i++) { if (nn.playername[i].equalsIgnoreCase(sname)) { return i; } } for (int i = 0; i < ddatamax; i++) { if (nn.playername[i].equalsIgnoreCase("")) { nn.playername[i] = sname; return i; } } return -1; } public Block getran(Block b, int ra) { Block b2 = b; int tx = 0; int ty = 0; int tz = 0; int counttry = 0; do { counttry++; tx = rnd.nextInt(ra * 2) - (ra * 1); ty = rnd.nextInt(ra * 2) - (ra * 1); tz = rnd.nextInt(ra * 2) - (ra * 1); if (ty < 1) ty = 1; if (ty > 254) ty = 254; b2 = b.getRelative(tx, ty, tz); if (counttry >= 100) { counttry = 0; ra = ra + 1; } } while (b2.getLocation().distance(b.getLocation()) < ra || b2 == b || b2.getTypeId() != 0); return b2; } public boolean isplayernearblock(Block bh, int ra) { for (Player uu : bh.getWorld().getPlayers()) { if (nn.isrun[getfreeselect(uu.getName())] == false) continue; if (uu.getLocation().distance(bh.getLocation()) <= ra) { return true; } } return false; } } // class<|fim▁end|>
int ra = 5; int ddatamax = 29;
<|file_name|>HHPH2013data_to_burnman.py<|end_file_name|><|fim▁begin|># BurnMan - a lower mantle toolkit # Copyright (C) 2012-2014, Myhill, R., Heister, T., Unterborn, C., Rose, I. and Cottaar, S.<|fim▁hole|> import sys def read_dataset(datafile): f=open(datafile,'r') ds=[] for line in f: ds.append(line.decode('utf-8').split()) return ds ds=read_dataset('HHPH2013_endmembers.dat') print '# BurnMan - a lower mantle toolkit' print '# Copyright (C) 2012, 2013, Heister, T., Unterborn, C., Rose, I. and Cottaar, S.' print '# Released under GPL v2 or later.' print '' print '"""' print 'HHPH_2013' print 'Minerals from Holland et al 2013 and references therein' print 'The values in this document are all in S.I. units,' print 'unlike those in the original paper' print 'File autogenerated using HHPHdata_to_burnman.py' print '"""' print '' print 'from burnman.mineral import Mineral' print 'from burnman.solidsolution import SolidSolution' print 'from burnman.solutionmodel import *' print 'from burnman.processchemistry import read_masses, dictionarize_formula, formula_mass' print '' print 'atomic_masses=read_masses()' print '' print '"""' print 'ENDMEMBERS' print '"""' print '' param_scales = [ -1., -1., #not nubmers, so we won't scale 1.e3, 1.e3, #kJ -> J 1.0, # J/K/mol 1.e-5, # kJ/kbar/mol -> m^3/mol 1.e3, 1.e-2, 1.e3, 1.e3, # kJ -> J and table conversion for b 1.e-5, # table conversion 1.e8, # kbar -> Pa 1.0, # no scale for K'0 1.e-8] #GPa -> Pa # no scale for eta_s formula='0' for idx, m in enumerate(ds): if idx == 0: param_names=m else: print 'class', m[0].lower(), '(Mineral):' print ' def __init__(self):' print ''.join([' formula=\'',m[1],'\'']) print ' formula = dictionarize_formula(formula)' print ' self.params = {' print ''.join([' \'name\': \'', m[0], '\',']) print ' \'formula\': formula,' print ' \'equation_of_state\': \'hp_tmt\',' for pid, param in enumerate(m): if pid > 1 and pid != 3 and pid<6: print ' \''+param_names[pid]+'\':', float(param)*param_scales[pid], ',' print ' \'Cp\':', [round(float(m[i])*param_scales[i],10) for i in [6, 7, 8, 9]], ',' for pid, param in enumerate(m): if pid > 9: print ' \''+param_names[pid]+'\':', float(param)*param_scales[pid], ',' print ' \'n\': sum(formula.values()),' print ' \'molar_mass\': formula_mass(formula, atomic_masses)}' print '' print ' self.uncertainties = {' print ' \''+param_names[3]+'\':', float(m[3])*param_scales[3], '}' print ' Mineral.__init__(self)' print ''<|fim▁end|>
# Released under GPL v2 or later. # This is a standalone program that converts a tabulated version of the Stixrude and Lithgow-Bertelloni data format into the standard burnman format (printed to stdout)
<|file_name|>writer-opts.js<|end_file_name|><|fim▁begin|>'use strict' const Q = require(`q`) const readFile = Q.denodeify(require(`fs`).readFile) const resolve = require(`path`).resolve module.exports = Q.all([ readFile(resolve(__dirname, './templates/template.hbs'), 'utf-8'), readFile(resolve(__dirname, './templates/header.hbs'), 'utf-8'), readFile(resolve(__dirname, './templates/commit.hbs'), 'utf-8') ]) .spread((template, header, commit) => { const writerOpts = getWriterOpts() writerOpts.mainTemplate = template writerOpts.headerPartial = header writerOpts.commitPartial = commit return writerOpts }) function getWriterOpts () { return { transform: (commit) => { if (!commit.language) { return } if (typeof commit.hash === `string`) {<|fim▁hole|> return commit }, groupBy: `language`, commitGroupsSort: `title`, commitsSort: [`language`, `type`, `message`] } }<|fim▁end|>
commit.hash = commit.hash.substring(0, 7) }
<|file_name|>AbstractIndexInfoOptimizer.java<|end_file_name|><|fim▁begin|>/* * Copyright 2004-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0<|fim▁hole|> * 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.compass.core.lucene.engine.optimizer; import java.io.IOException; import org.apache.lucene.index.LuceneSubIndexInfo; import org.compass.core.engine.SearchEngineException; import org.compass.core.lucene.engine.manager.LuceneSearchEngineIndexManager; /** * @author kimchy */ public abstract class AbstractIndexInfoOptimizer extends AbstractOptimizer { protected void doOptimize(String subIndex) throws SearchEngineException { LuceneSubIndexInfo indexInfo = doGetIndexInfo(subIndex); if (indexInfo == null) { return; } doOptimize(subIndex, indexInfo); } protected void doForceOptimize(String subIndex) throws SearchEngineException { LuceneSubIndexInfo indexInfo = doGetIndexInfo(subIndex); if (indexInfo == null) { return; } doForceOptimize(subIndex, indexInfo); } protected LuceneSubIndexInfo doGetIndexInfo(String subIndex) { LuceneSearchEngineIndexManager indexManager = getSearchEngineFactory().getLuceneIndexManager(); LuceneSubIndexInfo indexInfo; try { indexInfo = LuceneSubIndexInfo.getIndexInfo(subIndex, indexManager); } catch (IOException e) { throw new SearchEngineException("Failed to read index info for sub index [" + subIndex + "]", e); } if (indexInfo == null) { // no index data, simply continue return null; } if (!isRunning()) { return null; } return indexInfo; } protected abstract void doOptimize(String subIndex, LuceneSubIndexInfo indexInfo) throws SearchEngineException; protected abstract void doForceOptimize(String subIndex, LuceneSubIndexInfo indexInfo) throws SearchEngineException; }<|fim▁end|>
*
<|file_name|>glib.rs<|end_file_name|><|fim▁begin|>// Copyleft (ↄ) meh. <[email protected]> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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. // // cancer is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of<|fim▁hole|>// GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with cancer. If not, see <http://www.gnu.org/licenses/>. use libc::c_void; #[repr(C)] pub struct GList { pub data: *mut c_void, pub next: *mut GList, pub prev: *mut GList, } extern "C" { pub fn g_list_free(ptr: *mut GList); pub fn g_object_unref(ptr: *mut c_void); pub fn g_object_ref(ptr: *mut c_void) -> *mut c_void; }<|fim▁end|>
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
<|file_name|>register.rs<|end_file_name|><|fim▁begin|>use super::super::{IrcMsg, numerics}; use super::super::message_types::server; pub type RegisterResult = Result<(), RegisterError>; #[derive(Clone, Debug)] pub struct RegisterError { pub errtype: RegisterErrorType, pub message: IrcMsg, } impl RegisterError { pub fn should_pick_new_nickname(&self) -> bool { match server::IncomingMsg::from_msg(self.message.clone()) { server::IncomingMsg::Numeric(num, _) => {<|fim▁hole|> } } } #[derive(Clone, Debug, Copy)] pub enum RegisterErrorType { NoNicknameGiven, NicknameInUse, UnavailableResource, ErroneousNickname, NicknameCollision, Restricted, } impl RegisterErrorType { pub fn is_known_error(result: i32) -> bool { RegisterErrorType::from_ord_known(result).is_some() } pub fn from_ord_known(result: i32) -> Option<RegisterErrorType> { match result { numerics::ERR_NONICKNAMEGIVEN => Some(RegisterErrorType::NoNicknameGiven), numerics::ERR_NICKNAMEINUSE => Some(RegisterErrorType::NicknameInUse), numerics::ERR_UNAVAILRESOURCE => Some(RegisterErrorType::UnavailableResource), numerics::ERR_ERRONEUSNICKNAME => Some(RegisterErrorType::ErroneousNickname), numerics::ERR_NICKCOLLISION => Some(RegisterErrorType::NicknameCollision), numerics::ERR_RESTRICTED => Some(RegisterErrorType::Restricted), _ => None } } }<|fim▁end|>
numerics::ERR_NICKNAMEINUSE == (num as i32) }, _ => false
<|file_name|>restoreObject.py<|end_file_name|><|fim▁begin|>from django.core.management.base import BaseCommand, CommandError import __future__ from ModelTracker.models import History import datetime from django.apps import apps def getModel(table_name): return next((m for m in apps.get_models() if m._meta.db_table==table_name), None) class Command(BaseCommand): help = 'Restore Object to old status' <|fim▁hole|> def add_arguments(self, parser): parser.add_argument('--id', nargs='?', type=str,default=None) parser.add_argument("--state",type=str,nargs='?',default="new") def handle(self, *args, **options): if not options.get("id",None): print ("Change ID is needed") exit(1) print (options) h = History.objects.get(id=int(options["id"])) model = getModel(h.table) if model == None: print("Can't find the Model") exit(2) d=[f.name for f in model._meta.get_fields()] if options["state"]=="old": state=h.old_state else: state=h.new_state keys2del=[] for key in state: if (key.startswith("_") and "_cache" in key) or (key not in d and not ("_id" in key and key[:-3] in d)): keys2del.append(key) if type(state[key])==type({}): if state[key].get("_type",None) == "datetime": state[key]=datetime.datetime.strptime(state[key]["value"],"%Y-%m-%d %H:%M:%S") elif state[key].get("_type",None) == "date": state[key]=datetime.datetime.strptime(state[key]["value"],"%Y-%m-%d") for key in keys2del: del state[key] print(state) m=model(**state) m.save("CLI",event_name="Restore Record to %s (%s)"%(options["id"],options["state"]))<|fim▁end|>
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Utilities for defining models """ import operator from typing import Any, Callable, Type class KeyBasedCompareMixin: """Provides comparison capabilities that is based on a key""" __slots__ = ["_compare_key", "_defining_class"] def __init__(self, key, defining_class): # type: (Any, Type[KeyBasedCompareMixin]) -> None self._compare_key = key self._defining_class = defining_class def __hash__(self): # type: () -> int return hash(self._compare_key) <|fim▁hole|> def __le__(self, other): # type: (Any) -> bool return self._compare(other, operator.__le__) def __gt__(self, other): # type: (Any) -> bool return self._compare(other, operator.__gt__) def __ge__(self, other): # type: (Any) -> bool return self._compare(other, operator.__ge__) def __eq__(self, other): # type: (Any) -> bool return self._compare(other, operator.__eq__) def _compare(self, other, method): # type: (Any, Callable[[Any, Any], bool]) -> bool if not isinstance(other, self._defining_class): return NotImplemented return method(self._compare_key, other._compare_key)<|fim▁end|>
def __lt__(self, other): # type: (Any) -> bool return self._compare(other, operator.__lt__)
<|file_name|>pad_controller.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2018, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use glib::IsA; use glib::translate::*; use PadActionEntry; use PadController; pub trait PadControllerExtManual: 'static { #[cfg(any(feature = "v3_22", feature = "dox"))] fn set_action_entries(&self, entries: &[PadActionEntry]);<|fim▁hole|> #[cfg(any(feature = "v3_22", feature = "dox"))] fn set_action_entries(&self, entries: &[PadActionEntry]) { let n_entries = entries.len() as i32; let entries = entries.as_ptr(); unsafe { ffi::gtk_pad_controller_set_action_entries(self.as_ref().to_glib_none().0, mut_override(entries as *const _), n_entries); } } }<|fim▁end|>
} impl<O: IsA<PadController>> PadControllerExtManual for O {
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Profile', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('point', models.IntegerField(default=1)), ('lastcall', models.DateTimeField(auto_now_add=True)), ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)), ],<|fim▁hole|><|fim▁end|>
), ]
<|file_name|>index.js<|end_file_name|><|fim▁begin|>'use strict'; const expect = require('chai').expect; const deepfind = require('../index'); const simpleFixture = { 'key': 'value' }; const complexFixture = { 'key1': { 'key': 'value1' }, 'key2': { 'key': 'value2' }, 'key3': { 'key': 'value3' } }; describe('deepfind', () => { it('should throw an error when given no object', () => { expect(() => deepfind(null, 'key')).to.throw('deepfind must be supplied an object'); }); it('should throw an error when given no key', () => { expect(() => deepfind({}, null)).to.throw('deepfind must be supplied a key'); }); it('should return an empty array when no key is found', () => { expect(deepfind({}, 'key')).to.be.an.array; expect(deepfind({}, 'key')).to.be.empty; }); it('should return an array when one value matches', () => {<|fim▁hole|> it('should return an array when multiple values match', () => { expect(deepfind(complexFixture, 'key')).to.be.an.array; expect(deepfind(complexFixture, 'key')).to.deep.equal(['value1', 'value2', 'value3']) }); });<|fim▁end|>
expect(deepfind(simpleFixture, 'key')).to.be.an.array; expect(deepfind(simpleFixture, 'key')).to.deep.equal(['value']); });
<|file_name|>interval.cc<|end_file_name|><|fim▁begin|>// Copyright 2021 The XLS Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "xls/ir/interval.h" #include <random> namespace xls { void Interval::EnsureValid() const { XLS_CHECK(is_valid_); XLS_CHECK_EQ(lower_bound_.bit_count(), upper_bound_.bit_count()); } int64_t Interval::BitCount() const { EnsureValid(); return lower_bound_.bit_count(); } Interval Interval::Maximal(int64_t bit_width) { return Interval(UBits(0, bit_width), Bits::AllOnes(bit_width)); } Interval Interval::Precise(const Bits& bits) { return Interval(bits, bits); } Interval Interval::ZeroExtend(int64_t bit_width) const { XLS_CHECK_GE(bit_width, BitCount()); return Interval(bits_ops::ZeroExtend(LowerBound(), bit_width), bits_ops::ZeroExtend(UpperBound(), bit_width)); } bool Interval::Overlaps(const Interval& lhs, const Interval& rhs) { XLS_CHECK_EQ(lhs.BitCount(), rhs.BitCount()); XLS_CHECK(!lhs.IsImproper()); XLS_CHECK(!rhs.IsImproper()); if (lhs.BitCount() == 0) { // The unique zero-width interval overlaps with itself. return true; } if (rhs < lhs) { return Overlaps(rhs, lhs); } return bits_ops::UGreaterThanOrEqual(lhs.upper_bound_, rhs.lower_bound_); } bool Interval::Disjoint(const Interval& lhs, const Interval& rhs) { return !Overlaps(lhs, rhs); } bool Interval::Abuts(const Interval& lhs, const Interval& rhs) { XLS_CHECK_EQ(lhs.BitCount(), rhs.BitCount()); XLS_CHECK(!lhs.IsImproper()); XLS_CHECK(!rhs.IsImproper()); if (lhs.BitCount() == 0) { // The unique zero-width interval does not abut itself. return false; } if (rhs < lhs) { return Abuts(rhs, lhs); } // If the two intervals overlap, they definitely don't abut. // This takes care of cases like // `Interval::Abuts(Interval::Maximal(n), Interval::Maximal(n))` // and any others I haven't thought of. if (Interval::Overlaps(lhs, rhs)) { return false; } Bits one = UBits(1, lhs.BitCount()); return bits_ops::UEqual(bits_ops::Add(lhs.upper_bound_, one), rhs.lower_bound_); } Interval Interval::ConvexHull(const Interval& lhs, const Interval& rhs) { XLS_CHECK_EQ(lhs.BitCount(), rhs.BitCount()); XLS_CHECK(!lhs.IsImproper()); XLS_CHECK(!rhs.IsImproper()); if (lhs.BitCount() == 0) { // The convex hull of any set of zero-width intervals is of course the // unique zero-width interval. return Interval(Bits(), Bits()); } Interval result = lhs; if (bits_ops::ULessThan(rhs.lower_bound_, result.lower_bound_)) { result.lower_bound_ = rhs.lower_bound_; } if (bits_ops::UGreaterThan(rhs.upper_bound_, result.upper_bound_)) { result.upper_bound_ = rhs.upper_bound_; } return result; } absl::optional<Interval> Interval::Intersect(const Interval& lhs, const Interval& rhs) { XLS_CHECK_EQ(lhs.BitCount(), rhs.BitCount()); XLS_CHECK(!lhs.IsImproper()); XLS_CHECK(!rhs.IsImproper()); if (!Interval::Overlaps(lhs, rhs)) { return absl::nullopt; } Bits lower = lhs.LowerBound(); if (bits_ops::UGreaterThan(rhs.LowerBound(), lower)) { lower = rhs.LowerBound(); } Bits upper = lhs.UpperBound(); if (bits_ops::ULessThan(rhs.UpperBound(), upper)) { upper = rhs.UpperBound(); } return Interval(lower, upper); } std::vector<Interval> Interval::Difference(const Interval& lhs, const Interval& rhs) { XLS_CHECK_EQ(lhs.BitCount(), rhs.BitCount()); XLS_CHECK(!lhs.IsImproper()); XLS_CHECK(!rhs.IsImproper()); if (!Interval::Overlaps(lhs, rhs)) { // X - Y = X when X ∩ Y = ø return {lhs}; } std::vector<Interval> result; if (bits_ops::ULessThan(lhs.LowerBound(), rhs.LowerBound())) { result.push_back( Interval(lhs.LowerBound(), bits_ops::Sub(rhs.LowerBound(), UBits(1, rhs.BitCount())))); } if (bits_ops::ULessThan(rhs.UpperBound(), lhs.UpperBound())) { result.push_back( Interval(bits_ops::Add(rhs.UpperBound(), UBits(1, rhs.BitCount())), lhs.UpperBound())); } return result; } std::vector<Interval> Interval::Complement(const Interval& interval) { return Difference(Maximal(interval.BitCount()), interval); } bool Interval::IsSubsetOf(const Interval& lhs, const Interval& rhs) { XLS_CHECK_EQ(lhs.BitCount(), rhs.BitCount()); XLS_CHECK(!lhs.IsImproper()); XLS_CHECK(!rhs.IsImproper()); return bits_ops::ULessThanOrEqual(rhs.LowerBound(), lhs.LowerBound()) && bits_ops::UGreaterThanOrEqual(rhs.UpperBound(), lhs.UpperBound()); } bool Interval::ForEachElement(std::function<bool(const Bits&)> callback) const { EnsureValid(); if (bits_ops::UEqual(lower_bound_, upper_bound_)) { return callback(lower_bound_); } Bits value = lower_bound_; Bits zero = UBits(0, BitCount()); Bits one = UBits(1, BitCount()); Bits max = Bits::AllOnes(BitCount()); if (bits_ops::UGreaterThan(lower_bound_, upper_bound_)) { while (true) { if (callback(value)) { return true; } if (bits_ops::UEqual(value, max)) { break; } value = bits_ops::Add(value, one); } value = zero; } while (true) { if (callback(value)) { return true; } if (bits_ops::UEqual(value, upper_bound_)) { break; } value = bits_ops::Add(value, one); } return false; } std::vector<Bits> Interval::Elements() const { std::vector<Bits> result; ForEachElement([&result](const Bits& value) { result.push_back(value); return false; }); return result; } Bits Interval::SizeBits() const { EnsureValid(); if (bits_ops::UGreaterThan(lower_bound_, upper_bound_)) { Bits zero = UBits(0, BitCount()); Bits max = Bits::AllOnes(BitCount()); Bits x = Interval(lower_bound_, max).SizeBits();<|fim▁hole|> Bits y = Interval(zero, upper_bound_).SizeBits(); return bits_ops::Add(x, y); } int64_t padded_size = BitCount() + 1; Bits difference = bits_ops::Sub(upper_bound_, lower_bound_); return bits_ops::Add(UBits(1, padded_size), bits_ops::ZeroExtend(difference, padded_size)); } absl::optional<int64_t> Interval::Size() const { absl::StatusOr<uint64_t> size_status = SizeBits().ToUint64(); if (size_status.ok()) { uint64_t size = *size_status; if (size > static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) { return absl::nullopt; } return static_cast<int64_t>(size); } return absl::nullopt; } bool Interval::IsImproper() const { EnsureValid(); if (BitCount() == 0) { return false; } return bits_ops::ULessThan(upper_bound_, lower_bound_); } bool Interval::IsPrecise() const { EnsureValid(); if (BitCount() == 0) { return true; } return lower_bound_ == upper_bound_; } absl::optional<Bits> Interval::GetPreciseValue() const { if (!IsPrecise()) { return absl::nullopt; } return lower_bound_; } bool Interval::IsMaximal() const { EnsureValid(); if (BitCount() == 0) { return true; } // This works because `bits_ops::Add` overflows, and correctly handles // improper intervals. Bits upper_plus_one = bits_ops::Add(upper_bound_, UBits(1, BitCount())); return bits_ops::UEqual(upper_plus_one, lower_bound_); } bool Interval::Covers(const Bits& point) const { EnsureValid(); XLS_CHECK_EQ(BitCount(), point.bit_count()); if (BitCount() == 0) { return true; } if (IsImproper()) { return bits_ops::ULessThanOrEqual(lower_bound_, point) || bits_ops::ULessThanOrEqual(point, upper_bound_); } else { return bits_ops::ULessThanOrEqual(lower_bound_, point) && bits_ops::ULessThanOrEqual(point, upper_bound_); } } bool Interval::CoversZero() const { return Covers(UBits(0, BitCount())); } bool Interval::CoversOne() const { return (BitCount() > 0) && Covers(UBits(1, BitCount())); } bool Interval::CoversMax() const { return Covers(Bits::AllOnes(BitCount())); } std::string Interval::ToString() const { FormatPreference pref = FormatPreference::kDefault; return absl::StrFormat("[%s, %s]", lower_bound_.ToString(pref, false), upper_bound_.ToString(pref, false)); } Interval Interval::Random(uint32_t seed, int64_t bit_count) { std::mt19937 gen(seed); std::uniform_int_distribution<int32_t> distrib(0, 255); int64_t num_bytes = (bit_count / 8) + ((bit_count % 8 == 0) ? 0 : 1); std::vector<uint8_t> start_bytes(num_bytes); for (int64_t i = 0; i < num_bytes; ++i) { start_bytes[i] = distrib(gen); } std::vector<uint8_t> end_bytes(num_bytes); for (int64_t i = 0; i < num_bytes; ++i) { end_bytes[i] = distrib(gen); } return Interval(Bits::FromBytes(start_bytes, bit_count), Bits::FromBytes(end_bytes, bit_count)); } } // namespace xls<|fim▁end|>
<|file_name|>listenconn.go<|end_file_name|><|fim▁begin|>package core import ( "net"; "os"; "log"; ) type acceptFunc func(net.Conn) type errorFunc func(os.Error) // A listen socket. type listenConn struct { listen net.Listener; accept acceptFunc; error errorFunc;<|fim▁hole|> l := &listenConn{listen, accept, error}; go l.run(); return l; } func (l *listenConn) run() { log.Stderrf("listening on %s\n", l.listen.Addr()); // TODO a way to shut this down for { conn, err := l.listen.Accept(); if err != nil { log.Stderrf("accept failed: %s\n", err); l.listen.Close(); if l.error != nil { l.error(err); } return } l.accept(conn); } } func (l *listenConn) Addr() net.Addr { return l.listen.Addr() }<|fim▁end|>
} func newListenConn(listen net.Listener, accept acceptFunc, error errorFunc) *listenConn {
<|file_name|>collapsible_match.rs<|end_file_name|><|fim▁begin|>use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::visitors::LocalUsedVisitor; use clippy_utils::{higher, is_lang_ctor, is_unit_expr, path_to_local, peel_ref_operators, SpanlessEq}; use if_chain::if_chain; use rustc_hir::LangItem::OptionNone; use rustc_hir::{Arm, Expr, ExprKind, Guard, HirId, MatchSource, Pat, PatKind, StmtKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{MultiSpan, Span}; declare_clippy_lint! { /// ### What it does /// Finds nested `match` or `if let` expressions where the patterns may be "collapsed" together /// without adding any branches. /// /// Note that this lint is not intended to find _all_ cases where nested match patterns can be merged, but only /// cases where merging would most likely make the code more readable. /// /// ### Why is this bad? /// It is unnecessarily verbose and complex. /// /// ### Example /// ```rust /// fn func(opt: Option<Result<u64, String>>) { /// let n = match opt { /// Some(n) => match n { /// Ok(n) => n, /// _ => return,<|fim▁hole|> /// } /// ``` /// Use instead: /// ```rust /// fn func(opt: Option<Result<u64, String>>) { /// let n = match opt { /// Some(Ok(n)) => n, /// _ => return, /// }; /// } /// ``` pub COLLAPSIBLE_MATCH, style, "Nested `match` or `if let` expressions where the patterns may be \"collapsed\" together." } declare_lint_pass!(CollapsibleMatch => [COLLAPSIBLE_MATCH]); impl<'tcx> LateLintPass<'tcx> for CollapsibleMatch { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'tcx>) { match IfLetOrMatch::parse(cx, expr) { Some(IfLetOrMatch::Match(_, arms, _)) => { if let Some(els_arm) = arms.iter().rfind(|arm| arm_is_wild_like(cx, arm)) { for arm in arms { check_arm(cx, true, arm.pat, arm.body, arm.guard.as_ref(), Some(els_arm.body)); } } } Some(IfLetOrMatch::IfLet(_, pat, body, els)) => { check_arm(cx, false, pat, body, None, els); } None => {} } } } fn check_arm<'tcx>( cx: &LateContext<'tcx>, outer_is_match: bool, outer_pat: &'tcx Pat<'tcx>, outer_then_body: &'tcx Expr<'tcx>, outer_guard: Option<&'tcx Guard<'tcx>>, outer_else_body: Option<&'tcx Expr<'tcx>> ) { let inner_expr = strip_singleton_blocks(outer_then_body); if_chain! { if let Some(inner) = IfLetOrMatch::parse(cx, inner_expr); if let Some((inner_scrutinee, inner_then_pat, inner_else_body)) = match inner { IfLetOrMatch::IfLet(scrutinee, pat, _, els) => Some((scrutinee, pat, els)), IfLetOrMatch::Match(scrutinee, arms, ..) => if_chain! { // if there are more than two arms, collapsing would be non-trivial if arms.len() == 2 && arms.iter().all(|a| a.guard.is_none()); // one of the arms must be "wild-like" if let Some(wild_idx) = arms.iter().rposition(|a| arm_is_wild_like(cx, a)); then { let (then, els) = (&arms[1 - wild_idx], &arms[wild_idx]); Some((scrutinee, then.pat, Some(els.body))) } else { None } }, }; if outer_pat.span.ctxt() == inner_scrutinee.span.ctxt(); // match expression must be a local binding // match <local> { .. } if let Some(binding_id) = path_to_local(peel_ref_operators(cx, inner_scrutinee)); if !pat_contains_or(inner_then_pat); // the binding must come from the pattern of the containing match arm // ..<local>.. => match <local> { .. } if let Some(binding_span) = find_pat_binding(outer_pat, binding_id); // the "else" branches must be equal if match (outer_else_body, inner_else_body) { (None, None) => true, (None, Some(e)) | (Some(e), None) => is_unit_expr(e), (Some(a), Some(b)) => SpanlessEq::new(cx).eq_expr(a, b), }; // the binding must not be used in the if guard let mut used_visitor = LocalUsedVisitor::new(cx, binding_id); if outer_guard.map_or(true, |(Guard::If(e) | Guard::IfLet(_, e))| !used_visitor.check_expr(e)); // ...or anywhere in the inner expression if match inner { IfLetOrMatch::IfLet(_, _, body, els) => { !used_visitor.check_expr(body) && els.map_or(true, |e| !used_visitor.check_expr(e)) }, IfLetOrMatch::Match(_, arms, ..) => !arms.iter().any(|arm| used_visitor.check_arm(arm)), }; then { let msg = format!( "this `{}` can be collapsed into the outer `{}`", if matches!(inner, IfLetOrMatch::Match(..)) { "match" } else { "if let" }, if outer_is_match { "match" } else { "if let" }, ); span_lint_and_then( cx, COLLAPSIBLE_MATCH, inner_expr.span, &msg, |diag| { let mut help_span = MultiSpan::from_spans(vec![binding_span, inner_then_pat.span]); help_span.push_span_label(binding_span, "replace this binding".into()); help_span.push_span_label(inner_then_pat.span, "with this pattern".into()); diag.span_help(help_span, "the outer pattern can be modified to include the inner pattern"); }, ); } } } fn strip_singleton_blocks<'hir>(mut expr: &'hir Expr<'hir>) -> &'hir Expr<'hir> { while let ExprKind::Block(block, _) = expr.kind { match (block.stmts, block.expr) { ([stmt], None) => match stmt.kind { StmtKind::Expr(e) | StmtKind::Semi(e) => expr = e, _ => break, }, ([], Some(e)) => expr = e, _ => break, } } expr } enum IfLetOrMatch<'hir> { Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource), /// scrutinee, pattern, then block, else block IfLet(&'hir Expr<'hir>, &'hir Pat<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>), } impl<'hir> IfLetOrMatch<'hir> { fn parse(cx: &LateContext<'_>, expr: &Expr<'hir>) -> Option<Self> { match expr.kind { ExprKind::Match(expr, arms, source) => Some(Self::Match(expr, arms, source)), _ => higher::IfLet::hir(cx, expr).map(|higher::IfLet { let_expr, let_pat, if_then, if_else }| { Self::IfLet(let_expr, let_pat, if_then, if_else) }) } } } /// A "wild-like" arm has a wild (`_`) or `None` pattern and no guard. Such arms can be "collapsed" /// into a single wild arm without any significant loss in semantics or readability. fn arm_is_wild_like(cx: &LateContext<'_>, arm: &Arm<'_>) -> bool { if arm.guard.is_some() { return false; } match arm.pat.kind { PatKind::Binding(..) | PatKind::Wild => true, PatKind::Path(ref qpath) => is_lang_ctor(cx, qpath, OptionNone), _ => false, } } fn find_pat_binding(pat: &Pat<'_>, hir_id: HirId) -> Option<Span> { let mut span = None; pat.walk_short(|p| match &p.kind { // ignore OR patterns PatKind::Or(_) => false, PatKind::Binding(_bm, _, _ident, _) => { let found = p.hir_id == hir_id; if found { span = Some(p.span); } !found }, _ => true, }); span } fn pat_contains_or(pat: &Pat<'_>) -> bool { let mut result = false; pat.walk(|p| { let is_or = matches!(p.kind, PatKind::Or(_)); result |= is_or; !is_or }); result }<|fim▁end|>
/// } /// None => return, /// };
<|file_name|>viewport.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/. */ //! The [`@viewport`][at] at-rule and [`meta`][meta] element. //! //! [at]: https://drafts.csswg.org/css-device-adapt/#atviewport-rule //! [meta]: https://drafts.csswg.org/css-device-adapt/#viewport-meta #![deny(missing_docs)]<|fim▁hole|>use app_units::Au; use cssparser::{AtRuleParser, DeclarationListParser, DeclarationParser, Parser, parse_important}; use cssparser::ToCss as ParserToCss; use euclid::scale_factor::ScaleFactor; use euclid::size::TypedSize2D; use media_queries::Device; use parser::{ParserContext, log_css_error}; use std::ascii::AsciiExt; use std::borrow::Cow; use std::fmt; use std::iter::Enumerate; use std::str::Chars; use style_traits::ToCss; use style_traits::viewport::{Orientation, UserZoom, ViewportConstraints, Zoom}; use stylesheets::{Stylesheet, Origin}; use values::computed::{Context, ToComputedValue}; use values::specified::{NoCalcLength, LengthOrPercentageOrAuto, ViewportPercentageLength}; macro_rules! declare_viewport_descriptor { ( $( $variant_name: expr => $variant: ident($data: ident), )+ ) => { declare_viewport_descriptor_inner!([] [ $( $variant_name => $variant($data), )+ ] 0); }; } macro_rules! declare_viewport_descriptor_inner { ( [ $( $assigned_variant_name: expr => $assigned_variant: ident($assigned_data: ident) = $assigned_discriminant: expr, )* ] [ $next_variant_name: expr => $next_variant: ident($next_data: ident), $( $variant_name: expr => $variant: ident($data: ident), )* ] $next_discriminant: expr ) => { declare_viewport_descriptor_inner! { [ $( $assigned_variant_name => $assigned_variant($assigned_data) = $assigned_discriminant, )* $next_variant_name => $next_variant($next_data) = $next_discriminant, ] [ $( $variant_name => $variant($data), )* ] $next_discriminant + 1 } }; ( [ $( $assigned_variant_name: expr => $assigned_variant: ident($assigned_data: ident) = $assigned_discriminant: expr, )* ] [ ] $number_of_variants: expr ) => { #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[allow(missing_docs)] pub enum ViewportDescriptor { $( $assigned_variant($assigned_data), )+ } const VIEWPORT_DESCRIPTOR_VARIANTS: usize = $number_of_variants; impl ViewportDescriptor { #[allow(missing_docs)] pub fn discriminant_value(&self) -> usize { match *self { $( ViewportDescriptor::$assigned_variant(..) => $assigned_discriminant, )* } } } impl ToCss for ViewportDescriptor { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { $( ViewportDescriptor::$assigned_variant(ref val) => { try!(dest.write_str($assigned_variant_name)); try!(dest.write_str(": ")); try!(val.to_css(dest)); }, )* } dest.write_str(";") } } }; } declare_viewport_descriptor! { "min-width" => MinWidth(ViewportLength), "max-width" => MaxWidth(ViewportLength), "min-height" => MinHeight(ViewportLength), "max-height" => MaxHeight(ViewportLength), "zoom" => Zoom(Zoom), "min-zoom" => MinZoom(Zoom), "max-zoom" => MaxZoom(Zoom), "user-zoom" => UserZoom(UserZoom), "orientation" => Orientation(Orientation), } trait FromMeta: Sized { fn from_meta(value: &str) -> Option<Self>; } /// ViewportLength is a length | percentage | auto | extend-to-zoom /// See: /// * http://dev.w3.org/csswg/css-device-adapt/#min-max-width-desc /// * http://dev.w3.org/csswg/css-device-adapt/#extend-to-zoom #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[allow(missing_docs)] pub enum ViewportLength { Specified(LengthOrPercentageOrAuto), ExtendToZoom } impl ToCss for ViewportLength { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write, { match *self { ViewportLength::Specified(ref length) => length.to_css(dest), ViewportLength::ExtendToZoom => write!(dest, "extend-to-zoom"), } } } impl FromMeta for ViewportLength { fn from_meta(value: &str) -> Option<ViewportLength> { macro_rules! specified { ($value:expr) => { ViewportLength::Specified(LengthOrPercentageOrAuto::Length($value)) } } Some(match value { v if v.eq_ignore_ascii_case("device-width") => specified!(NoCalcLength::ViewportPercentage(ViewportPercentageLength::Vw(100.))), v if v.eq_ignore_ascii_case("device-height") => specified!(NoCalcLength::ViewportPercentage(ViewportPercentageLength::Vh(100.))), _ => { match value.parse::<f32>() { Ok(n) if n >= 0. => specified!(NoCalcLength::from_px(n.max(1.).min(10000.))), Ok(_) => return None, Err(_) => specified!(NoCalcLength::from_px(1.)) } } }) } } impl ViewportLength { fn parse(input: &mut Parser) -> Result<ViewportLength, ()> { // we explicitly do not accept 'extend-to-zoom', since it is a UA internal value // for <META> viewport translation LengthOrPercentageOrAuto::parse_non_negative(input).map(ViewportLength::Specified) } } impl FromMeta for Zoom { fn from_meta(value: &str) -> Option<Zoom> { Some(match value { v if v.eq_ignore_ascii_case("yes") => Zoom::Number(1.), v if v.eq_ignore_ascii_case("no") => Zoom::Number(0.1), v if v.eq_ignore_ascii_case("device-width") => Zoom::Number(10.), v if v.eq_ignore_ascii_case("device-height") => Zoom::Number(10.), _ => { match value.parse::<f32>() { Ok(n) if n >= 0. => Zoom::Number(n.max(0.1).min(10.)), Ok(_) => return None, Err(_) => Zoom::Number(0.1), } } }) } } impl FromMeta for UserZoom { fn from_meta(value: &str) -> Option<UserZoom> { Some(match value { v if v.eq_ignore_ascii_case("yes") => UserZoom::Zoom, v if v.eq_ignore_ascii_case("no") => UserZoom::Fixed, v if v.eq_ignore_ascii_case("device-width") => UserZoom::Zoom, v if v.eq_ignore_ascii_case("device-height") => UserZoom::Zoom, _ => { match value.parse::<f32>() { Ok(n) if n >= 1. || n <= -1. => UserZoom::Zoom, _ => UserZoom::Fixed } } }) } } struct ViewportRuleParser<'a, 'b: 'a> { context: &'a ParserContext<'b> } #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[allow(missing_docs)] pub struct ViewportDescriptorDeclaration { pub origin: Origin, pub descriptor: ViewportDescriptor, pub important: bool } impl ViewportDescriptorDeclaration { #[allow(missing_docs)] pub fn new(origin: Origin, descriptor: ViewportDescriptor, important: bool) -> ViewportDescriptorDeclaration { ViewportDescriptorDeclaration { origin: origin, descriptor: descriptor, important: important } } } impl ToCss for ViewportDescriptorDeclaration { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.descriptor.to_css(dest)); if self.important { try!(dest.write_str(" !important")); } dest.write_str(";") } } fn parse_shorthand(input: &mut Parser) -> Result<(ViewportLength, ViewportLength), ()> { let min = try!(ViewportLength::parse(input)); match input.try(|input| ViewportLength::parse(input)) { Err(()) => Ok((min.clone(), min)), Ok(max) => Ok((min, max)) } } impl<'a, 'b> AtRuleParser for ViewportRuleParser<'a, 'b> { type Prelude = (); type AtRule = Vec<ViewportDescriptorDeclaration>; } impl<'a, 'b> DeclarationParser for ViewportRuleParser<'a, 'b> { type Declaration = Vec<ViewportDescriptorDeclaration>; fn parse_value(&mut self, name: &str, input: &mut Parser) -> Result<Vec<ViewportDescriptorDeclaration>, ()> { macro_rules! declaration { ($declaration:ident($parse:path)) => { declaration!($declaration(value: try!($parse(input)), important: input.try(parse_important).is_ok())) }; ($declaration:ident(value: $value:expr, important: $important:expr)) => { ViewportDescriptorDeclaration::new( self.context.stylesheet_origin, ViewportDescriptor::$declaration($value), $important) } } macro_rules! ok { ($declaration:ident($parse:path)) => { Ok(vec![declaration!($declaration($parse))]) }; (shorthand -> [$min:ident, $max:ident]) => {{ let shorthand = try!(parse_shorthand(input)); let important = input.try(parse_important).is_ok(); Ok(vec![declaration!($min(value: shorthand.0, important: important)), declaration!($max(value: shorthand.1, important: important))]) }} } match name { n if n.eq_ignore_ascii_case("min-width") => ok!(MinWidth(ViewportLength::parse)), n if n.eq_ignore_ascii_case("max-width") => ok!(MaxWidth(ViewportLength::parse)), n if n.eq_ignore_ascii_case("width") => ok!(shorthand -> [MinWidth, MaxWidth]), n if n.eq_ignore_ascii_case("min-height") => ok!(MinHeight(ViewportLength::parse)), n if n.eq_ignore_ascii_case("max-height") => ok!(MaxHeight(ViewportLength::parse)), n if n.eq_ignore_ascii_case("height") => ok!(shorthand -> [MinHeight, MaxHeight]), n if n.eq_ignore_ascii_case("zoom") => ok!(Zoom(Zoom::parse)), n if n.eq_ignore_ascii_case("min-zoom") => ok!(MinZoom(Zoom::parse)), n if n.eq_ignore_ascii_case("max-zoom") => ok!(MaxZoom(Zoom::parse)), n if n.eq_ignore_ascii_case("user-zoom") => ok!(UserZoom(UserZoom::parse)), n if n.eq_ignore_ascii_case("orientation") => ok!(Orientation(Orientation::parse)), _ => Err(()), } } } /// A `@viewport` rule. #[derive(Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct ViewportRule { /// The declarations contained in this @viewport rule. pub declarations: Vec<ViewportDescriptorDeclaration> } /// Whitespace as defined by DEVICE-ADAPT § 9.2 // TODO: should we just use whitespace as defined by HTML5? const WHITESPACE: &'static [char] = &['\t', '\n', '\r', ' ']; /// Separators as defined by DEVICE-ADAPT § 9.2 // need to use \x2c instead of ',' due to test-tidy const SEPARATOR: &'static [char] = &['\x2c', ';']; #[inline] fn is_whitespace_separator_or_equals(c: &char) -> bool { WHITESPACE.contains(c) || SEPARATOR.contains(c) || *c == '=' } impl ViewportRule { #[allow(missing_docs)] pub fn parse(input: &mut Parser, context: &ParserContext) -> Result<ViewportRule, ()> { let parser = ViewportRuleParser { context: context }; let mut cascade = Cascade::new(); let mut parser = DeclarationListParser::new(input, parser); while let Some(result) = parser.next() { match result { Ok(declarations) => { for declarations in declarations { cascade.add(Cow::Owned(declarations)) } } Err(range) => { let pos = range.start; let message = format!("Unsupported @viewport descriptor declaration: '{}'", parser.input.slice(range)); log_css_error(parser.input, pos, &*message, &context); } } } Ok(ViewportRule { declarations: cascade.finish() }) } #[allow(missing_docs)] pub fn from_meta(content: &str) -> Option<ViewportRule> { let mut declarations = vec![None; VIEWPORT_DESCRIPTOR_VARIANTS]; macro_rules! push_descriptor { ($descriptor:ident($value:expr)) => {{ let descriptor = ViewportDescriptor::$descriptor($value); let discriminant = descriptor.discriminant_value(); declarations[discriminant] = Some(ViewportDescriptorDeclaration::new( Origin::Author, descriptor, false)); } }} let mut has_width = false; let mut has_height = false; let mut has_zoom = false; let mut iter = content.chars().enumerate(); macro_rules! start_of_name { ($iter:ident) => { $iter.by_ref() .skip_while(|&(_, c)| is_whitespace_separator_or_equals(&c)) .next() } } while let Some((start, _)) = start_of_name!(iter) { let property = ViewportRule::parse_meta_property(content, &mut iter, start); if let Some((name, value)) = property { macro_rules! push { ($descriptor:ident($translate:path)) => { if let Some(value) = $translate(value) { push_descriptor!($descriptor(value)); } } } match name { n if n.eq_ignore_ascii_case("width") => { if let Some(value) = ViewportLength::from_meta(value) { push_descriptor!(MinWidth(ViewportLength::ExtendToZoom)); push_descriptor!(MaxWidth(value)); has_width = true; } } n if n.eq_ignore_ascii_case("height") => { if let Some(value) = ViewportLength::from_meta(value) { push_descriptor!(MinHeight(ViewportLength::ExtendToZoom)); push_descriptor!(MaxHeight(value)); has_height = true; } } n if n.eq_ignore_ascii_case("initial-scale") => { if let Some(value) = Zoom::from_meta(value) { push_descriptor!(Zoom(value)); has_zoom = true; } } n if n.eq_ignore_ascii_case("minimum-scale") => push!(MinZoom(Zoom::from_meta)), n if n.eq_ignore_ascii_case("maximum-scale") => push!(MaxZoom(Zoom::from_meta)), n if n.eq_ignore_ascii_case("user-scalable") => push!(UserZoom(UserZoom::from_meta)), _ => {} } } } // DEVICE-ADAPT § 9.4 - The 'width' and 'height' properties // http://dev.w3.org/csswg/css-device-adapt/#width-and-height-properties if !has_width && has_zoom { if has_height { push_descriptor!(MinWidth(ViewportLength::Specified(LengthOrPercentageOrAuto::Auto))); push_descriptor!(MaxWidth(ViewportLength::Specified(LengthOrPercentageOrAuto::Auto))); } else { push_descriptor!(MinWidth(ViewportLength::ExtendToZoom)); push_descriptor!(MaxWidth(ViewportLength::ExtendToZoom)); } } let declarations: Vec<_> = declarations.into_iter().filter_map(|entry| entry).collect(); if !declarations.is_empty() { Some(ViewportRule { declarations: declarations }) } else { None } } fn parse_meta_property<'a>(content: &'a str, iter: &mut Enumerate<Chars<'a>>, start: usize) -> Option<(&'a str, &'a str)> { fn end_of_token(iter: &mut Enumerate<Chars>) -> Option<(usize, char)> { iter.by_ref() .skip_while(|&(_, c)| !is_whitespace_separator_or_equals(&c)) .next() } fn skip_whitespace(iter: &mut Enumerate<Chars>) -> Option<(usize, char)> { iter.by_ref() .skip_while(|&(_, c)| WHITESPACE.contains(&c)) .next() } // <name> <whitespace>* '=' let end = match end_of_token(iter) { Some((end, c)) if WHITESPACE.contains(&c) => { match skip_whitespace(iter) { Some((_, c)) if c == '=' => end, _ => return None } } Some((end, c)) if c == '=' => end, _ => return None }; let name = &content[start..end]; // <whitespace>* <value> let start = match skip_whitespace(iter) { Some((start, c)) if !SEPARATOR.contains(&c) => start, _ => return None }; let value = match end_of_token(iter) { Some((end, _)) => &content[start..end], _ => &content[start..] }; Some((name, value)) } } impl ToCss for ViewportRule { // Serialization of ViewportRule is not specced. fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(dest.write_str("@viewport { ")); let mut iter = self.declarations.iter(); try!(iter.next().unwrap().to_css(dest)); for declaration in iter { try!(dest.write_str(" ")); try!(declaration.to_css(dest)); } dest.write_str(" }") } } /// Computes the cascade precedence as according to /// http://dev.w3.org/csswg/css-cascade/#cascade-origin fn cascade_precendence(origin: Origin, important: bool) -> u8 { match (origin, important) { (Origin::UserAgent, true) => 1, (Origin::User, true) => 2, (Origin::Author, true) => 3, (Origin::Author, false) => 4, (Origin::User, false) => 5, (Origin::UserAgent, false) => 6, } } impl ViewportDescriptorDeclaration { fn higher_or_equal_precendence(&self, other: &ViewportDescriptorDeclaration) -> bool { let self_precedence = cascade_precendence(self.origin, self.important); let other_precedence = cascade_precendence(other.origin, other.important); self_precedence <= other_precedence } } #[allow(missing_docs)] pub struct Cascade { declarations: Vec<Option<(usize, ViewportDescriptorDeclaration)>>, count_so_far: usize, } #[allow(missing_docs)] impl Cascade { pub fn new() -> Self { Cascade { declarations: vec![None; VIEWPORT_DESCRIPTOR_VARIANTS], count_so_far: 0, } } pub fn from_stylesheets<'a, I>(stylesheets: I, device: &Device) -> Self where I: IntoIterator, I::Item: AsRef<Stylesheet>, { let mut cascade = Self::new(); for stylesheet in stylesheets { stylesheet.as_ref().effective_viewport_rules(device, |rule| { for declaration in &rule.declarations { cascade.add(Cow::Borrowed(declaration)) } }) } cascade } pub fn add(&mut self, declaration: Cow<ViewportDescriptorDeclaration>) { let descriptor = declaration.descriptor.discriminant_value(); match self.declarations[descriptor] { Some((ref mut order_of_appearance, ref mut entry_declaration)) => { if declaration.higher_or_equal_precendence(entry_declaration) { *entry_declaration = declaration.into_owned(); *order_of_appearance = self.count_so_far; } } ref mut entry @ None => { *entry = Some((self.count_so_far, declaration.into_owned())); } } self.count_so_far += 1; } pub fn finish(mut self) -> Vec<ViewportDescriptorDeclaration> { // sort the descriptors by order of appearance self.declarations.sort_by_key(|entry| entry.as_ref().map(|&(index, _)| index)); self.declarations.into_iter().filter_map(|entry| entry.map(|(_, decl)| decl)).collect() } } /// Just a helper trait to be able to implement methods on ViewportConstraints. pub trait MaybeNew { /// Create a ViewportConstraints from a viewport size and a `@viewport` /// rule. fn maybe_new(device: &Device, rule: &ViewportRule) -> Option<ViewportConstraints>; } impl MaybeNew for ViewportConstraints { fn maybe_new(device: &Device, rule: &ViewportRule) -> Option<ViewportConstraints> { use std::cmp; if rule.declarations.is_empty() { return None } let mut min_width = None; let mut max_width = None; let mut min_height = None; let mut max_height = None; let mut initial_zoom = None; let mut min_zoom = None; let mut max_zoom = None; let mut user_zoom = UserZoom::Zoom; let mut orientation = Orientation::Auto; // collapse the list of declarations into descriptor values for declaration in &rule.declarations { match declaration.descriptor { ViewportDescriptor::MinWidth(ref value) => min_width = Some(value), ViewportDescriptor::MaxWidth(ref value) => max_width = Some(value), ViewportDescriptor::MinHeight(ref value) => min_height = Some(value), ViewportDescriptor::MaxHeight(ref value) => max_height = Some(value), ViewportDescriptor::Zoom(value) => initial_zoom = value.to_f32(), ViewportDescriptor::MinZoom(value) => min_zoom = value.to_f32(), ViewportDescriptor::MaxZoom(value) => max_zoom = value.to_f32(), ViewportDescriptor::UserZoom(value) => user_zoom = value, ViewportDescriptor::Orientation(value) => orientation = value } } // TODO: return `None` if all descriptors are either absent or initial value macro_rules! choose { ($op:ident, $opta:expr, $optb:expr) => { match ($opta, $optb) { (None, None) => None, (a, None) => a, (None, b) => b, (Some(a), Some(b)) => Some(a.$op(b)), } } } macro_rules! min { ($opta:expr, $optb:expr) => { choose!(min, $opta, $optb) } } macro_rules! max { ($opta:expr, $optb:expr) => { choose!(max, $opta, $optb) } } // DEVICE-ADAPT § 6.2.1 Resolve min-zoom and max-zoom values if min_zoom.is_some() && max_zoom.is_some() { max_zoom = Some(min_zoom.unwrap().max(max_zoom.unwrap())) } // DEVICE-ADAPT § 6.2.2 Constrain zoom value to the [min-zoom, max-zoom] range if initial_zoom.is_some() { initial_zoom = max!(min_zoom, min!(max_zoom, initial_zoom)); } // DEVICE-ADAPT § 6.2.3 Resolve non-auto lengths to pixel lengths // // Note: DEVICE-ADAPT § 5. states that relative length values are // resolved against initial values let initial_viewport = device.au_viewport_size(); // TODO(emilio): Stop cloning `ComputedValues` around! let context = Context { is_root_element: false, viewport_size: initial_viewport, inherited_style: device.default_values(), style: device.default_values().clone(), font_metrics_provider: None, // TODO: Should have! }; // DEVICE-ADAPT § 9.3 Resolving 'extend-to-zoom' let extend_width; let extend_height; if let Some(extend_zoom) = max!(initial_zoom, max_zoom) { let scale_factor = 1. / extend_zoom; extend_width = Some(initial_viewport.width.scale_by(scale_factor)); extend_height = Some(initial_viewport.height.scale_by(scale_factor)); } else { extend_width = None; extend_height = None; } macro_rules! to_pixel_length { ($value:ident, $dimension:ident, $extend_to:ident => $auto_extend_to:expr) => { if let Some($value) = $value { match *$value { ViewportLength::Specified(ref length) => match *length { LengthOrPercentageOrAuto::Length(ref value) => Some(value.to_computed_value(&context)), LengthOrPercentageOrAuto::Percentage(value) => Some(initial_viewport.$dimension.scale_by(value.0)), LengthOrPercentageOrAuto::Auto => None, LengthOrPercentageOrAuto::Calc(ref calc) => { let calc = calc.to_computed_value(&context); Some(initial_viewport.$dimension.scale_by(calc.percentage()) + calc.length()) } }, ViewportLength::ExtendToZoom => { // $extend_to will be 'None' if 'extend-to-zoom' is 'auto' match ($extend_to, $auto_extend_to) { (None, None) => None, (a, None) => a, (None, b) => b, (a, b) => cmp::max(a, b) } } } } else { None } } } // DEVICE-ADAPT § 9.3 states that max-descriptors need to be resolved // before min-descriptors. // http://dev.w3.org/csswg/css-device-adapt/#resolve-extend-to-zoom let max_width = to_pixel_length!(max_width, width, extend_width => None); let max_height = to_pixel_length!(max_height, height, extend_height => None); let min_width = to_pixel_length!(min_width, width, extend_width => max_width); let min_height = to_pixel_length!(min_height, height, extend_height => max_height); // DEVICE-ADAPT § 6.2.4 Resolve initial width and height from min/max descriptors macro_rules! resolve { ($min:ident, $max:ident, $initial:expr) => { if $min.is_some() || $max.is_some() { let max = match $max { Some(max) => cmp::min(max, $initial), None => $initial }; Some(match $min { Some(min) => cmp::max(min, max), None => max }) } else { None }; } } let width = resolve!(min_width, max_width, initial_viewport.width); let height = resolve!(min_height, max_height, initial_viewport.height); // DEVICE-ADAPT § 6.2.5 Resolve width value let width = if width.is_none() && height.is_none() { Some(initial_viewport.width) } else { width }; let width = width.unwrap_or_else(|| match initial_viewport.height { Au(0) => initial_viewport.width, initial_height => { let ratio = initial_viewport.width.to_f32_px() / initial_height.to_f32_px(); Au::from_f32_px(height.unwrap().to_f32_px() * ratio) } }); // DEVICE-ADAPT § 6.2.6 Resolve height value let height = height.unwrap_or_else(|| match initial_viewport.width { Au(0) => initial_viewport.height, initial_width => { let ratio = initial_viewport.height.to_f32_px() / initial_width.to_f32_px(); Au::from_f32_px(width.to_f32_px() * ratio) } }); Some(ViewportConstraints { size: TypedSize2D::new(width.to_f32_px(), height.to_f32_px()), // TODO: compute a zoom factor for 'auto' as suggested by DEVICE-ADAPT § 10. initial_zoom: ScaleFactor::new(initial_zoom.unwrap_or(1.)), min_zoom: min_zoom.map(ScaleFactor::new), max_zoom: max_zoom.map(ScaleFactor::new), user_zoom: user_zoom, orientation: orientation }) } }<|fim▁end|>
<|file_name|>suite_004_navbase.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """Package for suites and tests related to bots.modules package""" import pytest from qacode.core.bots.modules.nav_base import NavBase from qacode.core.exceptions.core_exception import CoreException from qacode.core.testing.asserts import Assert from qacode.core.testing.test_info import TestInfoBotUnique from qacode.utils import settings from selenium.webdriver.remote.webelement import WebElement ASSERT = Assert() SETTINGS = settings(file_path="qacode/configs/") SKIP_NAVS = SETTINGS['tests']['skip']['bot_navigations'] SKIP_NAVS_MSG = 'bot_navigations DISABLED by config file' class TestNavBase(TestInfoBotUnique): """Test Suite for class NavBase""" app = None page = None @classmethod def setup_class(cls, **kwargs): """Setup class (suite) to be executed""" super(TestNavBase, cls).setup_class( config=settings(file_path="qacode/configs/"), skip_force=SKIP_NAVS) def setup_method(self, test_method, close=True): """Configure self.attribute""" super(TestNavBase, self).setup_method( test_method, config=settings(file_path="qacode/configs/")) self.add_property('app', self.cfg_app('qadmin')) self.add_property('page', self.cfg_page('qacode_login')) self.add_property('txt_username', self.cfg_control('txt_username')) self.add_property('txt_password', self.cfg_control('txt_password')) self.add_property('btn_submit', self.cfg_control('btn_submit')) self.add_property('lst_ordered', self.cfg_control('lst_ordered')) self.add_property( 'lst_ordered_child', self.cfg_control('lst_ordered_child')) self.add_property('dd_menu_data', self.cfg_control('dd_menu_data')) self.add_property( 'dd_menu_data_lists', self.cfg_control('dd_menu_data_lists')) self.add_property( 'btn_click_invisible', self.cfg_control('btn_click_invisible')) self.add_property( 'btn_click_visible', self.cfg_control('btn_click_visible')) self.add_property('title_buttons', self.cfg_control('title_buttons')) def setup_login_to_inputs(self): """Do login before to exec some testcases""" # setup_login self.bot.navigation.get_url(self.page.get('url'), wait_for_load=10) txt_username = self.bot.navigation.find_element( self.txt_username.get("selector")) txt_password = self.bot.navigation.find_element( self.txt_password.get("selector")) btn_submit = self.bot.navigation.find_element( self.btn_submit.get("selector")) self.bot.navigation.ele_write(txt_username, "admin") self.bot.navigation.ele_write(txt_password, "admin") self.bot.navigation.ele_click(btn_submit) # end setup_login def setup_login_to_data(self): """Do login before to exec some testcases""" # setup_login self.bot.navigation.get_url(self.page.get('url'), wait_for_load=10) txt_username = self.bot.navigation.find_element( self.txt_username.get("selector")) txt_password = self.bot.navigation.find_element( self.txt_password.get("selector")) btn_submit = self.bot.navigation.find_element( self.btn_submit.get("selector")) self.bot.navigation.ele_write(txt_username, "admin") self.bot.navigation.ele_write(txt_password, "admin") self.bot.navigation.ele_click(btn_submit) self.bot.navigation.ele_click( self.bot.navigation.find_element_wait( self.dd_menu_data.get("selector"))) self.bot.navigation.ele_click( self.bot.navigation.find_element_wait( self.dd_menu_data_lists.get("selector"))) # end setup_login @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_navbase_instance(self): """Testcase: test_navbase_instance""" ASSERT.is_instance(self.bot.navigation, NavBase) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_gourl_withoutwaits(self): """Testcase: test_gourl_withoutwaits""" self.bot.navigation.get_url(self.page.get('url')) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_gourl_withwaits(self): """Testcase: test_gourl_withwaits""" self.bot.navigation.get_url( self.page.get('url'), wait_for_load=1) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_getcurrenturl_ok(self): """Testcase: test_getcurrenturl_ok""" ASSERT.equals( self.bot.navigation.get_current_url(), self.page.get('url')) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_isurl_true(self): """Testcase: test_isurl_true""" ASSERT.true( self.bot.navigation.is_url( self.bot.navigation.get_current_url())) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_isurl_false(self): """Testcase: test_isurl_false""" ASSERT.false(self.bot.navigation.is_url("")) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_isurl_raiseswhenurlreturnfalse(self): """Testcase: test_isurl_false""" with pytest.raises(CoreException): self.bot.navigation.is_url("", ignore_raises=False) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_reload_ok(self): """Testcase: test_reload_ok""" self.bot.navigation.reload() @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_forward_ok(self): """Testcase: test_reload_ok""" self.bot.navigation.forward() @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_getmaximizewindow_ok(self): """Testcase: test_getmaximizewindow_ok""" self.bot.navigation.get_maximize_window() @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_getcapabilities_ok(self): """Testcase: test_getcapabilities_ok""" caps = self.bot.navigation.get_capabilities() ASSERT.is_instance(caps, dict) ASSERT.is_instance(caps['chrome'], dict) ASSERT.equals(caps['browserName'], 'chrome') @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_getlog_ok(self): """Testcase: test_getlog_ok""" self.bot.navigation.get_url(self.page.get('url')) log_data = self.bot.navigation.get_log() ASSERT.not_none(log_data) self.log.debug("selenium logs, browser={}".format(log_data)) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) @pytest.mark.parametrize( "log_name", [None, 'browser', 'driver', 'client', 'server']) def test_getlog_lognames(self, log_name): """Testcase: test_getlog_lognames""" self.bot.navigation.get_url(self.page.get('url')) if log_name is None: with pytest.raises(CoreException): self.bot.navigation.get_log(log_name=log_name) return True log_data = self.bot.navigation.get_log(log_name=log_name) ASSERT.not_none(log_data) msg = "selenium logs, log_name={}, log_data={}".format( log_name, log_data) self.log.debug(msg) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_findelement_ok(self): """Testcase: test_findelement_ok""" ASSERT.is_instance( self.bot.navigation.find_element("body"), WebElement) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_findelement_notfound(self): """Testcase: test_findelement_notfound""" with pytest.raises(CoreException): self.bot.navigation.find_element("article") @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_findelement_notlocator(self): """Testcase: test_findelement_notlocator""" with pytest.raises(CoreException): self.bot.navigation.find_element( "body", locator=None) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_findelementwait_ok(self): """Testcase: test_findelementwait_ok""" ASSERT.is_instance( self.bot.navigation.find_element_wait("body"), WebElement) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_findelementswait_ok(self): """Testcase: test_findelementwait_ok""" elements = self.bot.navigation.find_elements_wait("body>*") ASSERT.is_instance(elements, list) for element in elements: ASSERT.is_instance(element, WebElement) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_findelements_ok(self): """Testcase: test_findelement_ok""" elements = self.bot.navigation.find_elements("body>*") ASSERT.is_instance(elements, list) for element in elements: ASSERT.is_instance(element, WebElement) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_findelements_notfound(self): """Testcase: test_findelements_notfound""" with pytest.raises(CoreException): self.bot.navigation.find_elements("article") @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_findelements_notlocator(self): """Testcase: test_findelements_notlocator""" with pytest.raises(CoreException): self.bot.navigation.find_elements( "body", locator=None) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_getwindowhandle_ok(self): """Testcase: test_getwindowhandle_ok""" ASSERT.not_none( self.bot.navigation.get_window_handle()) @pytest.mark.skipIf( True, "Depends of remote+local webdrivers to get working") def test_addcookie_ok(self): """Testcase: test_addcookie_ok""" cookie = {"name": "test_cookie", "value": "test_value"} self.bot.navigation.add_cookie(cookie) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_addcookie_notparams(self): """Testcase: test_addcookie_ok""" with pytest.raises(CoreException): self.bot.navigation.add_cookie(None) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_addcookie_badcookiekeys(self): """Testcase: test_addcookie_ok""" with pytest.raises(CoreException): self.bot.navigation.add_cookie({}) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_getcookies_ok(self): """Testcase: test_getcookies_ok""" ASSERT.is_instance( self.bot.navigation.get_cookies(), list) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_deletecookiebykey_ok(self): """Testcase: test_deleteallcookies_ok""" self.bot.navigation.delete_cookie_by_key("") @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_deleteallcookies_ok(self): """Testcase: test_deleteallcookies_ok""" self.bot.navigation.delete_cookies() @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_setwindowsize_ok(self): """Testcase: test_setwindowsize_ok""" self.bot.navigation.set_window_size( pos_x=1024, pos_y=768) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_gettitle_ok(self): """Testcase: test_gettitle_ok""" ASSERT.not_none( self.bot.navigation.get_title()) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_getscreenshotasbase64_ok(self): """Testcase: test_getscreenshotasbase64_ok""" ASSERT.not_none( self.bot.navigation.get_screenshot_as_base64()) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_jssettimeout_ok(self): """Testcase: test_jssettimeout_ok""" self.bot.navigation.js_set_timeout(1) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_eleclick_okbyselector(self): """Testcase: test_eleclick_ok""" self.bot.navigation.ele_click(selector="body") @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_eleclick_okbyelement(self): """Testcase: test_eleclick_ok""" self.bot.navigation.ele_click( element=self.bot.navigation.find_element("body")) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_eleclick_notparams(self): """Testcase: test_eleclick_notparams""" with pytest.raises(CoreException): self.bot.navigation.ele_click() @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_elewrite_ok(self): """Testcase: test_elewrite_ok""" self.bot.navigation.ele_write( self.bot.navigation.find_element("body"), text="test") @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_elewrite_okwithouttext(self): """Testcase: test_elewrite_ok""" self.bot.navigation.ele_write( self.bot.navigation.find_element("body"), text=None) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_elewrite_notparams(self): """Testcase: test_elewrite_notparams""" with pytest.raises(CoreException): self.bot.navigation.ele_write(None) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_setwebelement_ok(self): """Testcase: test_setwebelement_ok""" self.bot.navigation.set_web_element("test-element") @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_findelementchild_ok(self): """Testcase: test_findelementchild_ok""" self.setup_login_to_data() ele_parent = self.bot.navigation.find_element_wait( self.lst_ordered.get("selector")) ASSERT.is_instance(ele_parent, WebElement) ele_child = self.bot.navigation.find_element_child( ele_parent, self.lst_ordered_child.get("selector")) ASSERT.is_instance(ele_child, WebElement) ASSERT.equals( "Item list01", self.bot.navigation.ele_text(ele_child)) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_findelementchildren_ok(self): """Testcase: test_findelementchildren_ok""" self.setup_login_to_data() ele_parent = self.bot.navigation.find_element_wait( self.lst_ordered.get("selector")) ASSERT.is_instance(ele_parent, WebElement) ele_children = self.bot.navigation.find_element_children( ele_parent, self.lst_ordered_child.get("selector")) ASSERT.is_instance(ele_children, list) ASSERT.greater(len(ele_children), 1) ASSERT.lower(len(ele_children), 5) ASSERT.equals( "Item list01", self.bot.navigation.ele_text(ele_children[0])) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_elewaitinvisible_ok(self): """Testcase: test_elewaitinvisible_ok""" self.setup_login_to_inputs() selector = self.btn_click_invisible.get("selector") ele = self.bot.navigation.find_element_wait(selector) ele.click() # end setup ele = self.bot.navigation.ele_wait_invisible(selector, timeout=7) ASSERT.is_instance(ele, WebElement) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_elewaitvisible_ok(self): """Testcase: test_elewaitvisible_ok""" self.setup_login_to_inputs() find_ele = self.bot.navigation.find_element_wait ele = find_ele(self.btn_click_invisible.get("selector")) ele.click() ele_invisible = find_ele(self.btn_click_visible.get("selector")) # end setup ele_visible = self.bot.navigation.ele_wait_visible( ele_invisible, timeout=7) ASSERT.is_instance(ele_visible, WebElement) @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_elewaittext_ok(self): """Testcase: test_elewaitvalue_ok""" self.setup_login_to_inputs() selector = self.btn_click_invisible.get("selector") selector_title = self.title_buttons.get("selector") ele_text = self.bot.navigation.find_element_wait(selector) ele_text.click() # end setup is_changed = self.bot.navigation.ele_wait_text( selector_title, "Buttonss", timeout=12) ASSERT.true(is_changed) ASSERT.is_instance( self.bot.navigation.ele_text(ele_text), "Buttonss") @pytest.mark.skipIf(SKIP_NAVS, SKIP_NAVS_MSG) def test_elewaitvalue_ok(self): """Testcase: test_elewaitvalue_ok""" self.setup_login_to_inputs() selector = self.btn_click_invisible.get("selector") ele_text = self.bot.navigation.find_element_wait(selector) ele_text.click() # end setup is_changed = self.bot.navigation.ele_wait_value( selector, "bad_text", timeout=12) ASSERT.true(is_changed) ASSERT.is_instance( self.bot.navigation.ele_attribute(ele_text, "value"),<|fim▁hole|><|fim▁end|>
"bad_text")
<|file_name|>issue-14853.rs<|end_file_name|><|fim▁begin|>use std::fmt::Debug; trait Str {} trait Something: Sized { fn yay<T: Debug>(_: Option<Self>, thing: &[T]); } struct X { data: u32 } impl Something for X { fn yay<T: Str>(_:Option<X>, thing: &[T]) { //~^ ERROR E0276 } }<|fim▁hole|> println!("{:?}", Something::yay(None::<X>, arr)); }<|fim▁end|>
fn main() { let arr = &["one", "two", "three"];
<|file_name|>validators.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). import re from rest_framework.serializers import ValidationError def name(value): '''Matches names of people, countries and and other things.''' if re.match(r'^[A-Za-z\s\.\-\'àèéìòóôù]+$', value) is None: raise ValidationError('This field contains invalid characters.') def address(value): '''Matches street addresses.''' if re.match(r'^[\w\s\.\-\'àèéìòóôù]+$', value) is None: raise ValidationError('This field contains invalid characters.') def numeric(value): '''Matches numbers and spaces.''' if re.match(r'^[\d\s]+$', value) is None: raise ValidationError('This field can only contain numbers and spaces.') <|fim▁hole|> raise ValidationError('This is an invalid email address.') def phone_international(value): '''Loosely matches phone numbers.''' if re.match(r'^[\d\-x\s\+\(\)]+$', value) is None: raise ValidationError('This is an invalid phone number.') def phone_domestic(value): '''Matches domestic phone numbers.''' if re.match(r'^\(?(\d{3})\)?\s(\d{3})-(\d{4})(\sx\d{1,5})?$', value) is None: raise ValidationError('This is an invalid phone number.') def nonempty(value): '''Requires that a field be non-empty.''' if not value: raise ValidationError('This field is required.')<|fim▁end|>
def email(value): '''Loosely matches email addresses.''' if re.match(r'^[\w_.+-]+@[\w-]+\.[\w\-.]+$', value) is None:
<|file_name|>scoreovertime.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import sys from lxml import html import urllib3 import re http = urllib3.PoolManager() baseUrl = 'http://scoreboard.uscyberpatriot.org/' scoresPage = html.fromstring(http.request('GET', baseUrl + 'team.php?team=' + sys.argv[1]).data) # XPath for chart script: /html/body/div[2]/div/script[1]<|fim▁hole|>chart = scoresPage.xpath('/html/body/div[2]/div/script[1]')[0] scoreTimes = re.compile(r'\[\'([0-9]{2}/[0123456789 :]+)\'((, (-?[0-9]{1,3}|null))+)\],?', re.MULTILINE) reSearch = scoreTimes.findall(chart.text) for res in reSearch: # Tuple result # Capture 0 is time # Capture 1 is screwyformat scores print(res[0], end='') for score in filter(None, res[1].split(',')): print('\t' + score, end='') print()<|fim▁end|>
<|file_name|>nodeGraphs.tsx<|end_file_name|><|fim▁begin|>import * as React from "react"; import * as d3 from "d3"; import GraphGroup from "../components/graphGroup"; import { LineGraph, Axis, Metric } from "../components/linegraph"; import { StackedAreaGraph } from "../components/stackedgraph"; import { Bytes } from "../util/format"; import { NanoToMilli } from "../util/convert"; interface NodeGraphsOwnProps { groupId: string; nodeIds: string[]; } /** * Renders the main content of the help us page. */ export default class NodeGraphs extends React.Component<NodeGraphsOwnProps, {}> { static displayTimeScale = true; render() { let sources: string[] = this.props.nodeIds || null; let specifier = (sources && sources.length === 1) ? `on node ${sources[0]}` : "across all nodes"; return <div className="section node"> <div className="charts"> <GraphGroup groupId="node.activity" hide={this.props.groupId !== "node.activity"}> <h2>Activity</h2> <LineGraph title="SQL Connections" sources={sources} tooltip={`The total number of active SQL connections ${specifier}.`}> <Axis format={ d3.format(".1f") }> <Metric name="cr.node.sql.conns" title="Client Connections" /> </Axis> </LineGraph> <LineGraph title="SQL Traffic" sources={sources} tooltip={`The average amount of SQL client network traffic in bytes per second ${specifier}.`}> <Axis format={ Bytes }> <Metric name="cr.node.sql.bytesin" title="Bytes In" nonNegativeRate /> <Metric name="cr.node.sql.bytesout" title="Bytes Out" nonNegativeRate /> </Axis> </LineGraph> <LineGraph title="Queries Per Second" sources={sources} tooltip={`The average number of SQL queries per second ${specifier}.`}> <Axis format={ d3.format(".1f") }> <Metric name="cr.node.sql.query.count" title="Queries/Sec" nonNegativeRate /> </Axis> </LineGraph> <LineGraph title="Live Bytes" sources={sources} tooltip={`The amount of storage space used by live (non-historical) data ${specifier}.`}> <Axis format={ Bytes }> <Metric name="cr.store.livebytes" title="Live Bytes" /> </Axis> </LineGraph> <LineGraph title="Query Time" subtitle="(Max Per Percentile)" tooltip={`The latency between query requests and responses over a 1 minute period. Percentiles are first calculated on each node. For each percentile, the maximum latency across all nodes is then shown.`} sources={sources}> <Axis format={ (n: number) => d3.format(".1f")(NanoToMilli(n)) } label="Milliseconds"> <Metric name="cr.node.exec.latency-max" title="Max Latency" aggregateMax downsampleMax /> <Metric name="cr.node.exec.latency-p99" title="99th percentile latency" aggregateMax downsampleMax /> <Metric name="cr.node.exec.latency-p90" title="90th percentile latency" aggregateMax downsampleMax /> <Metric name="cr.node.exec.latency-p50" title="50th percentile latency" aggregateMax downsampleMax /> </Axis> </LineGraph> <LineGraph title="GC Pause Time" sources={sources} tooltip={`The ${sources ? "average and maximum" : ""} amount of processor time used by Go’s garbage collector per second ${specifier}. During garbage collection, application code execution is paused.`}> <Axis label="Milliseconds" format={ (n) => d3.format(".1f")(NanoToMilli(n)) }> <Metric name="cr.node.sys.gc.pause.ns" title={`${sources ? "" : "Avg "}Time`} aggregateAvg nonNegativeRate /> { (sources && sources[0]) ? null : <Metric name="cr.node.sys.gc.pause.ns" title="Max Time" aggregateMax nonNegativeRate /> } </Axis> </LineGraph> </GraphGroup> <GraphGroup groupId="node.queries" hide={this.props.groupId !== "node.queries"}> <h2>SQL Queries</h2> <LineGraph title="Reads" sources={sources} tooltip={`The average number of SELECT statements per second ${specifier}.`}> <Axis format={ d3.format(".1f") }> <Metric name="cr.node.sql.select.count" title="Selects" nonNegativeRate /> </Axis> </LineGraph> <LineGraph title="Writes" sources={sources} tooltip={`The average number of INSERT, UPDATE, and DELETE statements per second across ${specifier}.`}> <Axis format={ d3.format(".1f") }> <Metric name="cr.node.sql.update.count" title="Updates" nonNegativeRate /> <Metric name="cr.node.sql.insert.count" title="Inserts" nonNegativeRate /> <Metric name="cr.node.sql.delete.count" title="Deletes" nonNegativeRate /> </Axis> </LineGraph> <LineGraph title="Transactions" sources={sources} tooltip={`The average number of transactions committed, rolled back, or aborted per second ${specifier}.`}> <Axis format={ d3.format(".1f") }> <Metric name="cr.node.sql.txn.commit.count" title="Commits" nonNegativeRate /> <Metric name="cr.node.sql.txn.rollback.count" title="Rollbacks" nonNegativeRate /> <Metric name="cr.node.sql.txn.abort.count" title="Aborts" nonNegativeRate /> </Axis> </LineGraph> <LineGraph title="Schema Changes" sources={sources} tooltip={`The average number of DDL statements per second ${specifier}.`}> <Axis format={ d3.format(".1f") }> <Metric name="cr.node.sql.ddl.count" title="DDL Statements" nonNegativeRate /> </Axis> </LineGraph> </GraphGroup> <GraphGroup groupId="node.resources" hide={this.props.groupId !== "node.resources"}> <h2>System Resources</h2> <StackedAreaGraph title="CPU Usage" sources={sources} tooltip={`The average percentage of CPU used by CockroachDB (User %) and system-level operations (Sys %) ${specifier}.`}> <Axis format={ d3.format(".2%") }> <Metric name="cr.node.sys.cpu.user.percent" aggregateAvg title="CPU User %" /> <Metric name="cr.node.sys.cpu.sys.percent" aggregateAvg title="CPU Sys %" /> </Axis> </StackedAreaGraph> <LineGraph title="Memory Usage" sources={sources} tooltip={<div>{`Memory in use ${specifier}:`}<dl> <dt>RSS</dt><dd>Total memory in use by CockroachDB</dd> <dt>Go Allocated</dt><dd>Memory allocated by the Go layer</dd> <dt>Go Total</dt><dd>Total memory managed by the Go layer</dd> <dt>C Allocated</dt><dd>Memory allocated by the C layer</dd> <dt>C Total</dt><dd>Total memory managed by the C layer</dd> </dl></div>}> <Axis format={ Bytes }> <Metric name="cr.node.sys.rss" title="Total memory (RSS)" /> <Metric name="cr.node.sys.go.allocbytes" title="Go Allocated" /> <Metric name="cr.node.sys.go.totalbytes" title="Go Total" /> <Metric name="cr.node.sys.cgo.allocbytes" title="C Allocated" /> <Metric name="cr.node.sys.cgo.totalbytes" title="C Total" /> </Axis> </LineGraph> <StackedAreaGraph title="SQL Memory" sources={sources}> <Axis format={ Bytes }> <Metric name="cr.node.sql.mon.client.cur" title="Clients" /> </Axis> </StackedAreaGraph> <LineGraph title="Goroutine Count" sources={sources} tooltip={`The number of Goroutines ${specifier}. This count should rise and fall based on load.`}> <Axis format={ d3.format(".1f") }> <Metric name="cr.node.sys.goroutines" title="Goroutine Count" /> </Axis> </LineGraph> <LineGraph title="Cgo Calls" sources={sources} tooltip={`The average number of calls from Go to C per second ${specifier}.`}> <Axis format={ d3.format(".1f") }> <Metric name="cr.node.sys.cgocalls" title="Cgo Calls" nonNegativeRate /> </Axis> </LineGraph> </GraphGroup> <GraphGroup groupId="node.internals" hide={this.props.groupId !== "node.internals"}> <h2>Advanced Internals</h2> <StackedAreaGraph title="Key/Value Transactions" sources={sources}> <Axis label="transactions/sec" format={ d3.format(".1f") }> <Metric name="cr.node.txn.commits-count" title="Commits" nonNegativeRate /> <Metric name="cr.node.txn.commits1PC-count" title="Fast 1PC" nonNegativeRate /> <Metric name="cr.node.txn.aborts-count" title="Aborts" nonNegativeRate /> <Metric name="cr.node.txn.abandons-count" title="Abandons" nonNegativeRate /> </Axis> </StackedAreaGraph> <StackedAreaGraph title="Node Liveness" sources={sources}> <Axis label="Count" format={ d3.format(".1f") }> <Metric name="cr.node.liveness.heartbeatsuccesses" title="Heartbeat Successes" nonNegativeRate /> <Metric name="cr.node.liveness.heartbeatfailures" title="Heartbeat Failures" nonNegativeRate /> <Metric name="cr.node.liveness.epochincrements" title="Epoch Increments" nonNegativeRate /> </Axis> </StackedAreaGraph> <LineGraph title="Engine Memory Usage" sources={sources}> <Axis format={ Bytes }> <Metric name="cr.store.rocksdb.block.cache.usage" title="Block Cache" /> <Metric name="cr.store.rocksdb.block.cache.pinned-usage" title="Iterators" /> <Metric name="cr.store.rocksdb.memtable.total-size" title="Memtable" /> <Metric name="cr.store.rocksdb.table-readers-mem-estimate" title="Index" /> </Axis> </LineGraph> <StackedAreaGraph title="Block Cache Hits/Misses" sources={sources}> <Axis format={ d3.format(".1f") }> <Metric name="cr.store.rocksdb.block.cache.hits" title="Cache Hits" nonNegativeRate /> <Metric name="cr.store.rocksdb.block.cache.misses" title="Cache Missses" nonNegativeRate /> </Axis> </StackedAreaGraph> <StackedAreaGraph title="Range Events" sources={sources}> <Axis format={ d3.format(".1f") }> <Metric name="cr.store.range.splits" title="Splits" nonNegativeRate /> <Metric name="cr.store.range.adds" title="Adds" nonNegativeRate /> <Metric name="cr.store.range.removes" title="Removes" nonNegativeRate /> </Axis> </StackedAreaGraph> <LineGraph title="Flushes and Compactions" sources={sources}> <Axis format={ d3.format(".1f") }> <Metric name="cr.store.rocksdb.flushes" title="Flushes" nonNegativeRate /> <Metric name="cr.store.rocksdb.compactions" title="Compactions" nonNegativeRate /> </Axis> </LineGraph> <LineGraph title="Bloom Filter Prefix" sources={sources}> <Axis format={ d3.format(".1f") }> <Metric name="cr.store.rocksdb.bloom.filter.prefix.checked" title="Checked" nonNegativeRate /> <Metric name="cr.store.rocksdb.bloom.filter.prefix.useful" title="Useful" nonNegativeRate /> </Axis> </LineGraph> <LineGraph title="Read Amplification" sources={sources}> <Axis format={ d3.format(".1f") }> <Metric name="cr.store.rocksdb.read-amplification" title="Read Amplification" /> </Axis> </LineGraph> <StackedAreaGraph title="Raft Time" sources={sources}> <Axis label="Milliseconds" format={ (n) => d3.format(".1f")(NanoToMilli(n)) }><|fim▁hole|> <StackedAreaGraph title="Raft Messages received" sources={sources}> <Axis label="Count" format={ d3.format(".1f") }> <Metric name="cr.store.raft.rcvd.prop" title="MsgProp" nonNegativeRate /> <Metric name="cr.store.raft.rcvd.app" title="MsgApp" nonNegativeRate /> <Metric name="cr.store.raft.rcvd.appresp" title="MsgAppResp" nonNegativeRate /> <Metric name="cr.store.raft.rcvd.vote" title="MsgVote" nonNegativeRate /> <Metric name="cr.store.raft.rcvd.voteresp" title="MsgVoteResp" nonNegativeRate /> <Metric name="cr.store.raft.rcvd.snap" title="MsgSnap" nonNegativeRate /> <Metric name="cr.store.raft.rcvd.heartbeat" title="MsgHeartbeat" nonNegativeRate /> <Metric name="cr.store.raft.rcvd.heartbeatresp" title="MsgHeartbeatResp" nonNegativeRate /> <Metric name="cr.store.raft.rcvd.transferleader" title="MsgTransferLeader" nonNegativeRate /> <Metric name="cr.store.raft.rcvd.timeoutnow" title="MsgTimeoutNow" nonNegativeRate /> <Metric name="cr.store.raft.rcvd.dropped" title="MsgDropped" nonNegativeRate /> </Axis> </StackedAreaGraph> <LineGraph title="GCInfo metrics" sources={sources}> <Axis label="Count" format={ d3.format(".1f") }> <Metric name="cr.store.queue.gc.info.numkeysaffected" title="NumKeysAffected" nonNegativeRate /> <Metric name="cr.store.queue.gc.info.intentsconsidered" title="IntentsConsidered" nonNegativeRate /> <Metric name="cr.store.queue.gc.info.intenttxns" title="IntentTxns" nonNegativeRate /> <Metric name="cr.store.queue.gc.info.transactionspanscanned" title="TransactionSpanScanned" nonNegativeRate /> <Metric name="cr.store.queue.gc.info.transactionspangcaborted" title="TransactionSpanGCAborted" nonNegativeRate /> <Metric name="cr.store.queue.gc.info.transactionspangccommitted" title="TransactionSpanGCCommitted" nonNegativeRate /> <Metric name="cr.store.queue.gc.info.transactionspangcpending" title="TransactionSpanGCPending" nonNegativeRate /> <Metric name="cr.store.queue.gc.info.abortspanscanned" title="AbortSpanScanned" nonNegativeRate /> <Metric name="cr.store.queue.gc.info.abortspanconsidered" title="AbortSpanConsidered" nonNegativeRate /> <Metric name="cr.store.queue.gc.info.abortspangcnum" title="AbortSpanGCNum" nonNegativeRate /> <Metric name="cr.store.queue.gc.info.pushtxn" title="PushTxn" nonNegativeRate /> <Metric name="cr.store.queue.gc.info.resolvetotal" title="ResolveTotal" nonNegativeRate /> <Metric name="cr.store.queue.gc.info.resovlesuccess" title="ResolveSuccess" nonNegativeRate /> </Axis> </LineGraph> <LineGraph title="Raft Transport Queue Pending Count" sources={sources}> <Axis format={ d3.format(".1f") }> <Metric name="cr.store.raft.enqueued.pending" title="Outstanding message count in the Raft Transport queue to be sent over the network" /> <Metric name="cr.store.raft.heartbeats.pending" title="Outstanding individual heartbeats in the Raft Transport queue that have been coalesced" /> </Axis> </LineGraph> <LineGraph title="Replicas: Details" sources={sources}> <Axis format={ d3.format(".1f") }> <Metric name="cr.store.replicas.leaders" title="Leaders" /> <Metric name="cr.store.replicas.leaseholders" title="Lease Holders" /> <Metric name="cr.store.replicas.leaders_not_leaseholders" title="Leaders w/o Lease" /> <Metric name="cr.store.replicas.quiescent" title="Quiescent" /> </Axis> </LineGraph> <LineGraph title="Raft Ticks" sources={sources}> <Axis format={ d3.format(".1f") }> <Metric name="cr.store.raft.ticks" title="Raft Ticks" nonNegativeRate /> </Axis> </LineGraph> <LineGraph title="Critical Section Time" tooltip={`The maximum duration (capped at 1s) for which the corresponding mutex was held in the last minute ${specifier}.`} sources={sources}> <Axis format={ (n: number) => d3.format(".1f")(NanoToMilli(n)) } label="Milliseconds"> <Metric name="cr.store.mutex.storenanos-max" title="StoreMu" aggregateMax downsampleMax /> <Metric name="cr.store.mutex.schedulernanos-max" title="SchedulerMu" aggregateMax downsampleMax /> <Metric name="cr.store.mutex.replicananos-max" title="ReplicaMu" aggregateMax downsampleMax /> <Metric name="cr.store.mutex.raftnanos-max" title="RaftMu" aggregateMax downsampleMax /> </Axis> </LineGraph> <StackedAreaGraph title="SQL Memory (detailed)" sources={sources}> <Axis format={ Bytes }> <Metric name="cr.node.sql.mon.client.cur" title="Clients" /> <Metric name="cr.node.sql.mon.admin.cur" title="Admin" /> <Metric name="cr.node.sql.mon.internal.cur" title="Internal" /> </Axis> </StackedAreaGraph> <LineGraph title="SQL Session Cumulative Max Size" subtitle="(log10(Max) Per Percentile)" tooltip={`The maximum memory usage per SQL session (including session-bound and txn-bound data), displayed as log(max). Percentiles are first calculated on each node. For each percentile, the maximum usage across all nodes is then shown.`} sources={sources}> <Axis format={ (n: number) => d3.format(".3f")(n / 1000) } label="log10(Bytes)"> <Metric name="cr.node.sql.mon.client.max-max" title="Max Mem Usage (log10)" aggregateMax downsampleMax /> <Metric name="cr.node.sql.mon.client.max-p99" title="99th percentile max mem usage (log10)" aggregateMax downsampleMax /> <Metric name="cr.node.sql.mon.client.max-p90" title="90th percentile max mem usage (log10)" aggregateMax downsampleMax /> <Metric name="cr.node.sql.mon.client.max-p50" title="50th percentile max mem usage (log10)" aggregateMax downsampleMax /> </Axis> </LineGraph> <LineGraph title="SQL Session Cumulative Max Size (Admin)" subtitle="(log10(Max) Per Percentile)" tooltip={`The maximum memory usage per SQL admin session (including session-bound and txn-bound data), displayed as log(max). Percentiles are first calculated on each node. For each percentile, the maximum usage across all nodes is then shown.`} sources={sources}> <Axis format={ (n: number) => d3.format(".3f")(n / 1000) } label="log10(Bytes)"> <Metric name="cr.node.sql.mon.admin.max-max" title="Max Mem Usage (log10)" aggregateMax downsampleMax /> <Metric name="cr.node.sql.mon.admin.max-p99" title="99th percentile max mem usage (log10)" aggregateMax downsampleMax /> <Metric name="cr.node.sql.mon.admin.max-p90" title="90th percentile max mem usage (log10)" aggregateMax downsampleMax /> <Metric name="cr.node.sql.mon.admin.max-p50" title="50th percentile max mem usage (log10)" aggregateMax downsampleMax /> </Axis> </LineGraph> <LineGraph title="SQL Session Cumulative Max Size (Internal)" subtitle="(log10(Max) Per Percentile)" tooltip={`The maximum memory usage per SQL internal session (including session-bound and txn-bound data), displayed as log(max). Percentiles are first calculated on each node. For each percentile, the maximum usage across all nodes is then shown.`} sources={sources}> <Axis format={ (n: number) => d3.format(".3f")(n / 1000) } label="log10(Bytes)"> <Metric name="cr.node.sql.mon.internal.max-max" title="Max Mem Usage (log10)" aggregateMax downsampleMax /> <Metric name="cr.node.sql.mon.internal.max-p99" title="99th percentile max mem usage (log10)" aggregateMax downsampleMax /> <Metric name="cr.node.sql.mon.internal.max-p90" title="90th percentile max mem usage (log10)" aggregateMax downsampleMax /> <Metric name="cr.node.sql.mon.internal.max-p50" title="50th percentile max mem usage (log10)" aggregateMax downsampleMax /> </Axis> </LineGraph> <LineGraph title="SQL Txn Max Size" subtitle="(log10(Max) Per Percentile)" tooltip={`The maximum memory usage per SQL txn, displayed as log(max). Percentiles are first calculated on each node. For each percentile, the maximum usage across all nodes is then shown.`} sources={sources}> <Axis format={ (n: number) => d3.format(".3f")(n / 1000) } label="log10(Bytes)"> <Metric name="cr.node.sql.mon.client.txn.max-max" title="Max Mem Usage (log10)" aggregateMax downsampleMax /> <Metric name="cr.node.sql.mon.client.txn.max-p99" title="99th percentile max mem usage (log10)" aggregateMax downsampleMax /> <Metric name="cr.node.sql.mon.client.txn.max-p90" title="90th percentile max mem usage (log10)" aggregateMax downsampleMax /> <Metric name="cr.node.sql.mon.client.txn.max-p50" title="50th percentile max mem usage (log10)" aggregateMax downsampleMax /> </Axis> </LineGraph> <LineGraph title="SQL Txn Max Size (Admin)" subtitle="(log10(Max) Per Percentile)" tooltip={`The maximum memory usage per SQL admin session (including session-bound and txn-bound data), displayed as log(max). Percentiles are first calculated on each node. For each percentile, the maximum usage across all nodes is then shown.`} sources={sources}> <Axis format={ (n: number) => d3.format(".3f")(n / 1000) } label="log10(Bytes)"> <Metric name="cr.node.sql.mon.admin.txn.max-max" title="Max Mem Usage (log10)" aggregateMax downsampleMax /> <Metric name="cr.node.sql.mon.admin.txn.max-p99" title="99th percentile max mem usage (log10)" aggregateMax downsampleMax /> <Metric name="cr.node.sql.mon.admin.txn.max-p90" title="90th percentile max mem usage (log10)" aggregateMax downsampleMax /> <Metric name="cr.node.sql.mon.admin.txn.max-p50" title="50th percentile max mem usage (log10)" aggregateMax downsampleMax /> </Axis> </LineGraph> <LineGraph title="SQL Txn Max Size (Internal)" subtitle="(log10(Max) Per Percentile)" tooltip={`The maximum memory usage per SQL internal session (including session-bound and txn-bound data), displayed as log(max). Percentiles are first calculated on each node. For each percentile, the maximum usage across all nodes is then shown.`} sources={sources}> <Axis format={ (n: number) => d3.format(".3f")(n / 1000) } label="log10(Bytes)"> <Metric name="cr.node.sql.mon.internal.txn.max-max" title="Max Mem Usage (log10)" aggregateMax downsampleMax /> <Metric name="cr.node.sql.mon.internal.txn.max-p99" title="99th percentile max mem usage (log10)" aggregateMax downsampleMax /> <Metric name="cr.node.sql.mon.internal.txn.max-p90" title="90th percentile max mem usage (log10)" aggregateMax downsampleMax /> <Metric name="cr.node.sql.mon.internal.txn.max-p50" title="50th percentile max mem usage (log10)" aggregateMax downsampleMax /> </Axis> </LineGraph> </GraphGroup> </div> </div>; } }<|fim▁end|>
<Metric name="cr.store.raft.process.workingnanos" title="Working" nonNegativeRate /> <Metric name="cr.store.raft.process.tickingnanos" title="Ticking" nonNegativeRate /> </Axis> </StackedAreaGraph>
<|file_name|>AttributesProcessor.ts<|end_file_name|><|fim▁begin|>/* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ import { Context } from '@opentelemetry/api'; import { Attributes } from '@opentelemetry/api-metrics-wip'; /** * The {@link AttributesProcessor} is responsible for customizing which * attribute(s) are to be reported as metrics dimension(s) and adding * additional dimension(s) from the {@link Context}. */ export abstract class AttributesProcessor { /** * Process the metric instrument attributes. * * @param incoming The metric instrument attributes. * @param context The active context when the instrument is synchronous. * `undefined` otherwise. */ abstract process(incoming: Attributes, context?: Context): Attributes; static Noop() { return NOOP; } } export class NoopAttributesProcessor extends AttributesProcessor { process(incoming: Attributes, _context?: Context) { return incoming; } } /** * {@link AttributesProcessor} that filters by allowed attribute names and drops any names that are not in the * allow list. */ export class FilteringAttributesProcessor extends AttributesProcessor { constructor(private _allowedAttributeNames: string[]) { super(); } process(incoming: Attributes, _context: Context): Attributes { const filteredAttributes: Attributes = {};<|fim▁hole|> .forEach(attributeName => filteredAttributes[attributeName] = incoming[attributeName]); return filteredAttributes; } } const NOOP = new NoopAttributesProcessor;<|fim▁end|>
Object.keys(incoming) .filter(attributeName => this._allowedAttributeNames.includes(attributeName))
<|file_name|>stringtableduplicates.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 import os import sys import xml.dom from xml.dom import minidom # STRINGTABLE DIAG TOOL # Author: KoffeinFlummi # --------------------- # Counts duplicates stringtable entries def check_module(projectpath, module): """ Checks the given module for all the different languages. """ localized = [] <|fim▁hole|> except IOError: return 0 keys = xmldoc.getElementsByTagName("Key") duplicates = 0 for key in keys: children = key.childNodes entries = [] for c in range(children.length): entries.append(children.item(c)) entries = list(filter(lambda x: x.nodeType == x.ELEMENT_NODE, entries)) entries = list(map(lambda x: str(x.nodeName).lower(), entries)) diff = len(entries) - len(list(set(entries))) duplicates += diff if diff > 0: print(key.getAttribute("ID")) return duplicates def main(): scriptpath = os.path.realpath(__file__) projectpath = os.path.dirname(os.path.dirname(scriptpath)) projectpath = os.path.join(projectpath, "addons") print("###############################") print("# Stringtable Duplicates Tool #") print("###############################\n") duplicates = 0 for module in os.listdir(projectpath): d = check_module(projectpath, module) print("# {} {}".format(module.ljust(20), d)) duplicates += d print("\nTotal number of duplicates: {}".format(duplicates)) if __name__ == "__main__": main()<|fim▁end|>
stringtablepath = os.path.join(projectpath, module, "stringtable.xml") try: xmldoc = minidom.parse(stringtablepath)
<|file_name|>cds.js<|end_file_name|><|fim▁begin|>/** * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // @codekit-prepend 'third_party/signals.min.js' // @codekit-prepend 'third_party/requestAnimationFrame.js' var CDS = {}; // @codekit-append 'helper/event-publisher.js' // @codekit-append 'helper/util.js' // @codekit-append 'helper/history.js' // @codekit-append 'helper/analytics.js' // @codekit-append 'helper/theme.js' // @codekit-append 'helper/video-embedder.js' // @codekit-append 'components/button.js' // @codekit-append 'components/card.js' // @codekit-append 'components/cards.js' // @codekit-append 'components/toast.js' // @codekit-append 'components/masthead.js'<|fim▁hole|>// @codekit-append 'bootstrap.js'<|fim▁end|>
// @codekit-append 'components/schedule.js'
<|file_name|>app.go<|end_file_name|><|fim▁begin|>package app import ( "github.com/GodSlave/MyGoServer/module" "github.com/GodSlave/MyGoServer/conf" "os/exec" "os" "path/filepath" "fmt" "flag" "github.com/GodSlave/MyGoServer/log" "github.com/GodSlave/MyGoServer/module/base" "github.com/GodSlave/MyGoServer/rpc/base" "github.com/GodSlave/MyGoServer/rpc" "strings" "github.com/GodSlave/MyGoServer/db" "github.com/go-xorm/xorm" "github.com/garyburd/redigo/redis" "github.com/GodSlave/MyGoServer/utils" "time" "github.com/GodSlave/MyGoServer/master" "os/signal" "math" "hash/crc32" "github.com/GodSlave/MyGoServer/base" ) type DefaultApp struct { module.App version string serverList map[string]module.ServerSession byteServerList map[byte]module.ServerSession settings conf.Config routes map[string]func(app module.App, Type string, hash string) module.ServerSession byteRoutes map[byte]func(app module.App, Type byte, hash string) module.ServerSession defaultRoutes func(app module.App, Type string, hash string) module.ServerSession byteDefaultRoutes func(app module.App, Type byte, hash string) module.ServerSession rpcserializes map[string]module.RPCSerialize Engine *xorm.Engine redisPool *redis.Pool psc *redis.PubSubConn userManager module.UserManager initDownCallback module.OnInitDownCallBack masterServer master.Master masterClient master.MasterClient moduleManger *basemodule.ModuleManager } func NewApp() module.App { newApp := new(DefaultApp) newApp.routes = map[string]func(app module.App, Type string, hash string) module.ServerSession{} newApp.byteRoutes = map[byte]func(app module.App, Type byte, hash string) module.ServerSession{} newApp.byteServerList = map[byte]module.ServerSession{} newApp.serverList = map[string]module.ServerSession{} newApp.defaultRoutes = func(app module.App, Type string, hash string) module.ServerSession { if newApp.masterClient != nil { serverSession := newApp.masterClient.GetModule(Type) if serverSession != nil { return *serverSession } } else { servers := app.GetServersByType(Type) if len(servers) == 0 { log.Error("no smodule find %s", Type) return nil } index := int(math.Abs(float64(crc32.ChecksumIEEE([]byte(hash))))) % len(servers) return servers[index] } return nil } newApp.byteDefaultRoutes = func(app module.App, Type byte, hash string) module.ServerSession { if newApp.masterClient != nil { return *newApp.masterClient.GetModuleByByte(Type) } else { servers := app.GetServersByByteType(Type) if len(servers) == 0 { log.Error("no module find %v", Type) return nil } index := int(math.Abs(float64(crc32.ChecksumIEEE([]byte(hash))))) % len(servers) return servers[index] } return nil } newApp.rpcserializes = map[string]module.RPCSerialize{} newApp.version = "0.0.1" return newApp } func (app *DefaultApp) Run(mods ...module.Module) error { file, _ := exec.LookPath(os.Args[0]) ApplicationPath, _ := filepath.Abs(file) ApplicationDir, _ := filepath.Split(ApplicationPath) defaultPath := fmt.Sprintf("%sconf"+string(filepath.Separator)+"server.json", ApplicationDir) confPath := flag.String("conf", defaultPath, "Server configuration file path") ProcessID := flag.String("pid", "development", "Server ProcessID?") Logdir := flag.String("log", fmt.Sprintf("%slogs", ApplicationDir), "Log file directory?") flag.Parse() //解析输入的参数 f, err := os.Open(*confPath) if err != nil { panic(err) } _, err = os.Open(*Logdir) if err != nil { //文件不存在 err := os.Mkdir(*Logdir, os.ModePerm) // if err != nil { fmt.Println(err) } } log.Info("Server configuration file path [%s]", *confPath) conf.LoadConfig(f.Name()) //加载配置文件 app.Configure(conf.Conf) //配置信息 log.Init(conf.Conf.Debug, *ProcessID, *Logdir) log.Info("server %v starting up at %v", app.version, time.Now().Unix()) log.Debug("start connect DB %v", conf.Conf.DB.SQL) app.userManager = InitUserManager(app, conf.Conf.OnlineLimit) //sql sql := db.BaseSql{ } sql.Url = conf.Conf.DB.SQL log.Info(sql.Url) sql.InitDB() sql.CheckMigrate() app.Engine = sql.Engine defer app.Engine.Close() url := app.GetSettings().DB.Redis app.redisPool = utils.GetRedisFactory().GetPool(url) defer app.redisPool.Close() // module log.Info("start register module %v", conf.Conf.DB.SQL) app.moduleManger = basemodule.NewModuleManager() for i := 0; i < len(mods); i++ { app.moduleManger.Register(mods[i]) } if conf.Conf.Master.ISRealMaster && conf.Conf.Master.Enable { app.masterServer = master.NewMaster(conf.Conf.Name, conf.Conf.Master) } if conf.Conf.Master.Enable { app.masterClient = master.NewMasterClient(conf.Conf.Master, conf.Conf.Name, app, app.moduleManger) } app.OnInit(app.settings) app.moduleManger.Init(app, *ProcessID) if app.initDownCallback != nil { app.initDownCallback(app) } // close c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, os.Kill) sig := <-c app.moduleManger.Destroy() app.OnDestroy() log.Info("mqant closing down (signal: %v)", sig) return nil } func (app *DefaultApp) Route(moduleType string, fn func(app module.App, Type string, hash string) module.ServerSession) error { app.routes[moduleType] = fn return nil } func (app *DefaultApp) getRoute(moduleType string) func(app module.App, Type string, hash string) module.ServerSession { fn := app.routes[moduleType] if fn == nil { //如果没有设置的路由,则使用默认的 return app.defaultRoutes } return fn } func (app *DefaultApp) getByteRoute(moduleType byte) func(app module.App, Type byte, hash string) module.ServerSession { fn := app.byteRoutes[moduleType] if fn == nil { //如果没有设置的路由,则使用默认的 return app.byteDefaultRoutes } return fn } func (app *DefaultApp) AddRPCSerialize(name string, Interface module.RPCSerialize) error { if _, ok := app.rpcserializes[name]; ok { return fmt.Errorf("The name(%s) has been occupied", name) } app.rpcserializes[name] = Interface return nil } func (app *DefaultApp) GetRPCSerialize() (map[string]module.RPCSerialize) { return app.rpcserializes } func (app *DefaultApp) Configure(settings conf.Config) error { app.settings = settings return nil } /** */<|fim▁hole|>func (app *DefaultApp) OnInit(settings conf.Config) error { app.serverList = make(map[string]module.ServerSession) for Type, ModuleInfos := range settings.Module { for _, moduel := range ModuleInfos { m := app.serverList[moduel.Id] if m != nil { //如果Id已经存在,说明有两个相同Id的模块,这种情况不能被允许,这里就直接抛异常 强制崩溃以免以后调试找不到问题 panic(fmt.Sprintf("ServerId (%s) Type (%s) of the modules already exist Can not be reused ServerId (%s) Type (%s)", m.GetId(), m.GetType(), moduel.Id, Type)) } client, err := defaultrpc.NewRPCClient(app, moduel.Id) if err != nil { continue } if moduel.Rabbitmq != nil { //如果远程的rpc存在则创建一个对应的客户端 client.NewRabbitmqClient(moduel.Rabbitmq) } if moduel.Redis != nil { //如果远程的rpc存在则创建一个对应的客户端 client.NewRedisClient(moduel.Redis) } session := basemodule.NewServerSession(moduel.Id, Type, moduel.ByteID, client) app.serverList[moduel.Id] = session app.byteServerList[moduel.ByteID] = session log.Info("RPCClient create success type(%s) id(%s)", Type, moduel.Id) } } return nil } func (app *DefaultApp) OnDestroy() error { for id, session := range app.serverList { err := session.GetRpc().Done() if err != nil { log.Warning("RPCClient close fail type(%s) id(%s)", session.GetType(), id) } else { log.Info("RPCClient close success type(%s) id(%s)", session.GetType(), id) } } return nil } func (app *DefaultApp) RegisterLocalClient(serverId string, server mqrpc.RPCServer) error { if session, ok := app.serverList[serverId]; ok { return session.GetRpc().NewLocalClient(server) } else { return fmt.Errorf("Server(%s) Not Found", serverId) } return nil } func (app *DefaultApp) GetServersById(serverId string) (module.ServerSession, error) { if session, ok := app.serverList[serverId]; ok { return session, nil } else { return nil, fmt.Errorf("Server(%s) Not Found", serverId) } } func (app *DefaultApp) GetServersByType(Type string) []module.ServerSession { sessions := make([]module.ServerSession, 0) for _, session := range app.serverList { if session.GetType() == Type { sessions = append(sessions, session) } } return sessions } func (app *DefaultApp) GetServersByByteType(Type byte) []module.ServerSession { sessions := make([]module.ServerSession, 0) for _, session := range app.serverList { if session.GetByteType() == Type { sessions = append(sessions, session) } } return sessions } func (app *DefaultApp) GetRouteServers(filter string, hash string) (s module.ServerSession, err error) { sl := strings.Split(filter, "@") if len(sl) == 2 { moduleID := sl[1] if moduleID != "" { return app.GetServersById(moduleID) } } moduleType := sl[0] route := app.getRoute(moduleType) if route == nil { return nil, base.ErrFrozen } s = route(app, moduleType, hash) if s == nil { log.Error("Server(type : %s) Not Found", moduleType) } return } func (app *DefaultApp) GetByteRouteServers(filter byte, hash string) (s module.ServerSession, err error) { route := app.getByteRoute(filter) s = route(app, filter, hash) if s == nil { log.Error("Server(type : %x) Not Found", filter) } return } func (app *DefaultApp) GetSettings() conf.Config { return app.settings } func (app *DefaultApp) RpcInvokeArgs(module module.RPCModule, moduleType string, _func string, sessionId string, args []byte) (result []byte, err *base.ErrorCode) { server, e := app.GetRouteServers(moduleType, module.GetServerId()) if e != nil { err = base.NewError(404, e.Error()) return } return server.CallArgs(_func, sessionId, args) } func (app *DefaultApp) RpcAllInvokeArgs(module module.RPCModule, moduleType string, _func string, sessionId string, args []byte) (result [][]byte, err []*base.ErrorCode) { servers := app.GetServersByType(moduleType) err = []*base.ErrorCode{} for _, server := range servers { resultItem, errItem := server.CallArgs(_func, sessionId, args) result = append(result, resultItem) err = append(err, errItem) } return } func (app *DefaultApp) RpcInvokeNRArgs(module module.RPCModule, moduleType string, _func string, sessionId string, args []byte) (err error) { server, err := app.GetRouteServers(moduleType, module.GetServerId()) if err != nil { return } return server.CallNRArgs(_func, sessionId, args) } func (app *DefaultApp) GetSqlEngine() *xorm.Engine { return app.Engine } func (app *DefaultApp) GetRedis() *redis.Pool { return app.redisPool } func (app *DefaultApp) GetUserManager() module.UserManager { return app.userManager } func (app *DefaultApp) SetInitDownCallBack(callBack module.OnInitDownCallBack) { app.initDownCallback = callBack } func (app *DefaultApp) GetModuleManager() *basemodule.ModuleManager { return app.moduleManger } func (app *DefaultApp) GetConfig() conf.Config{ return app.settings }<|fim▁end|>
<|file_name|>utils.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ OneLogin_Saml2_Utils class Copyright (c) 2014, OneLogin, Inc. All rights reserved. Auxiliary class of OneLogin's Python Toolkit. """ import base64 from datetime import datetime import calendar from hashlib import sha1, sha256, sha384, sha512 from isodate import parse_duration as duration_parser import re from textwrap import wrap from uuid import uuid4 import zlib import xmlsec from onelogin.saml2 import compat from onelogin.saml2.constants import OneLogin_Saml2_Constants from onelogin.saml2.errors import OneLogin_Saml2_Error from onelogin.saml2.xml_utils import OneLogin_Saml2_XML try: from urllib.parse import quote_plus # py3 except ImportError: from urllib import quote_plus # py2 class OneLogin_Saml2_Utils(object): """ Auxiliary class that contains several utility methods to parse time, urls, add sign, encrypt, decrypt, sign validation, handle xml ... """ @staticmethod def escape_url(url, lowercase_urlencoding=False): """ escape the non-safe symbols in url The encoding used by ADFS 3.0 is not compatible with python's quote_plus (ADFS produces lower case hex numbers and quote_plus produces upper case hex numbers) :param url: the url to escape :type url: str :param lowercase_urlencoding: lowercase or no :type lowercase_urlencoding: boolean :return: the escaped url :rtype str """ encoded = quote_plus(url) return re.sub(r"%[A-F0-9]{2}", lambda m: m.group(0).lower(), encoded) if lowercase_urlencoding else encoded @staticmethod def b64encode(data): """base64 encode""" return compat.to_string(base64.b64encode(compat.to_bytes(data))) @staticmethod def b64decode(data): """base64 decode""" return base64.b64decode(data) @staticmethod def decode_base64_and_inflate(value, ignore_zip=False): """ base64 decodes and then inflates according to RFC1951 :param value: a deflated and encoded string :type value: string :param ignore_zip: ignore zip errors :returns: the string after decoding and inflating :rtype: string """ encoded = OneLogin_Saml2_Utils.b64decode(value) try: return zlib.decompress(encoded, -15) except zlib.error: if not ignore_zip: raise return encoded @staticmethod def deflate_and_base64_encode(value): """ Deflates and then base64 encodes a string :param value: The string to deflate and encode :type value: string :returns: The deflated and encoded string :rtype: string """ return OneLogin_Saml2_Utils.b64encode(zlib.compress(compat.to_bytes(value))[2:-4]) @staticmethod def format_cert(cert, heads=True): """ Returns a x509 cert (adding header & footer if required). :param cert: A x509 unformatted cert :type: string :param heads: True if we want to include head and footer :type: boolean :returns: Formatted cert :rtype: string """ x509_cert = cert.replace('\x0D', '') x509_cert = x509_cert.replace('\r', '') x509_cert = x509_cert.replace('\n', '') if len(x509_cert) > 0: x509_cert = x509_cert.replace('-----BEGIN CERTIFICATE-----', '') x509_cert = x509_cert.replace('-----END CERTIFICATE-----', '') x509_cert = x509_cert.replace(' ', '') if heads: x509_cert = "-----BEGIN CERTIFICATE-----\n" + "\n".join(wrap(x509_cert, 64)) + "\n-----END CERTIFICATE-----\n" return x509_cert @staticmethod def format_private_key(key, heads=True): """ Returns a private key (adding header & footer if required). :param key A private key :type: string :param heads: True if we want to include head and footer :type: boolean :returns: Formated private key :rtype: string """ private_key = key.replace('\x0D', '') private_key = private_key.replace('\r', '') private_key = private_key.replace('\n', '') if len(private_key) > 0: if private_key.find('-----BEGIN PRIVATE KEY-----') != -1: private_key = private_key.replace('-----BEGIN PRIVATE KEY-----', '') private_key = private_key.replace('-----END PRIVATE KEY-----', '') private_key = private_key.replace(' ', '') if heads: private_key = "-----BEGIN PRIVATE KEY-----\n" + "\n".join(wrap(private_key, 64)) + "\n-----END PRIVATE KEY-----\n" else: private_key = private_key.replace('-----BEGIN RSA PRIVATE KEY-----', '') private_key = private_key.replace('-----END RSA PRIVATE KEY-----', '') private_key = private_key.replace(' ', '') if heads: private_key = "-----BEGIN RSA PRIVATE KEY-----\n" + "\n".join(wrap(private_key, 64)) + "\n-----END RSA PRIVATE KEY-----\n" return private_key @staticmethod def redirect(url, parameters={}, request_data={}): """ Executes a redirection to the provided url (or return the target url). :param url: The target url :type: string :param parameters: Extra parameters to be passed as part of the url :type: dict :param request_data: The request as a dict :type: dict :returns: Url :rtype: string """ assert isinstance(url, compat.str_type) assert isinstance(parameters, dict) if url.startswith('/'): url = '%s%s' % (OneLogin_Saml2_Utils.get_self_url_host(request_data), url) # Verify that the URL is to a http or https site. if re.search('^https?://', url) is None: raise OneLogin_Saml2_Error( 'Redirect to invalid URL: ' + url, OneLogin_Saml2_Error.REDIRECT_INVALID_URL ) # Add encoded parameters if url.find('?') < 0: param_prefix = '?' else: param_prefix = '&' for name, value in parameters.items(): if value is None: param = OneLogin_Saml2_Utils.escape_url(name) elif isinstance(value, list): param = '' for val in value: param += OneLogin_Saml2_Utils.escape_url(name) + '[]=' + OneLogin_Saml2_Utils.escape_url(val) + '&' if len(param) > 0: param = param[0:-1] else: param = OneLogin_Saml2_Utils.escape_url(name) + '=' + OneLogin_Saml2_Utils.escape_url(value) if param: url += param_prefix + param param_prefix = '&' return url @staticmethod def get_self_url_host(request_data): """ Returns the protocol + the current host + the port (if different than common ports). :param request_data: The request as a dict :type: dict :return: Url :rtype: string """ current_host = OneLogin_Saml2_Utils.get_self_host(request_data) port = '' if OneLogin_Saml2_Utils.is_https(request_data): protocol = 'https' else: protocol = 'http' if 'server_port' in request_data and request_data['server_port'] is not None: port_number = str(request_data['server_port']) port = ':' + port_number if protocol == 'http' and port_number == '80': port = '' elif protocol == 'https' and port_number == '443': port = '' return '%s://%s%s' % (protocol, current_host, port) @staticmethod def get_self_host(request_data): """ Returns the current host. :param request_data: The request as a dict :type: dict :return: The current host :rtype: string """ if 'http_host' in request_data: current_host = request_data['http_host'] elif 'server_name' in request_data: current_host = request_data['server_name'] else: raise Exception('No hostname defined') if ':' in current_host: current_host_data = current_host.split(':') possible_port = current_host_data[-1] try: int(possible_port) current_host = current_host_data[0] except ValueError: current_host = ':'.join(current_host_data) return current_host @staticmethod def is_https(request_data): """ Checks if https or http. :param request_data: The request as a dict :type: dict :return: False if https is not active :rtype: boolean """ is_https = 'https' in request_data and request_data['https'] != 'off' is_https = is_https or ('server_port' in request_data and str(request_data['server_port']) == '443') return is_https @staticmethod def get_self_url_no_query(request_data): """ Returns the URL of the current host + current view. :param request_data: The request as a dict :type: dict :return: The url of current host + current view :rtype: string """ self_url_host = OneLogin_Saml2_Utils.get_self_url_host(request_data) script_name = request_data['script_name'] if script_name: if script_name[0] != '/': script_name = '/' + script_name else: script_name = '' self_url_no_query = self_url_host + script_name if 'path_info' in request_data: self_url_no_query += request_data['path_info'] return self_url_no_query @staticmethod def get_self_routed_url_no_query(request_data): """ Returns the routed URL of the current host + current view. :param request_data: The request as a dict :type: dict :return: The url of current host + current view :rtype: string """ self_url_host = OneLogin_Saml2_Utils.get_self_url_host(request_data) route = '' if 'request_uri' in request_data and request_data['request_uri']: route = request_data['request_uri'] if 'query_string' in request_data and request_data['query_string']: route = route.replace(request_data['query_string'], '') return self_url_host + route @staticmethod def get_self_url(request_data): """ Returns the URL of the current host + current view + query. :param request_data: The request as a dict :type: dict :return: The url of current host + current view + query :rtype: string """ self_url_host = OneLogin_Saml2_Utils.get_self_url_host(request_data) request_uri = '' if 'request_uri' in request_data: request_uri = request_data['request_uri'] if not request_uri.startswith('/'): match = re.search('^https?://[^/]*(/.*)', request_uri) if match is not None: request_uri = match.groups()[0] return self_url_host + request_uri <|fim▁hole|> """ Generates an unique string (used for example as ID for assertions). :return: A unique string :rtype: string """ return 'ONELOGIN_%s' % sha1(compat.to_bytes(uuid4().hex)).hexdigest() @staticmethod def parse_time_to_SAML(time): """ Converts a UNIX timestamp to SAML2 timestamp on the form yyyy-mm-ddThh:mm:ss(\.s+)?Z. :param time: The time we should convert (DateTime). :type: string :return: SAML2 timestamp. :rtype: string """ data = datetime.utcfromtimestamp(float(time)) return data.strftime('%Y-%m-%dT%H:%M:%SZ') @staticmethod def parse_SAML_to_time(timestr): """ Converts a SAML2 timestamp on the form yyyy-mm-ddThh:mm:ss(\.s+)?Z to a UNIX timestamp. The sub-second part is ignored. :param timestr: The time we should convert (SAML Timestamp). :type: string :return: Converted to a unix timestamp. :rtype: int """ try: data = datetime.strptime(timestr, '%Y-%m-%dT%H:%M:%SZ') except ValueError: data = datetime.strptime(timestr, '%Y-%m-%dT%H:%M:%S.%fZ') return calendar.timegm(data.utctimetuple()) @staticmethod def now(): """ :return: unix timestamp of actual time. :rtype: int """ return calendar.timegm(datetime.utcnow().utctimetuple()) @staticmethod def parse_duration(duration, timestamp=None): """ Interprets a ISO8601 duration value relative to a given timestamp. :param duration: The duration, as a string. :type: string :param timestamp: The unix timestamp we should apply the duration to. Optional, default to the current time. :type: string :return: The new timestamp, after the duration is applied. :rtype: int """ assert isinstance(duration, compat.str_type) assert timestamp is None or isinstance(timestamp, int) timedelta = duration_parser(duration) if timestamp is None: data = datetime.utcnow() + timedelta else: data = datetime.utcfromtimestamp(timestamp) + timedelta return calendar.timegm(data.utctimetuple()) @staticmethod def get_expire_time(cache_duration=None, valid_until=None): """ Compares 2 dates and returns the earliest. :param cache_duration: The duration, as a string. :type: string :param valid_until: The valid until date, as a string or as a timestamp :type: string :return: The expiration time. :rtype: int """ expire_time = None if cache_duration is not None: expire_time = OneLogin_Saml2_Utils.parse_duration(cache_duration) if valid_until is not None: if isinstance(valid_until, int): valid_until_time = valid_until else: valid_until_time = OneLogin_Saml2_Utils.parse_SAML_to_time(valid_until) if expire_time is None or expire_time > valid_until_time: expire_time = valid_until_time if expire_time is not None: return '%d' % expire_time return None @staticmethod def delete_local_session(callback=None): """ Deletes the local session. """ if callback is not None: callback() @staticmethod def calculate_x509_fingerprint(x509_cert, alg='sha1'): """ Calculates the fingerprint of a x509cert. :param x509_cert: x509 cert :type: string :param alg: The algorithm to build the fingerprint :type: string :returns: fingerprint :rtype: string """ assert isinstance(x509_cert, compat.str_type) lines = x509_cert.split('\n') data = '' for line in lines: # Remove '\r' from end of line if present. line = line.rstrip() if line == '-----BEGIN CERTIFICATE-----': # Delete junk from before the certificate. data = '' elif line == '-----END CERTIFICATE-----': # Ignore data after the certificate. break elif line == '-----BEGIN PUBLIC KEY-----' or line == '-----BEGIN RSA PRIVATE KEY-----': # This isn't an X509 certificate. return None else: # Append the current line to the certificate data. data += line decoded_data = base64.b64decode(compat.to_bytes(data)) if alg == 'sha512': fingerprint = sha512(decoded_data) elif alg == 'sha384': fingerprint = sha384(decoded_data) elif alg == 'sha256': fingerprint = sha256(decoded_data) else: fingerprint = sha1(decoded_data) return fingerprint.hexdigest().lower() @staticmethod def format_finger_print(fingerprint): """ Formats a fingerprint. :param fingerprint: fingerprint :type: string :returns: Formatted fingerprint :rtype: string """ formatted_fingerprint = fingerprint.replace(':', '') return formatted_fingerprint.lower() @staticmethod def generate_name_id(value, sp_nq, sp_format, cert=None, debug=False, nq=None): """ Generates a nameID. :param value: fingerprint :type: string :param sp_nq: SP Name Qualifier :type: string :param sp_format: SP Format :type: string :param cert: IdP Public Cert to encrypt the nameID :type: string :param debug: Activate the xmlsec debug :type: bool :returns: DOMElement | XMLSec nameID :rtype: string :param nq: IDP Name Qualifier :type: string """ root = OneLogin_Saml2_XML.make_root('{%s}container' % OneLogin_Saml2_Constants.NS_SAML, nsmap={'saml': OneLogin_Saml2_Constants.NS_SAML}) name_id = OneLogin_Saml2_XML.make_child(root, '{%s}NameID' % OneLogin_Saml2_Constants.NS_SAML, nsmap={'saml2': OneLogin_Saml2_Constants.NS_SAML}) if sp_nq is not None: name_id.set('SPNameQualifier', sp_nq) name_id.set('Format', sp_format) if nq is not None: name_id.set('NameQualifier', nq) name_id.text = value if cert is not None: xmlsec.enable_debug_trace(debug) # Load the public cert manager = xmlsec.KeysManager() manager.add_key(xmlsec.Key.from_memory(cert, xmlsec.KeyFormat.CERT_PEM, None)) # Prepare for encryption enc_data = xmlsec.template.encrypted_data_create( root, xmlsec.Transform.AES128, type=xmlsec.EncryptionType.ELEMENT, ns="xenc") xmlsec.template.encrypted_data_ensure_cipher_value(enc_data) key_info = xmlsec.template.encrypted_data_ensure_key_info(enc_data, ns="dsig") enc_key = xmlsec.template.add_encrypted_key(key_info, xmlsec.Transform.RSA_OAEP) xmlsec.template.encrypted_data_ensure_cipher_value(enc_key) # Encrypt! enc_ctx = xmlsec.EncryptionContext(manager) enc_ctx.key = xmlsec.Key.generate(xmlsec.KeyData.AES, 128, xmlsec.KeyDataType.SESSION) enc_data = enc_ctx.encrypt_xml(enc_data, name_id) return '<saml:EncryptedID>' + compat.to_string(OneLogin_Saml2_XML.to_string(enc_data)) + '</saml:EncryptedID>' else: return OneLogin_Saml2_XML.extract_tag_text(root, "saml:NameID") @staticmethod def get_status(dom): """ Gets Status from a Response. :param dom: The Response as XML :type: Document :returns: The Status, an array with the code and a message. :rtype: dict """ status = {} status_entry = OneLogin_Saml2_XML.query(dom, '/samlp:Response/samlp:Status') if len(status_entry) == 0: raise Exception('Missing Status on response') code_entry = OneLogin_Saml2_XML.query(dom, '/samlp:Response/samlp:Status/samlp:StatusCode', status_entry[0]) if len(code_entry) == 0: raise Exception('Missing Status Code on response') code = code_entry[0].values()[0] status['code'] = code message_entry = OneLogin_Saml2_XML.query(dom, '/samlp:Response/samlp:Status/samlp:StatusMessage', status_entry[0]) if len(message_entry) == 0: subcode_entry = OneLogin_Saml2_XML.query(dom, '/samlp:Response/samlp:Status/samlp:StatusCode/samlp:StatusCode', status_entry[0]) if len(subcode_entry) > 0: status['msg'] = subcode_entry[0].values()[0] else: status['msg'] = '' else: status['msg'] = message_entry[0].text return status @staticmethod def decrypt_element(encrypted_data, key, debug=False): """ Decrypts an encrypted element. :param encrypted_data: The encrypted data. :type: lxml.etree.Element | DOMElement | basestring :param key: The key. :type: string :param debug: Activate the xmlsec debug :type: bool :returns: The decrypted element. :rtype: lxml.etree.Element """ encrypted_data = OneLogin_Saml2_XML.to_etree(encrypted_data) xmlsec.enable_debug_trace(debug) manager = xmlsec.KeysManager() manager.add_key(xmlsec.Key.from_memory(key, xmlsec.KeyFormat.PEM, None)) enc_ctx = xmlsec.EncryptionContext(manager) return enc_ctx.decrypt(encrypted_data) @staticmethod def add_sign(xml, key, cert, debug=False, sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA1): """ Adds signature key and senders certificate to an element (Message or Assertion). :param xml: The element we should sign :type: string | Document :param key: The private key :type: string :param cert: The public :type: string :param debug: Activate the xmlsec debug :type: bool :param sign_algorithm: Signature algorithm method :type sign_algorithm: string """ if xml is None or xml == '': raise Exception('Empty string supplied as input') elem = OneLogin_Saml2_XML.to_etree(xml) xmlsec.enable_debug_trace(debug) xmlsec.tree.add_ids(elem, ["ID"]) # Sign the metadata with our private key. sign_algorithm_transform_map = { OneLogin_Saml2_Constants.DSA_SHA1: xmlsec.Transform.DSA_SHA1, OneLogin_Saml2_Constants.RSA_SHA1: xmlsec.Transform.RSA_SHA1, OneLogin_Saml2_Constants.RSA_SHA256: xmlsec.Transform.RSA_SHA256, OneLogin_Saml2_Constants.RSA_SHA384: xmlsec.Transform.RSA_SHA384, OneLogin_Saml2_Constants.RSA_SHA512: xmlsec.Transform.RSA_SHA512 } sign_algorithm_transform = sign_algorithm_transform_map.get(sign_algorithm, xmlsec.Transform.RSA_SHA1) signature = xmlsec.template.create(elem, xmlsec.Transform.EXCL_C14N, sign_algorithm_transform, ns='ds') issuer = OneLogin_Saml2_XML.query(elem, '//saml:Issuer') if len(issuer) > 0: issuer = issuer[0] issuer.addnext(signature) else: elem[0].insert(0, signature) elem_id = elem.get('ID', None) if elem_id: elem_id = '#' + elem_id ref = xmlsec.template.add_reference(signature, xmlsec.Transform.SHA1, uri=elem_id) xmlsec.template.add_transform(ref, xmlsec.Transform.ENVELOPED) xmlsec.template.add_transform(ref, xmlsec.Transform.EXCL_C14N) key_info = xmlsec.template.ensure_key_info(signature) xmlsec.template.add_x509_data(key_info) dsig_ctx = xmlsec.SignatureContext() sign_key = xmlsec.Key.from_memory(key, xmlsec.KeyFormat.PEM, None) sign_key.load_cert_from_memory(cert, xmlsec.KeyFormat.PEM) dsig_ctx.key = sign_key dsig_ctx.sign(signature) return OneLogin_Saml2_XML.to_string(elem) @staticmethod def validate_sign(xml, cert=None, fingerprint=None, fingerprintalg='sha1', validatecert=False, debug=False): """ Validates a signature (Message or Assertion). :param xml: The element we should validate :type: string | Document :param cert: The public cert :type: string :param fingerprint: The fingerprint of the public cert :type: string :param fingerprintalg: The algorithm used to build the fingerprint :type: string :param validatecert: If true, will verify the signature and if the cert is valid. :type: bool :param debug: Activate the xmlsec debug :type: bool """ try: if xml is None or xml == '': raise Exception('Empty string supplied as input') elem = OneLogin_Saml2_XML.to_etree(xml) xmlsec.enable_debug_trace(debug) xmlsec.tree.add_ids(elem, ["ID"]) signature_nodes = OneLogin_Saml2_XML.query(elem, '/samlp:Response/ds:Signature') if not len(signature_nodes) > 0: signature_nodes += OneLogin_Saml2_XML.query(elem, '/samlp:Response/ds:Signature') signature_nodes += OneLogin_Saml2_XML.query(elem, '/samlp:Response/saml:Assertion/ds:Signature') if len(signature_nodes) == 1: signature_node = signature_nodes[0] return OneLogin_Saml2_Utils.validate_node_sign(signature_node, elem, cert, fingerprint, fingerprintalg, validatecert, debug) else: return False except xmlsec.Error as e: if debug: print(e) return False @staticmethod def validate_metadata_sign(xml, cert=None, fingerprint=None, fingerprintalg='sha1', validatecert=False, debug=False): """ Validates a signature of a EntityDescriptor. :param xml: The element we should validate :type: string | Document :param cert: The public cert :type: string :param fingerprint: The fingerprint of the public cert :type: string :param fingerprintalg: The algorithm used to build the fingerprint :type: string :param validatecert: If true, will verify the signature and if the cert is valid. :type: bool :param debug: Activate the xmlsec debug :type: bool """ try: if xml is None or xml == '': raise Exception('Empty string supplied as input') elem = OneLogin_Saml2_XML.to_etree(xml) xmlsec.enable_debug_trace(debug) xmlsec.tree.add_ids(elem, ["ID"]) signature_nodes = OneLogin_Saml2_XML.query(elem, '/md:EntitiesDescriptor/ds:Signature') if len(signature_nodes) == 0: signature_nodes += OneLogin_Saml2_XML.query(elem, '/md:EntityDescriptor/ds:Signature') if len(signature_nodes) == 0: signature_nodes += OneLogin_Saml2_XML.query(elem, '/md:EntityDescriptor/md:SPSSODescriptor/ds:Signature') signature_nodes += OneLogin_Saml2_XML.query(elem, '/md:EntityDescriptor/md:IDPSSODescriptor/ds:Signature') if len(signature_nodes) > 0: for signature_node in signature_nodes: if not OneLogin_Saml2_Utils.validate_node_sign(signature_node, elem, cert, fingerprint, fingerprintalg, validatecert, debug): return False return True else: return False except Exception: return False @staticmethod def validate_node_sign(signature_node, elem, cert=None, fingerprint=None, fingerprintalg='sha1', validatecert=False, debug=False): """ Validates a signature node. :param signature_node: The signature node :type: Node :param xml: The element we should validate :type: Document :param cert: The public cert :type: string :param fingerprint: The fingerprint of the public cert :type: string :param fingerprintalg: The algorithm used to build the fingerprint :type: string :param validatecert: If true, will verify the signature and if the cert is valid. :type: bool :param debug: Activate the xmlsec debug :type: bool """ try: if (cert is None or cert == '') and fingerprint: x509_certificate_nodes = OneLogin_Saml2_XML.query(signature_node, '//ds:Signature/ds:KeyInfo/ds:X509Data/ds:X509Certificate') if len(x509_certificate_nodes) > 0: x509_certificate_node = x509_certificate_nodes[0] x509_cert_value = x509_certificate_node.text x509_fingerprint_value = OneLogin_Saml2_Utils.calculate_x509_fingerprint(x509_cert_value, fingerprintalg) if fingerprint == x509_fingerprint_value: cert = OneLogin_Saml2_Utils.format_cert(x509_cert_value) if cert is None or cert == '': return False # Check if Reference URI is empty reference_elem = OneLogin_Saml2_XML.query(signature_node, '//ds:Reference') if len(reference_elem) > 0: if reference_elem[0].get('URI') == '': reference_elem[0].set('URI', '#%s' % signature_node.getparent().get('ID')) if validatecert: manager = xmlsec.KeysManager() manager.load_cert_from_memory(cert, xmlsec.KeyFormat.CERT_PEM, xmlsec.KeyDataType.TRUSTED) dsig_ctx = xmlsec.SignatureContext(manager) else: dsig_ctx = xmlsec.SignatureContext() dsig_ctx.key = xmlsec.Key.from_memory(cert, xmlsec.KeyFormat.CERT_PEM, None) dsig_ctx.set_enabled_key_data([xmlsec.KeyData.X509]) dsig_ctx.verify(signature_node) return True except xmlsec.Error as e: if debug: print(e) @staticmethod def sign_binary(msg, key, algorithm=xmlsec.Transform.RSA_SHA1, debug=False): """ Sign binary message :param msg: The element we should validate :type: bytes :param key: The private key :type: string :param debug: Activate the xmlsec debug :type: bool :return signed message :rtype str """ if isinstance(msg, str): msg = msg.encode('utf8') xmlsec.enable_debug_trace(debug) dsig_ctx = xmlsec.SignatureContext() dsig_ctx.key = xmlsec.Key.from_memory(key, xmlsec.KeyFormat.PEM, None) return dsig_ctx.sign_binary(compat.to_bytes(msg), algorithm) @staticmethod def validate_binary_sign(signed_query, signature, cert=None, algorithm=OneLogin_Saml2_Constants.RSA_SHA1, debug=False): """ Validates signed binary data (Used to validate GET Signature). :param signed_query: The element we should validate :type: string :param signature: The signature that will be validate :type: string :param cert: The public cert :type: string :param algorithm: Signature algorithm :type: string :param debug: Activate the xmlsec debug :type: bool """ try: xmlsec.enable_debug_trace(debug) dsig_ctx = xmlsec.SignatureContext() dsig_ctx.key = xmlsec.Key.from_memory(cert, xmlsec.KeyFormat.CERT_PEM, None) sign_algorithm_transform_map = { OneLogin_Saml2_Constants.DSA_SHA1: xmlsec.Transform.DSA_SHA1, OneLogin_Saml2_Constants.RSA_SHA1: xmlsec.Transform.RSA_SHA1, OneLogin_Saml2_Constants.RSA_SHA256: xmlsec.Transform.RSA_SHA256, OneLogin_Saml2_Constants.RSA_SHA384: xmlsec.Transform.RSA_SHA384, OneLogin_Saml2_Constants.RSA_SHA512: xmlsec.Transform.RSA_SHA512 } sign_algorithm_transform = sign_algorithm_transform_map.get(algorithm, xmlsec.Transform.RSA_SHA1) dsig_ctx.verify_binary(compat.to_bytes(signed_query), sign_algorithm_transform, compat.to_bytes(signature)) return True except xmlsec.Error as e: if debug: print(e) return False<|fim▁end|>
@staticmethod def generate_unique_id():
<|file_name|>test.rs<|end_file_name|><|fim▁begin|>extern crate dyon; use dyon::{error, run}; <|fim▁hole|><|fim▁end|>
fn main() { error(run("source/test.dyon")); }
<|file_name|>hsl.rs<|end_file_name|><|fim▁begin|>//! The HSL device-dependent polar color model use crate::channel::{ AngularChannel, AngularChannelScalar, ChannelCast, ChannelFormatCast, ColorChannel, PosNormalBoundedChannel, PosNormalChannelScalar, }; use crate::color; use crate::color::{Color, FromTuple}; use crate::convert; use crate::convert::GetChroma; use crate::encoding::EncodableColor; use crate::rgb::Rgb; use crate::tags::HslTag; use angle; use angle::{Angle, Deg, FromAngle, IntoAngle}; #[cfg(feature = "approx")] use approx; use num_traits; use std::fmt; use std::ops; //TODO: Consider adding an `HCL` constructor and conversion /// The HSL device-dependent polar color model /// /// ![hsl-diagram](https://upload.wikimedia.org/wikipedia/commons/6/6b/HSL_color_solid_cylinder_saturation_gray.png) /// /// HSL is defined by a hue (base color), saturation (color richness) and value (whiteness). /// Like HSV, HSL is modeled as a cylinder, however the underlying space is two cones /// stacked bottom-to-bottom. /// This causes some level of /// distortion and a degeneracy at `S=0` or `L={0,1}`. Thus, while easy to reason about, it is not good for /// perceptual uniformity. It does an okay job with averaging colors or doing other math, but prefer /// the CIE spaces for uniform gradients. /// /// Hsl takes two type parameters: the cartesian channel scalar, and an angular channel scalar. /// /// Hsl is in the same color space and encoding as the parent RGB space, it is merely a geometric /// transformation and distortion. /// /// For an undistorted device-dependent polar color model, look at /// [Hsi](../hsi/struct.Hsi.html). #[repr(C)] #[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Hash)] pub struct Hsl<T, A = Deg<T>> { hue: AngularChannel<A>, saturation: PosNormalBoundedChannel<T>, lightness: PosNormalBoundedChannel<T>, } impl<T, A> Hsl<T, A> where T: PosNormalChannelScalar, A: AngularChannelScalar, { /// Construct an `Hsl` instance from hue, saturation and lightness pub fn new(hue: A, saturation: T, lightness: T) -> Self { Hsl { hue: AngularChannel::new(hue), saturation: PosNormalBoundedChannel::new(saturation), lightness: PosNormalBoundedChannel::new(lightness), } } impl_color_color_cast_angular!( Hsl { hue, saturation, lightness }, chan_traits = { PosNormalChannelScalar } ); /// Returns the hue scalar pub fn hue(&self) -> A { self.hue.0.clone() } /// Returns the saturation scalar pub fn saturation(&self) -> T { self.saturation.0.clone() } /// Returns the lightness scalar pub fn lightness(&self) -> T { self.lightness.0.clone() } /// Returns a mutable reference to the hue scalar pub fn hue_mut(&mut self) -> &mut A { &mut self.hue.0 } /// Returns a mutable reference to the saturation scalar pub fn saturation_mut(&mut self) -> &mut T { &mut self.saturation.0 } /// Returns a mutable reference to the lightness scalar pub fn lightness_mut(&mut self) -> &mut T { &mut self.lightness.0 } /// Set the hue channel value pub fn set_hue(&mut self, val: A) { self.hue.0 = val; } /// Set the saturation channel value pub fn set_saturation(&mut self, val: T) { self.saturation.0 = val; } /// Set the lightness channel value pub fn set_lightness(&mut self, val: T) { self.lightness.0 = val; } } impl<T, A> Color for Hsl<T, A> where T: PosNormalChannelScalar, A: AngularChannelScalar, { type Tag = HslTag; type ChannelsTuple = (A, T, T); fn num_channels() -> u32 { 3 } fn to_tuple(self) -> Self::ChannelsTuple { (self.hue.0, self.saturation.0, self.lightness.0) } } impl<T, A> FromTuple for Hsl<T, A> where T: PosNormalChannelScalar, A: AngularChannelScalar, { fn from_tuple(values: Self::ChannelsTuple) -> Self { Hsl::new(values.0, values.1, values.2) } } impl<T, A> color::PolarColor for Hsl<T, A><|fim▁hole|> T: PosNormalChannelScalar, A: AngularChannelScalar, { type Angular = A; type Cartesian = T; } impl<T, A> color::Invert for Hsl<T, A> where T: PosNormalChannelScalar, A: AngularChannelScalar, { impl_color_invert!(Hsl { hue, saturation, lightness }); } impl<T, A> color::Lerp for Hsl<T, A> where T: PosNormalChannelScalar + color::Lerp, A: AngularChannelScalar + color::Lerp, { type Position = A::Position; impl_color_lerp_angular!(Hsl<T> {hue, saturation, lightness}); } impl<T, A> color::Bounded for Hsl<T, A> where T: PosNormalChannelScalar, A: AngularChannelScalar, { impl_color_bounded!(Hsl { hue, saturation, lightness }); } impl<T, A> EncodableColor for Hsl<T, A> where T: PosNormalChannelScalar + num_traits::Float, A: AngularChannelScalar + Angle<Scalar = T> + FromAngle<angle::Turns<T>>, { } #[cfg(feature = "approx")] impl<T, A> approx::AbsDiffEq for Hsl<T, A> where T: PosNormalChannelScalar + approx::AbsDiffEq<Epsilon = A::Epsilon>, A: AngularChannelScalar + approx::AbsDiffEq, A::Epsilon: Clone + num_traits::Float, { impl_abs_diff_eq!({hue, saturation, lightness}); } #[cfg(feature = "approx")] impl<T, A> approx::RelativeEq for Hsl<T, A> where T: PosNormalChannelScalar + approx::RelativeEq<Epsilon = A::Epsilon>, A: AngularChannelScalar + approx::RelativeEq, A::Epsilon: Clone + num_traits::Float, { impl_rel_eq!({hue, saturation, lightness}); } #[cfg(feature = "approx")] impl<T, A> approx::UlpsEq for Hsl<T, A> where T: PosNormalChannelScalar + approx::UlpsEq<Epsilon = A::Epsilon>, A: AngularChannelScalar + approx::UlpsEq, A::Epsilon: Clone + num_traits::Float, { impl_ulps_eq!({hue, saturation, lightness}); } impl<T, A> Default for Hsl<T, A> where T: PosNormalChannelScalar + num_traits::Zero, A: AngularChannelScalar + num_traits::Zero, { impl_color_default!(Hsl { hue: AngularChannel, saturation: PosNormalBoundedChannel, lightness: PosNormalBoundedChannel }); } impl<T, A> fmt::Display for Hsl<T, A> where T: PosNormalChannelScalar + fmt::Display, A: AngularChannelScalar + fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Hsl({}, {}, {})", self.hue, self.saturation, self.lightness ) } } impl<T, A> convert::GetChroma for Hsl<T, A> where T: PosNormalChannelScalar + ops::Mul<T, Output = T> + num_traits::Float, A: AngularChannelScalar, { type ChromaType = T; fn get_chroma(&self) -> T { let one: T = num_traits::cast(1.0).unwrap(); let scaled_lightness: T = (num_traits::cast::<_, T>(2.0).unwrap() * self.lightness() - one).abs(); (one - scaled_lightness) * self.saturation() } } impl<T, A> convert::GetHue for Hsl<T, A> where T: PosNormalChannelScalar, A: AngularChannelScalar, { impl_color_get_hue_angular!(Hsl); } impl<T, A> convert::FromColor<Hsl<T, A>> for Rgb<T> where T: PosNormalChannelScalar + num_traits::Float, A: AngularChannelScalar, { fn from_color(from: &Hsl<T, A>) -> Self { let (hue_seg, hue_frac) = convert::decompose_hue_segment(from); let one_half: T = num_traits::cast(0.5).unwrap(); let hue_frac_t: T = num_traits::cast(hue_frac).unwrap(); let chroma = from.get_chroma(); let channel_min = from.lightness() - num_traits::cast::<_, T>(0.5).unwrap() * chroma; let channel_max = channel_min + chroma; match hue_seg { 0 => { let g = chroma * (hue_frac_t - one_half) + from.lightness(); Rgb::new(channel_max, g, channel_min) } 1 => { let r = chroma * (one_half - hue_frac_t) + from.lightness(); Rgb::new(r, channel_max, channel_min) } 2 => { let b = chroma * (hue_frac_t - one_half) + from.lightness(); Rgb::new(channel_min, channel_max, b) } 3 => { let g = chroma * (one_half - hue_frac_t) + from.lightness(); Rgb::new(channel_min, g, channel_max) } 4 => { let r = chroma * (hue_frac_t - one_half) + from.lightness(); Rgb::new(r, channel_min, channel_max) } 5 => { let b = chroma * (one_half - hue_frac_t) + from.lightness(); Rgb::new(channel_max, channel_min, b) } _ => unreachable!(), } } } #[cfg(test)] mod test { use super::*; use crate::color::*; use crate::convert::*; use crate::rgb::Rgb; use angle::*; use approx::*; use std::f32::consts; use crate::test; #[test] fn test_construct() { let c1 = Hsl::new(Deg(90.0), 0.5, 0.25); assert_eq!(c1.hue(), Deg(90.0)); assert_eq!(c1.saturation(), 0.5); assert_eq!(c1.lightness(), 0.25); assert_eq!(c1.to_tuple(), (Deg(90.0), 0.5, 0.25)); assert_eq!(Hsl::from_tuple(c1.to_tuple()), c1); let c2 = Hsl::new(Rad(consts::PI), 0.20f32, 0.90f32); assert_eq!(c2.hue(), Rad(consts::PI)); assert_eq!(c2.saturation(), 0.2); assert_eq!(c2.lightness(), 0.90); } #[test] fn test_chroma() { let test_data = test::build_hs_test_data(); for item in test_data.iter() { let chroma = item.hsl.get_chroma(); assert_relative_eq!(chroma, item.chroma, epsilon = 1e-3); } } #[test] fn test_invert() { let c1 = Hsl::new(Deg(100f32), 0.77f32, 0.5); assert_relative_eq!(c1.clone().invert().invert(), c1); assert_relative_eq!(c1.invert(), Hsl::new(Deg(280f32), 0.23f32, 0.5)); let c2 = Hsl::new(Turns(0.10), 0.11, 0.55); assert_relative_eq!(c2.clone().invert().invert(), c2); assert_relative_eq!(c2.invert(), Hsl::new(Turns(0.60), 0.89, 0.45)); } #[test] fn test_lerp() { let c1 = Hsl::new(Turns(0.2), 0.25, 0.80); let c2 = Hsl::new(Turns(0.8), 0.75, 0.30); assert_relative_eq!(c1.lerp(&c2, 0.0), c1); assert_relative_eq!(c1.lerp(&c2, 1.0), c2); assert_relative_eq!(c1.lerp(&c2, 0.5), Hsl::new(Turns(0.0), 0.5, 0.55)); } #[test] fn test_hsl_to_rgb() { let test_data = test::build_hs_test_data(); for item in test_data.iter() { let rgb = Rgb::from_color(&item.hsl); assert_relative_eq!(rgb, item.rgb, epsilon = 1e-3); let hsl = Hsl::from_color(&rgb); assert_relative_eq!(hsl, item.hsl, epsilon = 1e-3); } } #[test] fn test_color_cast() { let c1 = Hsl::new(Deg(90.0), 0.23, 0.45); assert_relative_eq!(c1.color_cast(), Hsl::new(Turns(0.25f32), 0.23f32, 0.45f32)); assert_relative_eq!(c1.color_cast(), c1, epsilon = 1e-7); assert_relative_eq!( c1.color_cast::<f32, Rad<f32>>().color_cast(), c1, epsilon = 1e-7 ); } }<|fim▁end|>
where
<|file_name|>test.js<|end_file_name|><|fim▁begin|>describe('[Regression](GH-1424)', function () { it('Should raise click event on a button after "enter" key is pressed', function () { return runTests('testcafe-fixtures/index-test.js', 'Press enter');<|fim▁hole|><|fim▁end|>
}); });
<|file_name|>DisplayService.java<|end_file_name|><|fim▁begin|>package com.luciofm.presentation.androidsalao;<|fim▁hole|> void connection(boolean connetion); void next(); void previous(); void advance(); }<|fim▁end|>
public interface DisplayService {
<|file_name|>box.go<|end_file_name|><|fim▁begin|>// Package box stores values that may be undefined, unknown, or empty. package box import ( "strconv" "time" ) const ( Undefined = iota Unknown = iota Empty = iota Full = iota ) type Bool struct { value bool status byte } // NewBool returns a Bool initialized to v func NewBool(v bool) (box Bool) { box.Set(v) return box } // Set places v in box func (box *Bool) Set(v bool) { box.value = v box.status = Full } // GetCoerceNil returns the value if the box is full, otherwise it returns nil func (box *Bool) GetCoerceNil() interface{} { if box.status == Full { return box.value } else { return nil } } // SetCoerceNil places v in box if v is not nil, otherwise it sets box to nilStatus func (box *Bool) SetCoerceNil(v interface{}, nilStatus byte) { if v != nil { box.Set(v.(bool)) } else { box.status = nilStatus } } // GetCoerceZero returns value if the box is full, otherwise it returns the zero value func (box *Bool) GetCoerceZero() bool { if box.status == Full { return box.value } else { var zero bool return zero } } // SetCoerceZero places v in box if v is not the zero value, otherwise it sets box to zeroStatus func (box *Bool) SetCoerceZero(v bool, zeroStatus byte) { var zero bool if v != zero { box.Set(v) } else { box.status = zeroStatus } } // SetUndefined sets box to Undefined func (box *Bool) SetUndefined() { box.status = Undefined } // SetUnknown sets box to Unknown func (box *Bool) SetUnknown() { box.status = Unknown } // SetEmpty sets box to Empty func (box *Bool) SetEmpty() { box.status = Empty } // MustGet returns the value or panics if box is not full func (box *Bool) MustGet() bool { if box.status != Full { panic("called MustGet on a box that was not full") } return box.value } // Get returns the value and present. present is true only if the box is Full and value is valid func (box *Bool) Get() (bool, bool) { if box.status != Full { var zeroVal bool return zeroVal, false } return box.value, true } // Status returns the box's status func (box *Bool) Status() byte { return box.status } type Float32 struct { value float32 status byte } // NewFloat32 returns a Float32 initialized to v func NewFloat32(v float32) (box Float32) { box.Set(v) return box } // Set places v in box func (box *Float32) Set(v float32) { box.value = v box.status = Full } // GetCoerceNil returns the value if the box is full, otherwise it returns nil func (box *Float32) GetCoerceNil() interface{} { if box.status == Full { return box.value } else { return nil } } // SetCoerceNil places v in box if v is not nil, otherwise it sets box to nilStatus func (box *Float32) SetCoerceNil(v interface{}, nilStatus byte) { if v != nil { box.Set(v.(float32)) } else { box.status = nilStatus } } // GetCoerceZero returns value if the box is full, otherwise it returns the zero value func (box *Float32) GetCoerceZero() float32 { if box.status == Full { return box.value } else { var zero float32 return zero } } // SetCoerceZero places v in box if v is not the zero value, otherwise it sets box to zeroStatus func (box *Float32) SetCoerceZero(v float32, zeroStatus byte) { var zero float32 if v != zero { box.Set(v) } else { box.status = zeroStatus } } // SetUndefined sets box to Undefined func (box *Float32) SetUndefined() { box.status = Undefined } // SetUnknown sets box to Unknown func (box *Float32) SetUnknown() { box.status = Unknown } // SetEmpty sets box to Empty func (box *Float32) SetEmpty() { box.status = Empty } // MustGet returns the value or panics if box is not full func (box *Float32) MustGet() float32 { if box.status != Full { panic("called MustGet on a box that was not full") } return box.value } // Get returns the value and present. present is true only if the box is Full and value is valid func (box *Float32) Get() (float32, bool) { if box.status != Full { var zeroVal float32 return zeroVal, false } return box.value, true } // Status returns the box's status func (box *Float32) Status() byte { return box.status } type Float64 struct { value float64 status byte } // NewFloat64 returns a Float64 initialized to v func NewFloat64(v float64) (box Float64) { box.Set(v) return box } // Set places v in box func (box *Float64) Set(v float64) { box.value = v box.status = Full } // GetCoerceNil returns the value if the box is full, otherwise it returns nil func (box *Float64) GetCoerceNil() interface{} { if box.status == Full { return box.value } else { return nil } } // SetCoerceNil places v in box if v is not nil, otherwise it sets box to nilStatus func (box *Float64) SetCoerceNil(v interface{}, nilStatus byte) { if v != nil { box.Set(v.(float64)) } else { box.status = nilStatus } } // GetCoerceZero returns value if the box is full, otherwise it returns the zero value func (box *Float64) GetCoerceZero() float64 { if box.status == Full { return box.value } else { var zero float64 return zero } } // SetCoerceZero places v in box if v is not the zero value, otherwise it sets box to zeroStatus func (box *Float64) SetCoerceZero(v float64, zeroStatus byte) { var zero float64 if v != zero { box.Set(v) } else { box.status = zeroStatus } } // SetUndefined sets box to Undefined func (box *Float64) SetUndefined() { box.status = Undefined } // SetUnknown sets box to Unknown func (box *Float64) SetUnknown() { box.status = Unknown } // SetEmpty sets box to Empty func (box *Float64) SetEmpty() { box.status = Empty } // MustGet returns the value or panics if box is not full func (box *Float64) MustGet() float64 { if box.status != Full { panic("called MustGet on a box that was not full") } return box.value } // Get returns the value and present. present is true only if the box is Full and value is valid func (box *Float64) Get() (float64, bool) { if box.status != Full { var zeroVal float64 return zeroVal, false } return box.value, true } // Status returns the box's status func (box *Float64) Status() byte { return box.status } type Int8 struct { value int8 status byte } // NewInt8 returns a Int8 initialized to v func NewInt8(v int8) (box Int8) { box.Set(v) return box } // Set places v in box func (box *Int8) Set(v int8) { box.value = v box.status = Full } // GetCoerceNil returns the value if the box is full, otherwise it returns nil func (box *Int8) GetCoerceNil() interface{} { if box.status == Full { return box.value } else { return nil } } // SetCoerceNil places v in box if v is not nil, otherwise it sets box to nilStatus func (box *Int8) SetCoerceNil(v interface{}, nilStatus byte) { if v != nil { box.Set(v.(int8)) } else { box.status = nilStatus } } // GetCoerceZero returns value if the box is full, otherwise it returns the zero value func (box *Int8) GetCoerceZero() int8 { if box.status == Full { return box.value } else { var zero int8 return zero } } // SetCoerceZero places v in box if v is not the zero value, otherwise it sets box to zeroStatus func (box *Int8) SetCoerceZero(v int8, zeroStatus byte) { var zero int8 if v != zero { box.Set(v) } else { box.status = zeroStatus } } // SetUndefined sets box to Undefined func (box *Int8) SetUndefined() { box.status = Undefined } // SetUnknown sets box to Unknown func (box *Int8) SetUnknown() { box.status = Unknown } // SetEmpty sets box to Empty func (box *Int8) SetEmpty() { box.status = Empty } // MustGet returns the value or panics if box is not full func (box *Int8) MustGet() int8 { if box.status != Full { panic("called MustGet on a box that was not full") } return box.value } // Get returns the value and present. present is true only if the box is Full and value is valid func (box *Int8) Get() (int8, bool) { if box.status != Full { var zeroVal int8 return zeroVal, false } return box.value, true } // Status returns the box's status func (box *Int8) Status() byte { return box.status } type Int16 struct { value int16 status byte } // NewInt16 returns a Int16 initialized to v func NewInt16(v int16) (box Int16) { box.Set(v) return box } // Set places v in box func (box *Int16) Set(v int16) { box.value = v box.status = Full } // GetCoerceNil returns the value if the box is full, otherwise it returns nil func (box *Int16) GetCoerceNil() interface{} { if box.status == Full { return box.value } else { return nil } } // SetCoerceNil places v in box if v is not nil, otherwise it sets box to nilStatus func (box *Int16) SetCoerceNil(v interface{}, nilStatus byte) { if v != nil { box.Set(v.(int16)) } else { box.status = nilStatus } } // GetCoerceZero returns value if the box is full, otherwise it returns the zero value func (box *Int16) GetCoerceZero() int16 { if box.status == Full { return box.value } else { var zero int16 return zero } } // SetCoerceZero places v in box if v is not the zero value, otherwise it sets box to zeroStatus func (box *Int16) SetCoerceZero(v int16, zeroStatus byte) { var zero int16 if v != zero { box.Set(v) } else { box.status = zeroStatus } } // SetUndefined sets box to Undefined func (box *Int16) SetUndefined() { box.status = Undefined } // SetUnknown sets box to Unknown func (box *Int16) SetUnknown() { box.status = Unknown } // SetEmpty sets box to Empty func (box *Int16) SetEmpty() { box.status = Empty } // MustGet returns the value or panics if box is not full func (box *Int16) MustGet() int16 { if box.status != Full { panic("called MustGet on a box that was not full") } return box.value } // Get returns the value and present. present is true only if the box is Full and value is valid func (box *Int16) Get() (int16, bool) { if box.status != Full { var zeroVal int16 return zeroVal, false } return box.value, true } // Status returns the box's status func (box *Int16) Status() byte { return box.status } type Int32 struct { value int32 status byte } // NewInt32 returns a Int32 initialized to v func NewInt32(v int32) (box Int32) { box.Set(v) return box } // Set places v in box func (box *Int32) Set(v int32) { box.value = v box.status = Full } // GetCoerceNil returns the value if the box is full, otherwise it returns nil func (box *Int32) GetCoerceNil() interface{} { if box.status == Full { return box.value } else { return nil } } // SetCoerceNil places v in box if v is not nil, otherwise it sets box to nilStatus func (box *Int32) SetCoerceNil(v interface{}, nilStatus byte) { if v != nil { box.Set(v.(int32)) } else { box.status = nilStatus } } // GetCoerceZero returns value if the box is full, otherwise it returns the zero value func (box *Int32) GetCoerceZero() int32 { if box.status == Full { return box.value } else { var zero int32 return zero } } // SetCoerceZero places v in box if v is not the zero value, otherwise it sets box to zeroStatus func (box *Int32) SetCoerceZero(v int32, zeroStatus byte) { var zero int32 if v != zero { box.Set(v) } else { box.status = zeroStatus } } // SetUndefined sets box to Undefined func (box *Int32) SetUndefined() { box.status = Undefined } // SetUnknown sets box to Unknown func (box *Int32) SetUnknown() { box.status = Unknown } // SetEmpty sets box to Empty func (box *Int32) SetEmpty() { box.status = Empty } // MustGet returns the value or panics if box is not full func (box *Int32) MustGet() int32 { if box.status != Full { panic("called MustGet on a box that was not full") } return box.value } // Get returns the value and present. present is true only if the box is Full and value is valid func (box *Int32) Get() (int32, bool) { if box.status != Full { var zeroVal int32 return zeroVal, false } return box.value, true } // Status returns the box's status func (box *Int32) Status() byte { return box.status } type Int64 struct { value int64 status byte } // NewInt64 returns a Int64 initialized to v func NewInt64(v int64) (box Int64) { box.Set(v) return box } // Set places v in box func (box *Int64) Set(v int64) { box.value = v box.status = Full } // GetCoerceNil returns the value if the box is full, otherwise it returns nil func (box *Int64) GetCoerceNil() interface{} { if box.status == Full { return box.value } else { return nil } } // SetCoerceNil places v in box if v is not nil, otherwise it sets box to nilStatus func (box *Int64) SetCoerceNil(v interface{}, nilStatus byte) { if v != nil { box.Set(v.(int64)) } else { box.status = nilStatus } } // GetCoerceZero returns value if the box is full, otherwise it returns the zero value func (box *Int64) GetCoerceZero() int64 { if box.status == Full { return box.value } else { var zero int64 return zero } } // SetCoerceZero places v in box if v is not the zero value, otherwise it sets box to zeroStatus func (box *Int64) SetCoerceZero(v int64, zeroStatus byte) { var zero int64 if v != zero { box.Set(v) } else { box.status = zeroStatus } } // SetUndefined sets box to Undefined func (box *Int64) SetUndefined() { box.status = Undefined } // SetUnknown sets box to Unknown func (box *Int64) SetUnknown() { box.status = Unknown } // SetEmpty sets box to Empty func (box *Int64) SetEmpty() { box.status = Empty } // MustGet returns the value or panics if box is not full func (box *Int64) MustGet() int64 { if box.status != Full { panic("called MustGet on a box that was not full") } return box.value } // Get returns the value and present. present is true only if the box is Full and value is valid func (box *Int64) Get() (int64, bool) { if box.status != Full { var zeroVal int64 return zeroVal, false } return box.value, true } // Status returns the box's status func (box *Int64) Status() byte { return box.status } type String struct { value string status byte } // NewString returns a String initialized to v func NewString(v string) (box String) { box.Set(v) return box } // Set places v in box func (box *String) Set(v string) { box.value = v box.status = Full } // GetCoerceNil returns the value if the box is full, otherwise it returns nil func (box *String) GetCoerceNil() interface{} { if box.status == Full { return box.value } else { return nil } } // SetCoerceNil places v in box if v is not nil, otherwise it sets box to nilStatus func (box *String) SetCoerceNil(v interface{}, nilStatus byte) { if v != nil { box.Set(v.(string)) } else { box.status = nilStatus } } // GetCoerceZero returns value if the box is full, otherwise it returns the zero value func (box *String) GetCoerceZero() string { if box.status == Full { return box.value } else { var zero string return zero } } // SetCoerceZero places v in box if v is not the zero value, otherwise it sets box to zeroStatus func (box *String) SetCoerceZero(v string, zeroStatus byte) { var zero string if v != zero { box.Set(v) } else { box.status = zeroStatus } } // SetUndefined sets box to Undefined func (box *String) SetUndefined() { box.status = Undefined } // SetUnknown sets box to Unknown func (box *String) SetUnknown() { box.status = Unknown } // SetEmpty sets box to Empty func (box *String) SetEmpty() { box.status = Empty } // MustGet returns the value or panics if box is not full func (box *String) MustGet() string { if box.status != Full { panic("called MustGet on a box that was not full") } return box.value } // Get returns the value and present. present is true only if the box is Full and value is valid func (box *String) Get() (string, bool) { if box.status != Full { var zeroVal string return zeroVal, false } return box.value, true } // Status returns the box's status func (box *String) Status() byte { return box.status } type Time struct { value time.Time status byte } // NewTime returns a Time initialized to v func NewTime(v time.Time) (box Time) { box.Set(v) return box } // Set places v in box func (box *Time) Set(v time.Time) { box.value = v box.status = Full } // GetCoerceNil returns the value if the box is full, otherwise it returns nil func (box *Time) GetCoerceNil() interface{} { if box.status == Full { return box.value } else { return nil } } // SetCoerceNil places v in box if v is not nil, otherwise it sets box to nilStatus func (box *Time) SetCoerceNil(v interface{}, nilStatus byte) { if v != nil { box.Set(v.(time.Time)) } else { box.status = nilStatus } } // GetCoerceZero returns value if the box is full, otherwise it returns the zero value func (box *Time) GetCoerceZero() time.Time { if box.status == Full { return box.value } else { var zero time.Time return zero } } // SetCoerceZero places v in box if v is not the zero value, otherwise it sets box to zeroStatus func (box *Time) SetCoerceZero(v time.Time, zeroStatus byte) { var zero time.Time if v != zero { box.Set(v) } else { box.status = zeroStatus } } // SetUndefined sets box to Undefined func (box *Time) SetUndefined() { box.status = Undefined } // SetUnknown sets box to Unknown func (box *Time) SetUnknown() { box.status = Unknown } // SetEmpty sets box to Empty func (box *Time) SetEmpty() { box.status = Empty } // MustGet returns the value or panics if box is not full func (box *Time) MustGet() time.Time { if box.status != Full { panic("called MustGet on a box that was not full") } return box.value } // Get returns the value and present. present is true only if the box is Full and value is valid func (box *Time) Get() (time.Time, bool) { if box.status != Full { var zeroVal time.Time return zeroVal, false } return box.value, true } // Status returns the box's status func (box *Time) Status() byte { return box.status } type UInt8 struct { value uint8 status byte } // NewUInt8 returns a UInt8 initialized to v func NewUInt8(v uint8) (box UInt8) { box.Set(v) return box } // Set places v in box func (box *UInt8) Set(v uint8) { box.value = v box.status = Full } // GetCoerceNil returns the value if the box is full, otherwise it returns nil func (box *UInt8) GetCoerceNil() interface{} { if box.status == Full { return box.value } else { return nil } } // SetCoerceNil places v in box if v is not nil, otherwise it sets box to nilStatus func (box *UInt8) SetCoerceNil(v interface{}, nilStatus byte) { if v != nil { box.Set(v.(uint8)) } else { box.status = nilStatus } } // GetCoerceZero returns value if the box is full, otherwise it returns the zero value func (box *UInt8) GetCoerceZero() uint8 { if box.status == Full { return box.value } else { var zero uint8 return zero } } // SetCoerceZero places v in box if v is not the zero value, otherwise it sets box to zeroStatus func (box *UInt8) SetCoerceZero(v uint8, zeroStatus byte) { var zero uint8 if v != zero { box.Set(v) } else { box.status = zeroStatus } } // SetUndefined sets box to Undefined func (box *UInt8) SetUndefined() { box.status = Undefined } // SetUnknown sets box to Unknown func (box *UInt8) SetUnknown() { box.status = Unknown } // SetEmpty sets box to Empty func (box *UInt8) SetEmpty() { box.status = Empty } // MustGet returns the value or panics if box is not full func (box *UInt8) MustGet() uint8 { if box.status != Full { panic("called MustGet on a box that was not full") } return box.value } // Get returns the value and present. present is true only if the box is Full and value is valid func (box *UInt8) Get() (uint8, bool) { if box.status != Full { var zeroVal uint8 return zeroVal, false } return box.value, true } // Status returns the box's status func (box *UInt8) Status() byte { return box.status } type UInt16 struct { value uint16 status byte } // NewUInt16 returns a UInt16 initialized to v func NewUInt16(v uint16) (box UInt16) { box.Set(v) return box } // Set places v in box func (box *UInt16) Set(v uint16) { box.value = v box.status = Full } // GetCoerceNil returns the value if the box is full, otherwise it returns nil func (box *UInt16) GetCoerceNil() interface{} { if box.status == Full { return box.value } else { return nil } } // SetCoerceNil places v in box if v is not nil, otherwise it sets box to nilStatus func (box *UInt16) SetCoerceNil(v interface{}, nilStatus byte) { if v != nil { box.Set(v.(uint16)) } else { box.status = nilStatus } } // GetCoerceZero returns value if the box is full, otherwise it returns the zero value func (box *UInt16) GetCoerceZero() uint16 { if box.status == Full { return box.value } else { var zero uint16 return zero } } // SetCoerceZero places v in box if v is not the zero value, otherwise it sets box to zeroStatus func (box *UInt16) SetCoerceZero(v uint16, zeroStatus byte) { var zero uint16 if v != zero { box.Set(v) } else { box.status = zeroStatus } } // SetUndefined sets box to Undefined func (box *UInt16) SetUndefined() { box.status = Undefined } // SetUnknown sets box to Unknown func (box *UInt16) SetUnknown() { box.status = Unknown } // SetEmpty sets box to Empty func (box *UInt16) SetEmpty() { box.status = Empty } // MustGet returns the value or panics if box is not full func (box *UInt16) MustGet() uint16 { if box.status != Full { panic("called MustGet on a box that was not full") } return box.value } // Get returns the value and present. present is true only if the box is Full and value is valid func (box *UInt16) Get() (uint16, bool) { if box.status != Full { var zeroVal uint16 return zeroVal, false } return box.value, true } // Status returns the box's status func (box *UInt16) Status() byte { return box.status } type UInt32 struct { value uint32 status byte } // NewUInt32 returns a UInt32 initialized to v func NewUInt32(v uint32) (box UInt32) { box.Set(v) return box } // Set places v in box func (box *UInt32) Set(v uint32) { box.value = v box.status = Full } // GetCoerceNil returns the value if the box is full, otherwise it returns nil func (box *UInt32) GetCoerceNil() interface{} { if box.status == Full { return box.value } else { return nil } } // SetCoerceNil places v in box if v is not nil, otherwise it sets box to nilStatus func (box *UInt32) SetCoerceNil(v interface{}, nilStatus byte) { if v != nil { box.Set(v.(uint32)) } else { box.status = nilStatus } } // GetCoerceZero returns value if the box is full, otherwise it returns the zero value func (box *UInt32) GetCoerceZero() uint32 { if box.status == Full { return box.value } else { var zero uint32 return zero } } // SetCoerceZero places v in box if v is not the zero value, otherwise it sets box to zeroStatus func (box *UInt32) SetCoerceZero(v uint32, zeroStatus byte) { var zero uint32 if v != zero { box.Set(v) } else { box.status = zeroStatus } } // SetUndefined sets box to Undefined func (box *UInt32) SetUndefined() { box.status = Undefined } // SetUnknown sets box to Unknown func (box *UInt32) SetUnknown() { box.status = Unknown } // SetEmpty sets box to Empty func (box *UInt32) SetEmpty() { box.status = Empty } // MustGet returns the value or panics if box is not full func (box *UInt32) MustGet() uint32 { if box.status != Full { panic("called MustGet on a box that was not full") } return box.value } // Get returns the value and present. present is true only if the box is Full and value is valid func (box *UInt32) Get() (uint32, bool) { if box.status != Full { var zeroVal uint32 return zeroVal, false } return box.value, true } // Status returns the box's status func (box *UInt32) Status() byte { return box.status } type UInt64 struct { value uint64 status byte } // NewUInt64 returns a UInt64 initialized to v func NewUInt64(v uint64) (box UInt64) { box.Set(v) return box } // Set places v in box func (box *UInt64) Set(v uint64) { box.value = v box.status = Full } // GetCoerceNil returns the value if the box is full, otherwise it returns nil func (box *UInt64) GetCoerceNil() interface{} { if box.status == Full { return box.value } else { return nil } } // SetCoerceNil places v in box if v is not nil, otherwise it sets box to nilStatus func (box *UInt64) SetCoerceNil(v interface{}, nilStatus byte) { if v != nil { box.Set(v.(uint64)) } else { box.status = nilStatus } } // GetCoerceZero returns value if the box is full, otherwise it returns the zero value func (box *UInt64) GetCoerceZero() uint64 { if box.status == Full { return box.value } else { var zero uint64 return zero } } // SetCoerceZero places v in box if v is not the zero value, otherwise it sets box to zeroStatus func (box *UInt64) SetCoerceZero(v uint64, zeroStatus byte) { var zero uint64 if v != zero { box.Set(v) } else { box.status = zeroStatus } } // SetUndefined sets box to Undefined func (box *UInt64) SetUndefined() { box.status = Undefined } // SetUnknown sets box to Unknown func (box *UInt64) SetUnknown() { box.status = Unknown } // SetEmpty sets box to Empty func (box *UInt64) SetEmpty() { box.status = Empty } // MustGet returns the value or panics if box is not full func (box *UInt64) MustGet() uint64 { if box.status != Full { panic("called MustGet on a box that was not full") } return box.value } // Get returns the value and present. present is true only if the box is Full and value is valid func (box *UInt64) Get() (uint64, bool) { if box.status != Full { var zeroVal uint64 return zeroVal, false } return box.value, true } // Status returns the box's status func (box *UInt64) Status() byte { return box.status } func (box Bool) MarshalJSON() ([]byte, error) { if box.status != Full { return []byte("null"), nil } if box.value { return []byte("true"), nil } return []byte("false"), nil } func (box Float32) MarshalJSON() ([]byte, error) { if box.status != Full { return []byte("null"), nil } return []byte(strconv.FormatFloat(float64(box.value), 'f', -1, 32)), nil } func (box Float64) MarshalJSON() ([]byte, error) { if box.status != Full { return []byte("null"), nil } return []byte(strconv.FormatFloat(float64(box.value), 'f', -1, 64)), nil } func (box Int8) MarshalJSON() ([]byte, error) { if box.status != Full { return []byte("null"), nil } return []byte(strconv.FormatInt(int64(box.value), 10)), nil } func (box Int16) MarshalJSON() ([]byte, error) { if box.status != Full { return []byte("null"), nil } return []byte(strconv.FormatInt(int64(box.value), 10)), nil } func (box Int32) MarshalJSON() ([]byte, error) { if box.status != Full { return []byte("null"), nil } return []byte(strconv.FormatInt(int64(box.value), 10)), nil } func (box Int64) MarshalJSON() ([]byte, error) { if box.status != Full { return []byte("null"), nil } return []byte(strconv.FormatInt(int64(box.value), 10)), nil } func (box String) MarshalJSON() ([]byte, error) { if box.status != Full { return []byte("null"), nil } return []byte(`"` + box.value + `"`), nil } func (box UInt8) MarshalJSON() ([]byte, error) { if box.status != Full { return []byte("null"), nil } return []byte(strconv.FormatUint(uint64(box.value), 10)), nil } func (box UInt16) MarshalJSON() ([]byte, error) { if box.status != Full { return []byte("null"), nil } return []byte(strconv.FormatUint(uint64(box.value), 10)), nil }<|fim▁hole|> func (box UInt32) MarshalJSON() ([]byte, error) { if box.status != Full { return []byte("null"), nil } return []byte(strconv.FormatUint(uint64(box.value), 10)), nil } func (box UInt64) MarshalJSON() ([]byte, error) { if box.status != Full { return []byte("null"), nil } return []byte(strconv.FormatUint(uint64(box.value), 10)), nil }<|fim▁end|>
<|file_name|>CdiFxSaft.java<|end_file_name|><|fim▁begin|>/* * Copyright (C) 2020 GG-Net GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details.<|fim▁hole|> * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package eu.ggnet.dwoss.receipt.ui.tryout.fx; import java.util.concurrent.Executors; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Instance; import javax.inject.Inject; import eu.ggnet.saft.core.Saft; import eu.ggnet.saft.core.impl.Fx; import eu.ggnet.saft.core.ui.LocationStorage; /** * CDI Saft with FX. * * @author mirko.schulze */ @ApplicationScoped // @Specializes public class CdiFxSaft extends Saft { @Inject private Instance<Object> instance; public CdiFxSaft() { super(new LocationStorage(), Executors.newCachedThreadPool()); } @PostConstruct private void postInit() { init(new Fx(this, p -> instance.select(p).get())); core().captureMode(true); } }<|fim▁end|>
* * You should have received a copy of the GNU General Public License
<|file_name|>creatabla.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python <|fim▁hole|>conn = sqlite3.connect('accesslist.db') conn.execute('''CREATE TABLE USUARIO (CELLPHONE CHAR(11) PRIMARY KEY NOT NULL, PASSWD CHAR(138) NOT NULL);''') print "Table created successfully"; conn.close()<|fim▁end|>
import sqlite3
<|file_name|>setAwayMessageEvent.py<|end_file_name|><|fim▁begin|><|fim▁hole|> def handle(userToken, packetData): # get token data username = userToken.username # Read packet data packetData = clientPackets.setAwayMessage(packetData) # Set token away message userToken.awayMessage = packetData["awayMessage"] # Send private message from fokabot if packetData["awayMessage"] == "": fokaMessage = "Your away message has been reset" else: fokaMessage = "Your away message is now: {}".format(packetData["awayMessage"]) userToken.enqueue(serverPackets.sendMessage("FokaBot", username, fokaMessage)) log.info("{} has changed their away message to: {}".format(username, packetData["awayMessage"]))<|fim▁end|>
from common.log import logUtils as log from constants import clientPackets from constants import serverPackets
<|file_name|>main.go<|end_file_name|><|fim▁begin|>package lcd2usb import ( "errors" "fmt" "github.com/schleibinger/sio" ) type cmd byte const ( cmdPrefix cmd = 0xfe cmdBacklightOn = 0x42 cmdBacklightOff = 0x46 cmdBrightnes = 0x99 // brightnes cmdContrast = 0x50 // contrast cmdAutoscrollOn = 0x51 cmdAutoscrollOff = 0x52 cmdClearScreen = 0x58 cmdChangeSplash = 0x40 // Write number of chars for splash cmdCursorPosition = 0x47 // x, y cmdHome = 0x48 cmdCursorBack = 0x4c cmdCursorForward = 0x4d cmdUnderlineOn = 0x4a cmdUnderlineOff = 0x4b cmdBlockOn = 0x53 cmdBlockOff = 0x54 cmdBacklightColor = 0xd0 // r, g, b cmdLCDSize = 0xd1 // cols, rows cmdCreateChar = 0x4e cmdSaveChar = 0xc1 cmdLoadChar = 0xc0 ) type Device struct { rows uint8 cols uint8 p *sio.Port } func Open(name string, rows, cols uint8) (*Device, error) { p, err := sio.Open(name, 9600) if err != nil { return nil, err } d := &Device{ rows: rows, cols: cols, p: p, } if err = d.send(cmdLCDSize, cols, rows); err != nil { return nil, err } return d, nil } func (d *Device) Close() error { if d.p != nil { err := d.p.Close() d.p = nil return err } return nil } func (d *Device) Write(buf []byte) (n int, err error) { if d.p == nil { return 0, errors.New("writing to closed deviced") } return d.p.Write(buf) } func (d *Device) send(c cmd, args ...byte) error { _, err := d.Write(append([]byte{byte(cmdPrefix), byte(c)}, args...)) return err<|fim▁hole|>} func (d *Device) Backlight(on bool) error { if on { return d.send(cmdBacklightOn) } else { return d.send(cmdBacklightOff) } } func (d *Device) Brightnes(set uint8) error { return d.send(cmdBrightnes, set) } func (d *Device) Contrast(set uint8) error { return d.send(cmdContrast, set) } func (d *Device) Autoscroll(on bool) error { if on { return d.send(cmdAutoscrollOn) } else { return d.send(cmdAutoscrollOff) } } func (d *Device) Clear() error { return d.send(cmdClearScreen) } func (d *Device) ChangeSplash(set []byte) error { cells := int(d.rows) * int(d.cols) if len(set) > cells { return fmt.Errorf("wrong number of characters: expected %d", cells) } return d.send(cmdChangeSplash, set...) } func (d *Device) CursorPosition(x, y uint8) error { if x > d.cols || y > d.rows { return fmt.Errorf("setting cursor out of bounds") } return d.send(cmdCursorPosition, x, y) } func (d *Device) Home() error { return d.send(cmdHome) } func (d *Device) CursorBack() error { return d.send(cmdCursorBack) } func (d *Device) CursorForward() error { return d.send(cmdCursorForward) } func (d *Device) Underline(on bool) error { if on { return d.send(cmdUnderlineOn) } else { return d.send(cmdUnderlineOff) } } func (d *Device) Block(on bool) error { if on { return d.send(cmdBlockOn) } else { return d.send(cmdBlockOff) } } func (d *Device) Color(r, g, b uint8) error { return d.send(cmdBacklightColor, r, g, b) }<|fim▁end|>
<|file_name|>base_test.py<|end_file_name|><|fim▁begin|>import networkx as nx class BaseTestAttributeMixing(object): def setUp(self): G=nx.Graph() G.add_nodes_from([0,1],fish='one') G.add_nodes_from([2,3],fish='two') G.add_nodes_from([4],fish='red') G.add_nodes_from([5],fish='blue') G.add_edges_from([(0,1),(2,3),(0,4),(2,5)]) self.G=G D=nx.DiGraph() D.add_nodes_from([0,1],fish='one') D.add_nodes_from([2,3],fish='two') D.add_nodes_from([4],fish='red') D.add_nodes_from([5],fish='blue') D.add_edges_from([(0,1),(2,3),(0,4),(2,5)]) self.D=D M=nx.MultiGraph() M.add_nodes_from([0,1],fish='one') M.add_nodes_from([2,3],fish='two') M.add_nodes_from([4],fish='red') M.add_nodes_from([5],fish='blue') M.add_edges_from([(0,1),(0,1),(2,3)]) self.M=M S=nx.Graph() S.add_nodes_from([0,1],fish='one') S.add_nodes_from([2,3],fish='two') S.add_nodes_from([4],fish='red') S.add_nodes_from([5],fish='blue') <|fim▁hole|> S.add_edge(0,0) S.add_edge(2,2) self.S=S class BaseTestDegreeMixing(object): def setUp(self): self.P4=nx.path_graph(4) self.D=nx.DiGraph() self.D.add_edges_from([(0, 2), (0, 3), (1, 3), (2, 3)]) self.M=nx.MultiGraph() self.M.add_path(list(range(4))) self.M.add_edge(0,1) self.S=nx.Graph() self.S.add_edges_from([(0,0),(1,1)])<|fim▁end|>
<|file_name|>format-url.js<|end_file_name|><|fim▁begin|>export default function formatUrl({ baseUrl, size, theme, uri, view }) { let src = `${baseUrl}/?uri=${uri}&size=${size}&theme=${theme}`; if (view) { src += `&view=${view}`; }<|fim▁hole|> return src; }<|fim▁end|>
<|file_name|>TransformCreateCall.java<|end_file_name|><|fim▁begin|>/** * The MIT License * Copyright (c) 2003 David G Jones * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package info.dgjones.st2x.transform.method.intra; import java.util.List; import info.dgjones.st2x.ClassParser; import info.dgjones.st2x.JavaMethod; import info.dgjones.st2x.javatoken.JavaCallStart; import info.dgjones.st2x.javatoken.JavaIdentifier; import info.dgjones.st2x.javatoken.JavaKeyword; import info.dgjones.st2x.javatoken.JavaToken; import info.dgjones.st2x.transform.method.AbstractMethodBodyTransformation; import info.dgjones.st2x.transform.tokenmatcher.TokenMatcher; import info.dgjones.st2x.transform.tokenmatcher.TokenMatcherFactory; public class TransformCreateCall extends AbstractMethodBodyTransformation { public TransformCreateCall() { super(); } public TransformCreateCall(TokenMatcherFactory factory) { super(factory); } protected TokenMatcher matchers(TokenMatcherFactory factory) { return factory.token(JavaCallStart.class, "create.*"); } protected int transform(JavaMethod javaMethod, List tokens, int i) { JavaCallStart call = (JavaCallStart)tokens.get(i); if (ClassParser.NON_CONSTRUCTORS.contains(call.value)) { return i; } if (i > 0 && (tokens.get(i - 1) instanceof JavaIdentifier)) {<|fim▁hole|> JavaToken token = (JavaToken) tokens.get(i - 1); if (token.value.equals("super")) { return i; } else if (token.value.equals(javaMethod.javaClass.className) && javaMethod.isConstructor()) { call.value = "this"; tokens.remove(i-1); return i-1; } call.value = token.value; tokens.remove(i - 1); tokens.add(i - 1, new JavaKeyword("new")); } else if (javaMethod.isConstructor()) { call.value = "this"; } else { call.value = javaMethod.javaClass.className; tokens.add(i, new JavaKeyword("new")); } return i; } }<|fim▁end|>
<|file_name|>drums_rnn_create_dataset.py<|end_file_name|><|fim▁begin|># Copyright 2022 The Magenta Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Create a dataset of SequenceExamples from NoteSequence protos. This script will extract drum tracks from NoteSequence protos and save them to TensorFlow's SequenceExample protos for input to the drums RNN models. """ import os from magenta.models.drums_rnn import drums_rnn_config_flags from magenta.models.drums_rnn import drums_rnn_pipeline from magenta.pipelines import pipeline import tensorflow.compat.v1 as tf flags = tf.app.flags FLAGS = tf.app.flags.FLAGS flags.DEFINE_string('input', None, 'TFRecord to read NoteSequence protos from.') flags.DEFINE_string( 'output_dir', None, 'Directory to write training and eval TFRecord files. The TFRecord files '<|fim▁hole|> 'Fraction of input to set aside for eval set. Partition is randomly ' 'selected.') flags.DEFINE_string( 'log', 'INFO', 'The threshold for what messages will be logged DEBUG, INFO, WARN, ERROR, ' 'or FATAL.') def main(unused_argv): tf.logging.set_verbosity(FLAGS.log) config = drums_rnn_config_flags.config_from_flags() pipeline_instance = drums_rnn_pipeline.get_pipeline( config, FLAGS.eval_ratio) FLAGS.input = os.path.expanduser(FLAGS.input) FLAGS.output_dir = os.path.expanduser(FLAGS.output_dir) pipeline.run_pipeline_serial( pipeline_instance, pipeline.tf_record_iterator(FLAGS.input, pipeline_instance.input_type), FLAGS.output_dir) def console_entry_point(): tf.disable_v2_behavior() tf.app.run(main) if __name__ == '__main__': console_entry_point()<|fim▁end|>
'are populated with SequenceExample protos.') flags.DEFINE_float( 'eval_ratio', 0.1,
<|file_name|>inherited_box.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedBox", inherited=True, gecko_name="Visibility") %> // TODO: collapse. Well, do tables first. ${helpers.single_keyword( "visibility", "visible hidden", extra_gecko_values="collapse", gecko_ffi_name="mVisible", animation_value_type="ComputedValue", spec="https://drafts.csswg.org/css-box/#propdef-visibility", )} // CSS Writing Modes Level 3 // https://drafts.csswg.org/css-writing-modes-3 ${helpers.single_keyword( "writing-mode", "horizontal-tb vertical-rl vertical-lr", extra_gecko_values="sideways-rl sideways-lr", extra_gecko_aliases="lr=horizontal-tb lr-tb=horizontal-tb \ rl=horizontal-tb rl-tb=horizontal-tb \ tb=vertical-rl tb-rl=vertical-rl", servo_pref="layout.writing-mode.enabled", animation_value_type="none", spec="https://drafts.csswg.org/css-writing-modes/#propdef-writing-mode", servo_restyle_damage="rebuild_and_reflow", )} ${helpers.single_keyword( "direction", "ltr rtl", animation_value_type="none", spec="https://drafts.csswg.org/css-writing-modes/#propdef-direction", needs_conversion=True, servo_restyle_damage="rebuild_and_reflow", )} ${helpers.single_keyword( "text-orientation", "mixed upright sideways", extra_gecko_aliases="sideways-right=sideways", products="gecko", animation_value_type="none", spec="https://drafts.csswg.org/css-writing-modes/#propdef-text-orientation", )} // CSS Color Module Level 4 // https://drafts.csswg.org/css-color/ ${helpers.single_keyword( "color-adjust", "economy exact", products="gecko", gecko_pref="layout.css.color-adjust.enabled", animation_value_type="discrete", spec="https://drafts.csswg.org/css-color/#propdef-color-adjust", )} // According to to CSS-IMAGES-3, `optimizespeed` and `optimizequality` are synonyms for `auto` // And, firefox doesn't support `pixelated` yet (https://bugzilla.mozilla.org/show_bug.cgi?id=856337) ${helpers.single_keyword( "image-rendering", "auto crisp-edges", extra_gecko_values="optimizespeed optimizequality", extra_servo_values="pixelated", extra_gecko_aliases="-moz-crisp-edges=crisp-edges", animation_value_type="discrete", spec="https://drafts.csswg.org/css-images/#propdef-image-rendering", )} ${helpers.single_keyword( "image-orientation", "none from-image", products="gecko", gecko_enum_prefix="StyleImageOrientation", animation_value_type="discrete", gecko_pref="layout.css.image-orientation.enabled",<|fim▁hole|>)}<|fim▁end|>
spec="https://drafts.csswg.org/css-images/#propdef-image-orientation",
<|file_name|>ResourceData.cpp<|end_file_name|><|fim▁begin|>#include "ResourceData.h" ResourceData::ResourceData() { } ResourceData::~ResourceData() {<|fim▁hole|><|fim▁end|>
}
<|file_name|>prune_hidden_pass.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Prunes things with the #[doc(hidden)] attribute use astsrv; use attr_parser; use doc::ItemUtils; use doc; use fold::Fold; use fold; use pass::Pass; pub fn mk_pass() -> Pass { Pass { name: ~"prune_hidden", f: run } } pub fn run(srv: astsrv::Srv, doc: doc::Doc) -> doc::Doc { let fold = Fold { ctxt: srv.clone(), fold_mod: fold_mod, .. fold::default_any_fold(srv) }; (fold.fold_doc)(&fold, doc) } fn fold_mod( fold: &fold::Fold<astsrv::Srv>, doc: doc::ModDoc ) -> doc::ModDoc { let doc = fold::default_any_fold_mod(fold, doc); doc::ModDoc { items: do doc.items.filtered |ItemTag| { !is_hidden(fold.ctxt.clone(), ItemTag.item()) }, .. doc<|fim▁hole|>fn is_hidden(srv: astsrv::Srv, doc: doc::ItemDoc) -> bool { use syntax::ast_map; let id = doc.id; do astsrv::exec(srv) |ctxt| { let attrs = match *ctxt.ast_map.get(&id) { ast_map::node_item(item, _) => copy item.attrs, _ => ~[] }; attr_parser::parse_hidden(attrs) } } #[test] fn should_prune_hidden_items() { use core::vec; let doc = test::mk_doc(~"#[doc(hidden)] mod a { }"); assert!(vec::is_empty(doc.cratemod().mods())) } #[cfg(test)] pub mod test { use astsrv; use doc; use extract; use prune_hidden_pass::run; pub fn mk_doc(source: ~str) -> doc::Doc { do astsrv::from_str(copy source) |srv| { let doc = extract::from_srv(srv.clone(), ~""); run(srv.clone(), doc) } } }<|fim▁end|>
} }
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|>from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from functools import wraps TRANSIENT_USER_TYPES = [] def is_transient_user(user): return isinstance(user, tuple(TRANSIENT_USER_TYPES)) def prevent_access_to_transient_users(view_func): def _wrapped_view(request, *args, **kwargs): '''Test if the user is transient''' for user_type in TRANSIENT_USER_TYPES: if is_transient_user(request.user): return HttpResponseRedirect('/') return view_func(request, *args, **kwargs) return login_required(wraps(view_func)(_wrapped_view)) def to_list(func): @wraps(func) def f(*args, **kwargs):<|fim▁hole|><|fim▁end|>
return list(func(*args, **kwargs)) return f
<|file_name|>SearchAlbum.js<|end_file_name|><|fim▁begin|>let React = require('react'), SearchItem = require('./SearchItem'); let SearchAlbum = React.createClass({ contextTypes: { updateRoute: React.PropTypes.func, goBack: React.PropTypes.func, data: React.PropTypes.array, addTrack: React.PropTypes.func, getAlbum: React.PropTypes.func }, componentWillMount () { this.context.getAlbum(); }, render () { let tracks, albumName, artistName, albumUrl, albumId; if (this.context.data.length > 0) { tracks = this.context.data[0].data.map((d, i) => { return ( <SearchItem key={i} data={ d } btnSrc="something.png" onClick={ this.context.addTrack.bind(null, d.id) } type="album-track" /> ); }); albumId = this.context.data[0].data[0].album.id; albumName = this.context.data[0].data[0].name artistName = this.context.data[0].data[0].artist.name;<|fim▁hole|> return ( <div> <div className="album-header"> <img src={ albumUrl } /> <div className="title"> <p>{ albumName }</p> <p>{ artistName }</p> </div> </div> <div className="searchResults"> <div className="searchListContainer"> <span className="listHeader">Tracks</span> <a className="navLink" onClick={ this.context.goBack }>{ '< Back' }</a> <ul className="list song-title-tile"> { tracks } </ul> </div> </div> </div> ); } }); module.exports = SearchAlbum;<|fim▁end|>
albumUrl = `http://direct.rhapsody.com/imageserver/v2/albums/${albumId}/images/170x170.jpg`; }
<|file_name|>test.cpp<|end_file_name|><|fim▁begin|>#include <gtest/gtest.h> #include "solution.h" TEST(test, testcase0) { Stack s; EXPECT_EQ(true, s.empty()); s.push(1); s.push(2); s.push(3); EXPECT_EQ(false, s.empty()); EXPECT_EQ(3, s.top());<|fim▁hole|> EXPECT_EQ(2, s.top()); s.pop(); EXPECT_EQ(1, s.top()); s.pop(); EXPECT_EQ(true, s.empty()); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }<|fim▁end|>
s.pop();
<|file_name|>record_spec.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 */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { path } from '../path'; import { fileBuffer } from './buffer'; import { CordHost } from './record'; import { test } from './test'; describe('CordHost', () => { const TestHost = test.TestHost; const mutatingTestRecord = ['write', 'delete', 'rename']; it('works (create)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.write(path`/blue`, fileBuffer`hi`).subscribe(undefined, done.fail); const target = new TestHost(); host.commit(target).subscribe(undefined, done.fail); expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'write', path: path`/blue` }, ]); expect(target.$exists('/hello')).toBe(false); expect(target.$exists('/blue')).toBe(true); done(); }); it('works (create -> create)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.write(path`/blue`, fileBuffer`hi`).subscribe(undefined, done.fail); host.write(path`/blue`, fileBuffer`hi again`).subscribe(undefined, done.fail); const target = new TestHost(); host.commit(target).subscribe(undefined, done.fail); expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'write', path: path`/blue` }, ]); expect(target.$exists('/hello')).toBe(false); expect(target.$exists('/blue')).toBe(true); expect(target.$read('/blue')).toBe('hi again'); done(); }); it('works (create -> delete)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.write(path`/blue`, fileBuffer`hi`).subscribe(undefined, done.fail); host.delete(path`/blue`).subscribe(undefined, done.fail); const target = new TestHost(); host.commit(target).subscribe(undefined, done.fail); expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([]); expect(target.$exists('/hello')).toBe(false); expect(target.$exists('/blue')).toBe(false); done(); }); it('works (create -> rename)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.write(path`/blue`, fileBuffer`hi`).subscribe(undefined, done.fail); host.rename(path`/blue`, path`/red`).subscribe(undefined, done.fail); const target = new TestHost(); host.commit(target).subscribe(undefined, done.fail); // Check that there's only 1 write done. expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'write', path: path`/red` }, ]); expect(target.$exists('/hello')).toBe(false); expect(target.$exists('/blue')).toBe(false); expect(target.$exists('/red')).toBe(true); done(); }); it('works (create -> rename (identity))', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.write(path`/blue`, fileBuffer`hi`).subscribe(undefined, done.fail); host.rename(path`/blue`, path`/blue`).subscribe(undefined, done.fail); const target = new TestHost(); host.commit(target).subscribe(undefined, done.fail); // Check that there's only 1 write done. expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'write', path: path`/blue` }, ]); expect(target.$exists('/hello')).toBe(false); expect(target.$exists('/blue')).toBe(true); done(); }); it('works (create -> rename -> rename)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.write(path`/blue`, fileBuffer`hi`).subscribe(undefined, done.fail); host.rename(path`/blue`, path`/red`).subscribe(undefined, done.fail); host.rename(path`/red`, path`/yellow`).subscribe(undefined, done.fail); const target = new TestHost(); host.commit(target).subscribe(undefined, done.fail); // Check that there's only 1 write done. expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'write', path: path`/yellow` }, ]); expect(target.$exists('/hello')).toBe(false); expect(target.$exists('/blue')).toBe(false); expect(target.$exists('/red')).toBe(false); expect(target.$exists('/yellow')).toBe(true); done(); }); it('works (rename)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.rename(path`/hello`, path`/blue`).subscribe(undefined, done.fail); const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); // Check that there's only 1 write done. expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'rename', from: path`/hello`, to: path`/blue` }, ]); expect(target.$exists('/hello')).toBe(false); expect(target.$exists('/blue')).toBe(true); done(); }); it('works (rename -> rename)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.rename(path`/hello`, path`/blue`).subscribe(undefined, done.fail); host.rename(path`/blue`, path`/red`).subscribe(undefined, done.fail); const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); // Check that there's only 1 write done. expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'rename', from: path`/hello`, to: path`/red` }, ]); expect(target.$exists('/hello')).toBe(false); expect(target.$exists('/blue')).toBe(false); expect(target.$exists('/red')).toBe(true); done(); }); it('works (rename -> create)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.rename(path`/hello`, path`/blue`).subscribe(undefined, done.fail); host.write(path`/hello`, fileBuffer`beautiful world`).subscribe(undefined, done.fail); const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); // Check that there's only 1 write done. expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'rename', from: path`/hello`, to: path`/blue` }, { kind: 'write', path: path`/hello` }, ]); expect(target.$exists('/hello')).toBe(true); expect(target.$exists('/blue')).toBe(true); done(); }); it('works (overwrite)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.write(path`/hello`, fileBuffer`beautiful world`).subscribe(undefined, done.fail); const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); // Check that there's only 1 write done. expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'write', path: path`/hello` }, ]); expect(target.$exists('/hello')).toBe(true); expect(target.$read('/hello')).toBe('beautiful world'); done(); }); it('works (overwrite -> overwrite)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.write(path`/hello`, fileBuffer`beautiful world`).subscribe(undefined, done.fail); host.write(path`/hello`, fileBuffer`again`).subscribe(undefined, done.fail); const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); // Check that there's only 1 write done. expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'write', path: path`/hello` }, ]); expect(target.$exists('/hello')).toBe(true); expect(target.$read('/hello')).toBe('again'); done(); }); it('works (overwrite -> rename)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.write(path`/hello`, fileBuffer`beautiful world`).subscribe(undefined, done.fail); host.rename(path`/hello`, path`/blue`).subscribe(undefined, done.fail); const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'rename', from: path`/hello`, to: path`/blue` }, { kind: 'write', path: path`/blue` }, ]); expect(target.$exists('/hello')).toBe(false); expect(target.$exists('/blue')).toBe(true); expect(target.$read('/blue')).toBe('beautiful world'); done(); }); it('works (overwrite -> delete)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.write(path`/hello`, fileBuffer`beautiful world`).subscribe(undefined, done.fail); host.delete(path`/hello`).subscribe(undefined, done.fail); const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'delete', path: path`/hello` }, ]); expect(target.$exists('/hello')).toBe(false); done(); }); it('works (rename -> overwrite)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.rename(path`/hello`, path`/blue`).subscribe(undefined, done.fail); host.write(path`/blue`, fileBuffer`beautiful world`).subscribe(undefined, done.fail); const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'rename', from: path`/hello`, to: path`/blue` }, { kind: 'write', path: path`/blue` }, ]); expect(target.$exists('/hello')).toBe(false); expect(target.$exists('/blue')).toBe(true); expect(target.$read('/blue')).toBe('beautiful world'); done(); }); it('works (delete)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.delete(path`/hello`).subscribe(undefined, done.fail); const target = new TestHost(); host.commit(target).subscribe(undefined, done.fail); expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'delete', path: path`/hello` }, ]); expect(target.$exists('/hello')).toBe(false); done(); }); it('works (delete -> create)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.delete(path`/hello`).subscribe(undefined, done.fail); host.write(path`/hello`, fileBuffer`beautiful world`).subscribe(undefined, done.fail); const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'write', path: path`/hello` }, ]); expect(target.$exists('/hello')).toBe(true); expect(target.$read('/hello')).toBe('beautiful world'); done(); }); it('works (rename -> delete)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.rename(path`/hello`, path`/blue`).subscribe(undefined, done.fail); host.delete(path`/blue`).subscribe(undefined, done.fail); <|fim▁hole|> expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'delete', path: path`/hello` }, ]); expect(target.$exists('/hello')).toBe(false); done(); }); it('works (delete -> rename)', (done) => { const base = new TestHost({ '/hello': 'world', '/blue': 'foo', }); const host = new CordHost(base); host.delete(path`/blue`).subscribe(undefined, done.fail); host.rename(path`/hello`, path`/blue`).subscribe(undefined, done.fail); const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'delete', path: path`/hello` }, { kind: 'write', path: path`/blue` }, ]); expect(target.$exists('/hello')).toBe(false); expect(target.$exists('/blue')).toBe(true); done(); }); it('errors: commit (create: exists)', () => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.write(path`/blue`, fileBuffer`hi`).subscribe(); const target = new TestHost({ '/blue': 'test', }); let error = false; host.commit(target).subscribe( undefined, () => (error = true), () => (error = false), ); expect(error).toBe(true); }); it('errors: commit (overwrite: not exist)', () => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.write(path`/hello`, fileBuffer`hi`).subscribe(); const target = new TestHost({}); let error = false; host.commit(target).subscribe( undefined, () => (error = true), () => (error = false), ); expect(error).toBe(true); }); it('errors: commit (rename: not exist)', () => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.rename(path`/hello`, path`/blue`).subscribe(); const target = new TestHost({}); let error = false; host.commit(target).subscribe( undefined, () => (error = true), () => (error = false), ); expect(error).toBe(true); }); it('errors: commit (rename: exist)', () => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.rename(path`/hello`, path`/blue`).subscribe(); const target = new TestHost({ '/blue': 'foo', }); let error = false; host.commit(target).subscribe( undefined, () => (error = true), () => (error = false), ); expect(error).toBe(true); }); it('errors (write directory)', () => { const base = new TestHost({ '/dir/hello': 'world', }); const host = new CordHost(base); let error = false; host.write(path`/dir`, fileBuffer`beautiful world`).subscribe( undefined, () => (error = true), () => (error = false), ); expect(error).toBe(true); }); it('errors (delete: not exist)', () => { const base = new TestHost({}); const host = new CordHost(base); let error = false; host.delete(path`/hello`).subscribe( undefined, () => (error = true), () => (error = false), ); expect(error).toBe(true); }); it('errors (rename: exist)', () => { const base = new TestHost({ '/hello': 'world', '/blue': 'foo', }); const host = new CordHost(base); let error = false; host.rename(path`/hello`, path`/blue`).subscribe( undefined, () => (error = true), () => (error = false), ); expect(error).toBe(true); }); it('errors (rename: not exist)', () => { const base = new TestHost({}); const host = new CordHost(base); let error = false; host.rename(path`/hello`, path`/blue`).subscribe( undefined, () => (error = true), () => (error = false), ); expect(error).toBe(true); }); });<|fim▁end|>
const target = base.clone(); host.commit(target).subscribe(undefined, done.fail);
<|file_name|>management.py<|end_file_name|><|fim▁begin|>from django.apps import apps from django.dispatch import receiver from django.db.models.signals import post_migrate @receiver(post_migrate, sender=apps.get_app_config('autodidact')) def create_homepage(sender, **kwargs): '''Receiver function that populates the database with a homepage in case it doesn't exist''' from .models import Page<|fim▁hole|><|fim▁end|>
if not Page.objects.exists(): Page(content='***Hello, world!***').save()
<|file_name|>day_4.rs<|end_file_name|><|fim▁begin|>#[derive(Default)]<|fim▁hole|>} impl Game { pub fn new() -> Game { Game { score: 0, rolls: Vec::with_capacity(21) } } pub fn roll(&mut self, pins: i32) { self.rolls.push(pins); } pub fn score(&self) -> i32 { let mut score = 0; let mut frame_index = 0; for _ in 0..10 { if self.is_strike(frame_index) { score += 10 + self.strike_bonus(frame_index); frame_index += 1; } else if self.is_spare(frame_index) { score += 10 + self.spare_bonus(frame_index); frame_index += 2; } else { score += self.frame_points(frame_index); frame_index += 2; } } score } fn is_spare(&self, frame_index: usize) -> bool { self.rolls[frame_index] + self.rolls[frame_index + 1] == 10 } fn spare_bonus(&self, frame_index: usize) -> i32 { self.rolls[frame_index + 2] } fn frame_points(&self, frame_index: usize) -> i32 { self.rolls[frame_index] + self.rolls[frame_index + 1] } fn is_strike(&self, frame_index: usize) -> bool { self.rolls[frame_index] == 10 } fn strike_bonus(&self, frame_index: usize) -> i32 { self.rolls[frame_index + 1] + self.rolls[frame_index + 2] } } #[cfg(test)] pub mod tests { use super::*; fn roll_many(game: &mut Game, times: i32, pins: i32) { for _ in 0..times { game.roll(pins); } } fn roll_spare(game: &mut Game) { game.roll(5); game.roll(5); } #[test] fn test_gutter_game() { let mut game = Game::new(); roll_many(&mut game, 20, 0); assert_eq!(game.score(), 0); } #[test] fn test_all_ones() { let mut game = Game::new(); roll_many(&mut game, 20, 1); assert_eq!(game.score(), 20); } #[test] fn test_one_spare() { let mut game = Game::new(); roll_spare(&mut game); game.roll(3); roll_many(&mut game, 17, 0); assert_eq!(game.score(), 16); } #[test] fn test_one_strike() { let mut game = Game::new(); game.roll(10); game.roll(3); game.roll(4); roll_many(&mut game, 16, 0); assert_eq!(game.score(), 24); } #[test] fn test_perfect_game() { let mut game = Game::new(); roll_many(&mut game, 12, 10); assert_eq!(game.score(), 300); } }<|fim▁end|>
#[allow(dead_code)] pub struct Game { score: i32, rolls: Vec<i32>,
<|file_name|>boxed.rs<|end_file_name|><|fim▁begin|>use std::any::{self, Any}; use std::ops::Deref; use neon_runtime::raw; use neon_runtime::external; use crate::context::{Context, FinalizeContext}; use crate::context::internal::Env; use crate::handle::{Managed, Handle}; use crate::types::internal::ValueInternal; use crate::types::Value; type BoxAny = Box<dyn Any + Send + 'static>; /// A smart pointer for Rust data managed by the JavaScript engine. /// /// The type `JsBox<T>` provides shared ownership of a value of type `T`, /// allocated in the heap. The data is owned by the JavaScript engine and the /// lifetime is managed by the JavaScript garbage collector. /// /// Shared references in Rust disallow mutation by default, and `JsBox` is no /// exception: you cannot generally obtain a mutable reference to something /// inside a `JsBox`. If you need to mutate through a `JsBox`, use /// [`Cell`](https://doc.rust-lang.org/std/cell/struct.Cell.html), /// [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html), /// or one of the other types that provide /// [interior mutability](https://doc.rust-lang.org/book/ch15-05-interior-mutability.html). /// /// Values contained by a `JsBox` must implement the `Finalize` trait. `Finalize::finalize` /// will execute with the value in a `JsBox` immediately before the `JsBox` is garbage /// collected. If no additional finalization is necessary, an emply implementation may /// be provided. /// /// /// ## `Deref` behavior /// /// `JsBox<T>` automatically dereferences to `T` (via the `Deref` trait), so /// you can call `T`'s method on a value of type `JsBox<T>`. /// /// ```rust /// # use neon::prelude::*; /// # fn my_neon_function(mut cx: FunctionContext) -> JsResult<JsUndefined> { /// let vec: Handle<JsBox<Vec<_>>> = cx.boxed(vec![1, 2, 3]); /// /// println!("Length: {}", vec.len()); /// # Ok(cx.undefined()) /// # } /// ``` /// /// ## Examples /// /// Passing some immutable data between Rust and JavaScript. /// /// ```rust /// # use neon::prelude::*; /// # use std::path::{Path, PathBuf}; /// fn create_path(mut cx: FunctionContext) -> JsResult<JsBox<PathBuf>> { /// let path = cx.argument::<JsString>(0)?.value(&mut cx); /// let path = Path::new(&path).to_path_buf(); /// /// Ok(cx.boxed(path)) /// } /// /// fn print_path(mut cx: FunctionContext) -> JsResult<JsUndefined> { /// let path = cx.argument::<JsBox<PathBuf>>(0)?; /// /// println!("{}", path.display()); /// /// Ok(cx.undefined()) /// } /// ``` /// /// Passing a user defined struct wrapped in a `RefCell` for mutability. This /// pattern is useful for creating classes in JavaScript.<|fim▁hole|>/// /// ```rust /// # use neon::prelude::*; /// # use std::cell::RefCell; /// /// type BoxedPerson = JsBox<RefCell<Person>>; /// /// struct Person { /// name: String, /// } /// /// impl Finalize for Person {} /// /// impl Person { /// pub fn new(name: String) -> Self { /// Person { name } /// } /// /// pub fn set_name(&mut self, name: String) { /// self.name = name; /// } /// /// pub fn greet(&self) -> String { /// format!("Hello, {}!", self.name) /// } /// } /// /// fn person_new(mut cx: FunctionContext) -> JsResult<BoxedPerson> { /// let name = cx.argument::<JsString>(0)?.value(&mut cx); /// let person = RefCell::new(Person::new(name)); /// /// Ok(cx.boxed(person)) /// } /// /// fn person_set_name(mut cx: FunctionContext) -> JsResult<JsUndefined> { /// let person = cx.argument::<BoxedPerson>(0)?; /// let mut person = person.borrow_mut(); /// let name = cx.argument::<JsString>(1)?.value(&mut cx); /// /// person.set_name(name); /// /// Ok(cx.undefined()) /// } /// /// fn person_greet(mut cx: FunctionContext) -> JsResult<JsString> { /// let person = cx.argument::<BoxedPerson>(0)?; /// let person = person.borrow(); /// let greeting = person.greet(); /// /// Ok(cx.string(greeting)) /// } pub struct JsBox<T: Send + 'static> { local: raw::Local, // Cached raw pointer to the data contained in the `JsBox`. This value is // required to implement `Deref` for `JsBox`. Unlike most `Js` types, `JsBox` // is not a transparent wrapper around a `napi_value` and cannot implement `This`. // // Safety: `JsBox` cannot verify the lifetime. Store a raw pointer to force // uses to be marked unsafe. In practice, it can be treated as `'static` but // should only be exposed as part of a `Handle` tied to a `Context` lifetime. // Safety: The value must not move on the heap; we must never give a mutable // reference to the data until the `JsBox` is no longer accessible. raw_data: *const T, } // Attempt to use a `napi_value` as a `napi_external` to unwrap a `BoxAny> /// Safety: `local` must be a `napi_value` that is valid for the lifetime `'a`. unsafe fn maybe_external_deref<'a>(env: Env, local: raw::Local) -> Option<&'a BoxAny> { external::deref::<BoxAny>(env.to_raw(), local) .map(|v| &*v) } // Custom `Clone` implementation since `T` might not be `Clone` impl<T: Send + 'static> Clone for JsBox<T> { fn clone(&self) -> Self { JsBox { local: self.local, raw_data: self.raw_data, } } } impl<T: Send + 'static> Copy for JsBox<T> {} impl<T: Send + 'static> Value for JsBox<T> { } impl<T: Send + 'static> Managed for JsBox<T> { fn to_raw(self) -> raw::Local { self.local } fn from_raw(env: Env, local: raw::Local) -> Self { let raw_data = unsafe { maybe_external_deref(env, local) } .expect("Failed to unwrap napi_external as Box<Any>") .downcast_ref() .expect("Failed to downcast Any"); Self { local, raw_data, } } } impl<T: Send + 'static> ValueInternal for JsBox<T> { fn name() -> String { any::type_name::<Self>().to_string() } fn is_typeof<Other: Value>(env: Env, other: Other) -> bool { let data = unsafe { maybe_external_deref(env, other.to_raw()) }; data.map(|v| v.is::<T>()).unwrap_or(false) } fn downcast<Other: Value>(env: Env, other: Other) -> Option<Self> { let local = other.to_raw(); let data = unsafe { maybe_external_deref(env, local) }; // Attempt to downcast the `Option<&BoxAny>` to `Option<*const T>` data.and_then(|v| v.downcast_ref()) .map(|raw_data| Self { local, raw_data, }) } } /// Values contained by a `JsBox` must be `Finalize + Send + 'static` /// /// ### `Finalize` /// /// The `neon::prelude::Finalize` trait provides a `finalize` method that will be called /// immediately before the `JsBox` is garbage collected. /// /// ### `Send` /// /// `JsBox` may be moved across threads. It is important to guarantee that the /// contents is also safe to move across threads. /// /// ### `'static' /// /// The lifetime of a `JsBox` is managed by the JavaScript garbage collector. Since Rust /// is unable to verify the lifetime of the contents, references must be valid for the /// entire duration of the program. This does not mean that the `JsBox` will be valid /// until the application terminates, only that its lifetime is indefinite. impl<T: Finalize + Send + 'static> JsBox<T> { /// Constructs a new `JsBox` containing `value`. pub fn new<'a, C>(cx: &mut C, value: T) -> Handle<'a, JsBox<T>> where C: Context<'a>, T: Send + 'static, { // This function will execute immediately before the `JsBox` is garbage collected. // It unwraps the `napi_external`, downcasts the `BoxAny` and moves the type // out of the `Box`. Lastly, it calls the trait method `Finalize::fianlize` of the // contained value `T`. fn finalizer<U: Finalize + 'static>(env: raw::Env, data: BoxAny) { let data = *data.downcast::<U>().unwrap(); let env = unsafe { std::mem::transmute(env) }; FinalizeContext::with( env, move |mut cx| data.finalize(&mut cx), ); } let v = Box::new(value) as BoxAny; // Since this value was just constructed, we know it is `T` let raw_data = &*v as *const dyn Any as *const T; let local = unsafe { external::create(cx.env().to_raw(), v, finalizer::<T>) }; Handle::new_internal(Self { local, raw_data, }) } } impl<'a, T: Send + 'static> Deref for JsBox<T> { type Target = T; fn deref(&self) -> &Self::Target { // Safety: This depends on a `Handle<'a, JsBox<T>>` wrapper to provide // a proper lifetime. unsafe { &*self.raw_data } } } /// Finalize is executed on the main JavaScript thread and executed immediately /// before garbage collection. /// Values contained by a `JsBox` must implement `Finalize`. /// /// ## Examples /// /// `Finalize` provides a default implementation that does not perform any finalization. /// /// ```rust /// # use neon::prelude::*; /// struct Point(f64, f64); /// /// impl Finalize for Point {} /// ``` /// /// A `finalize` method may be specified for performing clean-up operations before dropping /// the contained value. /// /// ```rust /// # use neon::prelude::*; /// struct Point(f64, f64); /// /// impl Finalize for Point { /// fn finalize<'a, C: Context<'a>>(self, cx: &mut C) { /// let global = cx.global(); /// let emit = global /// .get(cx, "emit") /// .unwrap() /// .downcast::<JsFunction, _>(cx) /// .unwrap(); /// /// let args = vec![ /// cx.string("gc_point").upcast::<JsValue>(), /// cx.number(self.0).upcast(), /// cx.number(self.1).upcast(), /// ]; /// /// emit.call(cx, global, args).unwrap(); /// } /// } /// ``` pub trait Finalize: Sized { fn finalize<'a, C: Context<'a>>(self, _: &mut C) {} } // Primitives impl Finalize for bool {} impl Finalize for char {} impl Finalize for i8 {} impl Finalize for i16 {} impl Finalize for i32 {} impl Finalize for i64 {} impl Finalize for isize {} impl Finalize for u8 {} impl Finalize for u16 {} impl Finalize for u32 {} impl Finalize for u64 {} impl Finalize for usize {} impl Finalize for f32 {} impl Finalize for f64 {} // Common types impl Finalize for String {} impl Finalize for std::path::PathBuf {} // Tuples macro_rules! finalize_tuple_impls { ($( $name:ident )+) => { impl<$($name: Finalize),+> Finalize for ($($name,)+) { fn finalize<'a, C: Context<'a>>(self, cx: &mut C) { #![allow(non_snake_case)] let ($($name,)+) = self; ($($name.finalize(cx),)+); } } }; } impl Finalize for () {} finalize_tuple_impls! { T0 } finalize_tuple_impls! { T0 T1 } finalize_tuple_impls! { T0 T1 T2 } finalize_tuple_impls! { T0 T1 T2 T3 } finalize_tuple_impls! { T0 T1 T2 T3 T4 } finalize_tuple_impls! { T0 T1 T2 T3 T4 T5 } finalize_tuple_impls! { T0 T1 T2 T3 T4 T5 T6 } finalize_tuple_impls! { T0 T1 T2 T3 T4 T5 T6 T7 } // Collections impl<T: Finalize> Finalize for Vec<T> { fn finalize<'a, C: Context<'a>>(self, cx: &mut C) { for item in self { item.finalize(cx); } } } // Smart Pointers impl<T: Finalize> Finalize for std::boxed::Box<T> { fn finalize<'a, C: Context<'a>>(self, cx: &mut C) { (*self).finalize(cx); } } impl<T: Finalize> Finalize for std::rc::Rc<T> { fn finalize<'a, C: Context<'a>>(self, cx: &mut C) { if let Ok(v) = std::rc::Rc::try_unwrap(self) { v.finalize(cx); } } } impl<T: Finalize> Finalize for std::sync::Arc<T> { fn finalize<'a, C: Context<'a>>(self, cx: &mut C) { if let Ok(v) = std::sync::Arc::try_unwrap(self) { v.finalize(cx); } } } impl<T: Finalize> Finalize for std::sync::Mutex<T> { fn finalize<'a, C: Context<'a>>(self, cx: &mut C) { if let Ok(v) = self.into_inner() { v.finalize(cx); } } } impl<T: Finalize> Finalize for std::sync::RwLock<T> { fn finalize<'a, C: Context<'a>>(self, cx: &mut C) { if let Ok(v) = self.into_inner() { v.finalize(cx); } } } impl<T: Finalize> Finalize for std::cell::Cell<T> { fn finalize<'a, C: Context<'a>>(self, cx: &mut C) { self.into_inner().finalize(cx); } } impl<T: Finalize> Finalize for std::cell::RefCell<T> { fn finalize<'a, C: Context<'a>>(self, cx: &mut C) { self.into_inner().finalize(cx); } }<|fim▁end|>
<|file_name|>trip_planner.js<|end_file_name|><|fim▁begin|>var coords; var directionsDisplay; var map; var travelMode; var travelModeElement = $('#mode_travel'); // Order of operations for the trip planner (each function will have detailed notes): // 1) Calculate a user's route, with directions. // 2) Run a query using the route's max and min bounds to narrow potential results. // 3) Just because a marker is in the area of the route, it doesn't mean that it's on the route. // Use RouteBoxer to map sections of the route to markers, if applicable. Display only those markers on the map. // 4) The directions panel also isn't linked to a section of the route. // Use RouteBoxer to map a direction (turn left, right, etc) to part of the route. // 5) Build the custom directions panel by looping though each leg of the trip, finding the corresponding RouteBoxer // section, and use that to get markers for that section only. $(document).ready(function () { $('.active').toggleClass('active'); $('#trip-planner').toggleClass('active'); }); // Run these functions after setting geolocation. All except setFormDateTime() are dependent on geolocation to run. initGeolocation().then(function (coords) { map = mapGenerator(coords); setDirectionsDisplay(map); formListener(); }); // Instantiate directions methods on map. function setDirectionsDisplay(map) { directionsDisplay = new google.maps.DirectionsRenderer(); directionsDisplay.setMap(map); } // Listener for if the mode of travel is changed from an empty default to either bicycling or walking. function formListener() { travelModeElement.change(function(){ // Launch route calculation, markers, and directions panel. calcRoute(); }); } // Once the mode of travel is selected, start calculating routes and get marker data. function calcRoute() { var directionsService = new google.maps.DirectionsService(); var start = $('#start').val(); var end = $('#end').val(); travelMode = travelModeElement.val(); var request = { origin: start, destination: end, travelMode: google.maps.TravelMode[travelMode] }; directionsService.route(request, function (response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); // Remove existing markers from the map and map object. removeMarkers(true); queryResults = getMarkers(response); // Check if results are along the route. if (queryResults.objects.length > 0) { // Filter the query results further by comparing coords with each route section. narrowResults(queryResults.objects, response); // If no query results, set the marker count to 0 and generate the directions panel. } else { response.routes[0].legs[0]['marker_count'] = 0; generateDirectionsPanel(response); } } }); } // Get markers near a route. This is done by getting the boundaries for the route as a whole and using those // as query params. function getMarkers(response){ var userType; if (travelMode == "BICYCLING") { userType = 1; } else { userType = 2; } // Build the query string, limiting the results for cyclists and pedestrians. var queryString = '/api/v1/hazard/?format=json&?user_type=' + userType; // Get the maximum and minimum lat/lon bounds for the route. // This will narrow the query to a box around the route as a whole. var routeBounds = getBounds(response.routes[0].bounds); // TODO(zemadi): Look up alternatives for building the querystring. //Build the querystring. Negative numbers require different greater/less than logic, // so testing for that here. if (routeBounds.lat1 >= 0 && routeBounds.lat2 >= 0) { queryString += '&lat__gte=' + routeBounds.lat1 + '&lat__lte=' + routeBounds.lat2; } else { queryString += '&lat__gte=' + routeBounds.lat2 + '&lat__lte=' + routeBounds.lat1; } if (routeBounds.lon1 >= 0 && routeBounds.lon2 >= 0) { queryString += '&lon__gte=' + routeBounds.lon1 + '&lon__lte=' + routeBounds.lon2; } else { queryString += '&lon__gte=' + routeBounds.lon2 + '&lon__lte=' + routeBounds.lon1; } return httpGet(queryString); } // Function to get coordinate boundaries from the Directions route callback. function getBounds(data) { var coordinateBounds = {}; var keyByIndex = Object.keys(data); <|fim▁hole|> coordinateBounds['lon1'] = data[keyByIndex[1]]['k']; coordinateBounds['lon2'] = data[keyByIndex[1]]['j']; return coordinateBounds; } // Reduce the query results further by checking if they're actually along a route. // In order for a data point to be on the route, the coordinates need to be between the values of a box in routeBoxer. // RouteBoxer chops up a route into sections and returns the upper and lower boundaries for that section of the route. // Refer to: http://google-maps-utility-library-v3.googlecode.com/svn/trunk/routeboxer/docs/examples.html function narrowResults(queryResults, directionsResponse) { // Variables needed for routeBoxer. var path = directionsResponse.routes[0].overview_path; var rboxer = new RouteBoxer(); var boxes = rboxer.box(path, .03); // Second param is a boundary in km from the route path. //Variables to hold mapData and match a marker to a specific section of the route. var mapData = {'objects': []}; // Object to hold routeBoxer index to markers map. var mapBoxesAndMarkers = {}; // For each section of the route, look through markers to see if any fit in the section's boundaries. // Using a for loop here because routeBoxer returns an array. for (var j = 0, b=boxes.length; j < b; j++) { // For each section of the route, record the index as a key and create an empty array to hold marker values. mapBoxesAndMarkers[j] = []; queryResults.forEach(function(result) { // If a marker is between the latitude and longitude bounds of the route, add it to the map and // the route-marker dict. var currentResult = new google.maps.LatLng(result.lat, result.lon); if (boxes[j].contains(currentResult)) { mapData.objects.push(result); mapBoxesAndMarkers[j].push(result); } }); } if (mapData.objects.length > 0) { // Add new markers to the map. markerGenerator(map, mapData); // Add the count of valid markers to the directionsResponse object, which is used to generate // the directions panel. If there are no markers, add 'None'. directionsResponse.routes[0].legs[0]['marker_count'] = mapData.objects.length; } else { directionsResponse.routes[0].legs[0]['marker_count'] = 'None'; } mapDirectionsToBoxes(boxes, directionsResponse, mapBoxesAndMarkers); } // Directions information also needs to be mapped to a section of the route. function mapDirectionsToBoxes(boxes, directionsResponse, mapBoxesAndMarkers){ var directions = directionsResponse.routes[0].legs[0].steps; // go through each step and set of lat lngs per step. directions.forEach(function(direction) { var routeBoxesinDirection = []; for (var l = 0, b=boxes.length; l < b; l++) { direction.lat_lngs.forEach(function(lat_lng) { // If the index isn't already in the array and the box contains the current route's lat and long, add the // index. if (routeBoxesinDirection.indexOf(l) === -1 && boxes[l].contains(lat_lng)) { routeBoxesinDirection.push(l); } }); } // Once we're done looping over route boxes for the current direction, lookup markers that have the same bounds. // A direction can have multiple route boxes so a list is being used here. direction['markers'] = []; routeBoxesinDirection.forEach(function(box) { if (mapBoxesAndMarkers[box].length > 0) { // Use the route box to look up arrays of markers to add to the directions object. direction['markers'].push.apply(direction['markers'], mapBoxesAndMarkers[box]); } }); }); generateDirectionsPanel(directionsResponse); } function generateDirectionsPanel(directionsResponse) { var directionsPanel = $('#directions-panel'); var directionsPanelHtml = $('#directions-panel-template').html(); var newSearchTrigger = $('#new-search-trigger'); var template = Handlebars.compile(directionsPanelHtml); var compiledDirectionsPanel = template(directionsResponse.routes[0].legs[0]); if (directionsPanel[0].children.length > 0) { directionsPanel[0].innerHTML = compiledDirectionsPanel; } else { directionsPanel.append(compiledDirectionsPanel); } // Close the trip planner form and display the directions panel. $('#trip-planner-form').addClass('closed'); directionsPanel.removeClass('closed'); newSearchTrigger.removeClass('hidden'); // Listen for a new search event, which shows the form and closes the directions panel. newSearchTrigger.click(function(){ directionsPanel.addClass('closed'); newSearchTrigger.addClass('hidden'); $('#trip-planner-form').removeClass('closed'); }); }<|fim▁end|>
coordinateBounds['lat1'] = data[keyByIndex[0]]['k']; coordinateBounds['lat2'] = data[keyByIndex[0]]['j'];
<|file_name|>base-input.d.ts<|end_file_name|><|fim▁begin|>import { AfterContentInit, ElementRef, EventEmitter, Renderer } from '@angular/core'; import { ControlValueAccessor } from '@angular/forms'; import { NgControl } from '@angular/forms'; import { IonicFormInput } from './form'; import { Ion } from '../components/ion'; import { Config } from '../config/config'; import { Item } from '../components/item/item'; import { Form } from './form'; import { TimeoutDebouncer } from './debouncer'; export interface CommonInput<T> extends ControlValueAccessor, AfterContentInit, IonicFormInput { id: string; disabled: boolean; value: T; ionFocus: EventEmitter<CommonInput<T>>; ionChange: EventEmitter<BaseInput<T>>; ionBlur: EventEmitter<BaseInput<T>>; initFocus(): void;<|fim▁hole|> _inputNormalize(val: any): T; _inputShouldChange(val: T): boolean; _inputUpdated(): void; } export declare class BaseInput<T> extends Ion implements CommonInput<T> { private _defaultValue; _form: Form; _item: Item; _ngControl: NgControl; _value: T; _onChanged: Function; _onTouched: Function; _isFocus: boolean; _labelId: string; _disabled: boolean; _debouncer: TimeoutDebouncer; _init: boolean; _initModel: boolean; id: string; /** * @output {Range} Emitted when the range selector drag starts. */ ionFocus: EventEmitter<BaseInput<T>>; /** * @output {Range} Emitted when the range value changes. */ ionChange: EventEmitter<BaseInput<T>>; /** * @output {Range} Emitted when the range selector drag ends. */ ionBlur: EventEmitter<BaseInput<T>>; /** * @input {boolean} If true, the user cannot interact with this element. */ disabled: boolean; constructor(config: Config, elementRef: ElementRef, renderer: Renderer, name: string, _defaultValue: T, _form: Form, _item: Item, _ngControl: NgControl); value: T; setValue(val: any): void; /** * @hidden */ setDisabledState(isDisabled: boolean): void; /** * @hidden */ writeValue(val: any): void; /** * @hidden */ _writeValue(val: any): boolean; /** * @hidden */ _fireIonChange(): void; /** * @hidden */ registerOnChange(fn: Function): void; /** * @hidden */ registerOnTouched(fn: any): void; /** * @hidden */ _initialize(): void; /** * @hidden */ _fireFocus(): void; /** * @hidden */ _fireBlur(): void; /** * @hidden */ private _setFocus(isFocused); /** * @hidden */ private onChange(); /** * @hidden */ isFocus(): boolean; /** * @hidden */ hasValue(): boolean; /** * @hidden */ focusNext(): void; /** * @hidden */ ngOnDestroy(): void; /** * @hidden */ ngAfterContentInit(): void; /** * @hidden */ initFocus(): void; /** * @hidden */ _inputNormalize(val: any): T; /** * @hidden */ _inputShouldChange(val: T): boolean; /** * @hidden */ _inputChangeEvent(): any; /** * @hidden */ _inputNgModelEvent(): any; /** * @hidden */ _inputUpdated(): void; }<|fim▁end|>
isFocus(): boolean;
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
from jroc.tasks.tokenizers.TokenizerTask import SentenceTokenizerTask, WordTokenizerTask
<|file_name|>test_lookup.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import unittest from pyparsing import ParseException from cwr.grammar.field import basic """ Tests for Table/List Lookup (L) fields. """ __author__ = 'Bernardo Martínez Garrido' __license__ = 'MIT' __status__ = 'Development' class TestLookupName(unittest.TestCase): def test_name_default(self): """ Tests that the default field name is correct for optional fields. """ field = basic.lookup(['AB1', 'CD2', 'EF3']) self.assertEqual('Lookup Field', field.name) def test_name_set(self): """ Tests that the given field name is set correctly for optional fields. """ name = "Field Name" field = basic.lookup(['AB1', 'CD2', 'EF3'], name=name) self.assertEqual(name, field.name) def test_name_set_no_changes(self): """ Tests that the field name does not change for creating a new one """ field1 = basic.lookup(['AB1', 'CD2', 'EF3'], name='field1') field2 = basic.lookup(['AB1', 'CD2', 'EF3'], name='field2') self.assertEqual('field1', field1.name) self.assertEqual('field2', field2.name) class TestLookupValid(unittest.TestCase): """ Tests that the lookup field accepts and parse valid values. """<|fim▁hole|> def test_valid(self): """ Tests that the field accepts a valid value """ result = self.lookup.parseString('CD2') self.assertEqual('CD2', result[0]) class TestLookupExceptionCompulsory(unittest.TestCase): def setUp(self): self.lookup = basic.lookup(['AB1', 'CD2', 'EF3']) def test_invalid(self): """ Tests that an exception is thrown when parsing an invalid value """ self.assertRaises(ParseException, self.lookup.parseString, 'AEI') def test_empty(self): """ Tests that an exception is thrown when parsing an invalid value """ self.assertRaises(ParseException, self.lookup.parseString, '') def test_whitespace(self): """ Tests that an exception is thrown when parsing an invalid value """ self.assertRaises(ParseException, self.lookup.parseString, ' ')<|fim▁end|>
def setUp(self): self.lookup = basic.lookup(['AB1', 'CD2', 'EF3'])
<|file_name|>forms.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import re from django.conf import settings from django.core import validators from django.core.exceptions import ValidationError from django.forms.util import ErrorList from django.forms.fields import MultiValueField, FilePathField, \ FileField, CharField from django.utils.translation import ugettext as _ from hybrid_filefield.widgets import FileSelectOrUploadWidget class FileSelectOrUploadField(MultiValueField): widget = FileSelectOrUploadWidget default_error_messages = { 'optional_required': _('At least one value is required.'), } def __init__(self, upload_to='', path='', match='', recursive=False, widget=None, initial=None, optional=False, *args, **kwargs): self.upload_to, self.path, self.match, \ self.recursive, self.initial, self.optional = \ upload_to, path, match, recursive, initial, optional self.max_length = kwargs.pop('max_length', None) self.required = getattr(kwargs, 'required', True) fields = ( FilePathField( path=self.path, match=self.match, recursive=self.recursive, initial=self.initial, required=self.required, ), FileField( max_length=self.max_length, initial=self.initial, required=self.required, ), ) widget = widget or self.widget if isinstance(widget, type): widget = widget() self.widget = widget super(FileSelectOrUploadField, self).__init__( fields, widget=self.widget, *args, **kwargs ) self.choices = [('', 'Use upload')] + fields[0].choices self.widget.is_required = self.required def _get_choices(self): return self._choices def _set_choices(self, value): self._choices = self.widget.choices = list(value) choices = property(_get_choices, _set_choices) def clean(self, value): clean_data = [] errors = ErrorList() if value in validators.EMPTY_VALUES and self.required: raise ValidationError(self.error_messages['required']) for i, field in enumerate(self.fields): try: field_value = value[i] except IndexError:<|fim▁hole|> if (self.required and not self.optional): raise ValidationError(self.error_messages['required']) else: field_value = field_value try: clean_data.append(field.clean(field_value)) except ValidationError, e: errors.extend(e.messages) if i == len(self.fields) and len(clean_data) == 0: raise ValidationError(self.error_messages['optional_required']) if errors: raise ValidationError(errors) return self.compress(clean_data) def compress(self, data_list): if len(data_list) > 1 and data_list[1] not in validators.EMPTY_VALUES: return data_list[1] elif len(data_list) > 0 and data_list[0] not in validators.EMPTY_VALUES: return data_list[0] return None<|fim▁end|>
field_value = None if field_value in validators.EMPTY_VALUES:
<|file_name|>index.tsx<|end_file_name|><|fim▁begin|>import * as React from "react"; import {render} from "react-dom"; import {AppContainer} from "react-hot-loader"; import App from "./components/App"; const rootEl = document.getElementById("root"); render(<|fim▁hole|> rootEl ); // Hot Module Replacement API declare let module: { hot: any }; if (module.hot) { module.hot.accept("./components/App", () => { const NewApp = require("./components/App").default; render( <AppContainer> <NewApp/> </AppContainer>, rootEl ); }); }<|fim▁end|>
<AppContainer> <App/> </AppContainer>,
<|file_name|>generate_config.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import from __future__ import unicode_literals import collections import jsonschema DEFAULT_GENERATE_CONFIG_FILENAME = 'generate_config.yaml' GENERATE_OPTIONS_SCHEMA = { 'type': 'object', 'required': ['repo', 'database'], 'properties': { 'skip_default_metrics': {'type': 'boolean'}, 'tempdir_location': {'type': ['string', 'null']}, 'metric_package_names': {'type': 'array', 'items': {'type': 'string'}}, 'repo': {'type': 'string'}, 'database': {'type': 'string'}, }, } class GenerateOptions(collections.namedtuple( 'GenerateOptions', [ 'skip_default_metrics', 'tempdir_location', 'metric_package_names', 'repo',<|fim▁hole|> @classmethod def from_yaml(cls, yaml_dict): jsonschema.validate(yaml_dict, GENERATE_OPTIONS_SCHEMA) return cls( skip_default_metrics=yaml_dict.get('skip_default_metrics', False), tempdir_location=yaml_dict.get('tempdir_location', None), metric_package_names=yaml_dict.get('metric_package_names', []), repo=yaml_dict['repo'], database=yaml_dict['database'], ) def to_yaml(self): ret = {'repo': self.repo, 'database': self.database} if self.skip_default_metrics is True: ret['skip_default_metrics'] = True if self.metric_package_names: ret['metric_package_names'] = list(self.metric_package_names) if self.tempdir_location: ret['tempdir_location'] = self.tempdir_location return ret<|fim▁end|>
'database', ], )):
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # "convertor" - converts ODF files from a YUSCII font-encoding to proper UTF-8. # Copyright (C) 2009 Damjan Georgievski # # This program 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. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import setuptools __author__ = 'Damjan Georgievski' __version__ = '2.0' __email__ = '[email protected]' setuptools.setup( name = 'convertor', version = __version__, author = __author__, author_email = __email__, description = 'converts ODF files from a YUSCII font-encoding to proper UTF-8 ODF', license = 'AGPL 3.0', url = 'http://github.com/gdamjan/convertor', packages = ['convertor'], package_data = {}, keywords = "ODF", include_package_data = True, classifiers = [ 'Development Status :: 3 - Alpha',<|fim▁hole|> zip_safe = False, entry_points = { 'console_scripts': ['convertor=convertor.__main__:main'] }, install_requires = ['lxml'], extras_require = { "web": "Werkzeug" } )<|fim▁end|>
'Programming Language :: Python :: 3.6' ], test_suite = '',
<|file_name|>functions.py<|end_file_name|><|fim▁begin|>#!/bin/env python #-*-coding:utf-8-*- import MySQLdb import string import time import datetime import os import re import json import sys reload(sys) sys.setdefaultencoding('utf8') import ConfigParser import smtplib from email.mime.text import MIMEText from email.message import Message from email.header import Header from pymongo import MongoClient import dba_crypto as crypt basePath = "/usr/local/camelbell" fCnf = "%s/etc/config.ini" % (basePath) def get_item(data_dict,item,default='-1'): if data_dict.has_key(item): return data_dict[item] else: return default def get_config(group,config_name,default='-1'): config = ConfigParser.ConfigParser() config.readfp(open(fCnf,'rw')) if config.has_option(group,config_name): config_value=config.get(group,config_name).strip(' ').strip('\'').strip('\"') else: config_value=default return config_value def get_option(key): conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8') conn.select_db(dbname) cursor = conn.cursor() sql="select value from options where name='%s'" % (key) count=cursor.execute(sql) if count == 0 : result=0 else: result=(cursor.fetchone())[0] cursor.close() conn.close() return result def filters(data): return data.strip(' ').strip('\n').strip('\br') server_key = 'monitor_server' host = get_config(server_key,'host') port = get_config(server_key,'port') user = get_config(server_key,'user') passwd = get_config(server_key,'passwd') dbname = get_config(server_key,'dbname') server_mongodb_key = 'monitor_server_mongodb' mongodb_host = get_config(server_mongodb_key,'host') mongodb_port = get_config(server_mongodb_key,'port') mongodb_user = get_config(server_mongodb_key,'user') mongodb_passwd = get_config(server_mongodb_key,'passwd') mongodb_dbname = get_config(server_mongodb_key,'dbname') mongodb_replicaSet = get_config(server_mongodb_key,'replicaSet') ''' # collection 函数文档 http://api.mongodb.com/python/current/api/pymongo/collection.html?_ga=1.219309790.610772200.1468379950#pymongo.collection.Collection.find ''' def mongodb_save(tb_name, params): inpParams = params inpParams.pop("id", None) connect_mongodb = None try: connect_mongodb = MongoClient(host=mongodb_host,port=int(mongodb_port),replicaSet=mongodb_replicaSet) db = connect_mongodb.get_database(mongodb_dbname) db.authenticate(mongodb_user, mongodb_passwd, mechanism='SCRAM-SHA-1') tb = db[tb_name] tb.insert_one(inpParams) #print tb.find_one() #print tb.find_one(sort=[("create_time",-1)]) print tb.count() ''' tlines = tb.find(limit=10).sort([("create_time",-1)]) for tline in tlines: print tline ''' except Exception, e: logger_msg="insert alarm to mongodb %s:%s/%s,%s/%s : %s" %(mongodb_host,mongodb_port,mongodb_dbname,mongodb_user,mongodb_passwd,e) print logger_msg finally: if connect_mongodb != None: connect_mongodb.close() def other_save(tb_name, params): mongodb_save(tb_name, params) def mysql_exec_many(sqls,params=None): try: conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8') conn.select_db(dbname) curs = conn.cursor() curs.execute("set session sql_mode=''") for i in range(0,len(sqls)): sql = sqls[i] if params != None and params[i] <> '': curs.execute(sql,params[i]) else: curs.execute(sql) curs.close() conn.commit() conn.close() except Exception,e: print "mysql execute: %s,%s" % (sqls, e) conn.rollback() def mysql_exec(sql,params=''): try: conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8') conn.select_db(dbname) curs = conn.cursor() ''' curs.execute("set session sql_mode=''") curs.execute("SELECT CONNECTION_ID() AS cid") cnntID = (curs.fetchall())[0][0] #print sql ''' if params <> '': if len(params) > 0 and (isinstance(params[0], tuple) or isinstance(params[0], list)): curs.executemany(sql, params) else: curs.execute(sql,params) else: curs.execute(sql) curs.close() conn.commit() conn.close() except Exception, e: print "Error: %s" % (sql) print "Exception: %s" % (e) conn.rollback() def mysql_query(sql): conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8') conn.select_db(dbname) cursor = conn.cursor() #cursor.execute("set session sql_mode=''") count=cursor.execute(sql) if count == 0 : result=0 else: result=cursor.fetchall() cursor.close() conn.close() return result send_mail_max_count = get_option('send_mail_max_count') send_mail_sleep_time = get_option('send_mail_sleep_time') mail_to_list_common = get_option('send_mail_to_list') def add_alarm(server_id,tags,db_host,db_port,create_time,db_type,alarm_item,alarm_value,level,message,send_mail=1,send_mail_to_list=mail_to_list_common, send_sms=0, send_sms_to_list=''): inpParams = locals() try: conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8') conn.select_db(dbname) curs = conn.cursor() sql="insert into alarm(server_id,tags,host,port,create_time,db_type,alarm_item,alarm_value,level,message,send_mail,send_mail_to_list,send_sms,send_sms_to_list) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);" param=(server_id,tags,db_host,db_port,create_time,db_type,alarm_item,alarm_value,level,message,send_mail,send_mail_to_list,send_sms,send_sms_to_list) curs.execute(sql,param) if send_mail == 1: temp_sql = "insert into alarm_temp(server_id,ip,db_type,alarm_item,alarm_type) values(%s,%s,%s,%s,%s);" temp_param = (server_id,db_host,db_type,alarm_item,'mail') curs.execute(temp_sql,temp_param) if send_sms == 1: temp_sql = "insert into alarm_temp(server_id,ip,db_type,alarm_item,alarm_type) values(%s,%s,%s,%s,%s);" temp_param = (server_id,db_host,db_type,alarm_item,'sms') curs.execute(temp_sql,temp_param) if (send_mail ==0 and send_sms==0): temp_sql = "insert into alarm_temp(server_id,ip,db_type,alarm_item,alarm_type) values(%s,%s,%s,%s,%s);" temp_param = (server_id,db_host,db_type,alarm_item,'none') curs.execute(temp_sql,temp_param) conn.commit() curs.close() conn.close() except Exception,e: print "Add alarm: " + str(e) # insert mongodb mongodb_save("alarm_logs",inpParams) def check_if_ok(server_id,tags,db_host,db_port,create_time,db_type,alarm_item,alarm_value,message,send_mail,send_mail_to_list,send_sms,send_sms_to_list): conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8') conn.select_db(dbname) curs = conn.cursor() if db_type=='os': alarm_count=curs.execute("select id from alarm_temp where ip='%s' and alarm_item='%s' ;" %(db_host,alarm_item)) mysql_exec("delete from alarm_temp where ip='%s' and alarm_item='%s' ;" %(db_host,alarm_item),'') else: alarm_count=curs.execute("select id from alarm_temp where server_id=%s and db_type='%s' and alarm_item='%s' ;" %(server_id,db_type,alarm_item)) mysql_exec("delete from alarm_temp where server_id=%s and db_type='%s' and alarm_item='%s' ;" %(server_id,db_type,alarm_item),'') if int(alarm_count) > 0 : sql="insert into alarm(server_id,tags,host,port,create_time,db_type,alarm_item,alarm_value,level,message,send_mail,send_mail_to_list,send_sms,send_sms_to_list) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);" param=(server_id,tags,db_host,db_port,create_time,db_type,alarm_item,alarm_value,'ok',message,send_mail,send_mail_to_list,send_sms,send_sms_to_list) mysql_exec(sql,param) curs.close() conn.close() def update_send_mail_status(server,db_type,alarm_item,send_mail,send_mail_max_count): conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8') conn.select_db(dbname) curs = conn.cursor() if db_type == "os": alarm_count=curs.execute("select id from alarm_temp where ip='%s' and db_type='%s' and alarm_item='%s' and alarm_type='mail' ;" %(server,db_type,alarm_item)) else: alarm_count=curs.execute("select id from alarm_temp where server_id=%s and db_type='%s' and alarm_item='%s' and alarm_type='mail' ;" %(server,db_type,alarm_item)) if int(alarm_count) >= int(send_mail_max_count) : send_mail = 0 else: send_mail = send_mail curs.close() conn.close() return send_mail def update_send_sms_status(server,db_type,alarm_item,send_sms,send_sms_max_count): conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8') conn.select_db(dbname) curs = conn.cursor() if db_type == "os": alarm_count=curs.execute("select id from alarm_temp where ip='%s' and db_type='%s' and alarm_item='%s' and alarm_type='sms' ;" %(server,db_type,alarm_item)) else: alarm_count=curs.execute("select id from alarm_temp where server_id=%s and db_type='%s' and alarm_item='%s' and alarm_type='sms' ;" %(server,db_type,alarm_item)) if int(alarm_count) >= int(send_sms_max_count) : send_sms = 0 else: send_sms = send_sms curs.close() conn.close() return send_sms def check_db_status(server_id,db_host,db_port,tags,db_type): try: conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8') conn.select_db(dbname) curs = conn.cursor() sql="select id from db_status where host='%s' and port=%s " % (db_host, db_port) count=curs.execute(sql) if count ==0: if db_type=='mysql': sort=1 elif db_type=='oracle': sort=2 elif db_type=='mongodb': sort=3 elif db_type=='redis': sort=4 else: sort=0 sql="replace into db_status(server_id,host,port,tags,db_type,db_type_sort) values(%s,%s,%s,%s,%s,%s);" param=(server_id,db_host,str(db_port),tags,db_type,str(sort)) curs.execute(sql,param) conn.commit() except Exception,e: print "Check db status table: " + str(e) finally: curs.close() conn.close() def update_db_status_init(server_id,role,version,db_host,db_port,tags): try: conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8') conn.select_db(dbname) curs = conn.cursor() #sql="replace into db_status(server_id,host,port,tags,version,role,connect) values(%s,%s,%s,%s,%s,%s,%s)" #param=(server_id,host,port,tags,version,role,0) #curs.execute(sql,param) curs.execute("update db_status set role='%s',version='%s',tags='%s' where host='%s' and port='%s';" %(role,version,tags,db_host,db_port)) conn.commit() except Exception, e: print "update db status init: " + str(e) finally: curs.close() conn.close() def update_db_status_more(vals, db_host,db_port=''): try: setCols = [] for val in vals: field = val[0] value = val[1] field_tips=field+'_tips' if not cmp("-1",value): value_tips='no data' else: (alarm_time,alarm_item,alarm_value,alarm_level) = val[2:] value_tips=""" item: %s\n<br/> value: %s\n<br/> level: %s\n<br/> time: %s\n<br/> """ %(alarm_item,alarm_value,alarm_level,alarm_time) setCols.append("%s='%s'" % (field, value)) setCols.append("%s='%s'" % (field_tips, value_tips)) if cmp('', db_port) and int(db_port) >0: updSql = "update db_status set %s where host='%s' and port='%s';" %(",".join(setCols),db_host,db_port) else: updSql = "update db_status set %s where host='%s';" %(",".join(setCols),db_host) conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8') conn.select_db(dbname) curs = conn.cursor() curs.execute(updSql) conn.commit() except Exception, e: print "update db status more: " + str(e) print db_host,db_port, vals finally: curs.close() conn.close() def update_db_status(field,value,db_host,db_port,alarm_time,alarm_item,alarm_value,alarm_level): try: field_tips=field+'_tips' if value==-1: value_tips='no data' else: value_tips=""" item: %s\n<br/> value: %s\n<br/> level: %s\n<br/> time: %s\n<br/> """ %(alarm_item,alarm_value,alarm_level,alarm_time) conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8') conn.select_db(dbname) curs = conn.cursor() if cmp('', db_port) and int(db_port) >0: curs.execute("update db_status set %s='%s',%s='%s' where host='%s' and port='%s';" %(field,value,field_tips,value_tips,db_host,db_port)) else: curs.execute("update db_status set %s='%s',%s='%s' where host='%s';" %(field,value,field_tips,value_tips,db_host)) conn.commit() except Exception, e: print "update db status: " + str(e) print field,value,db_host,db_port,alarm_time,alarm_item,alarm_value,alarm_level finally: curs.close() conn.close() def update_check_time(): try: conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8') conn.select_db(dbname) curs = conn.cursor() localtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) curs.execute("update lepus_status set lepus_value='%s' where lepus_variables='lepus_checktime';" %(localtime)) conn.commit() except Exception, e: print "update check time: " + str(e) finally: curs.close() conn.close() def flush_hosts(): conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8') conn.select_db(dbname) cursor = conn.cursor() cursor.execute('flush hosts;'); def get_mysql_status(cursor): data=cursor.execute('show global status;'); data_list=cursor.fetchall() data_dict={} for item in data_list: data_dict[item[0]] = item[1] return data_dict def get_mysql_variables(cursor): data=cursor.execute('show global variables;'); data_list=cursor.fetchall() data_dict={} for item in data_list: data_dict[item[0]] = item[1] return data_dict def get_mysql_version(cursor): cursor.execute('select version();'); return cursor.fetchone()[0] ##################################### mail ############################################## mail_host = get_option('smtp_host') mail_port = int(get_option('smtp_port')) mail_user = get_option('smtp_user') mail_pass = get_option('smtp_pass') mail_send_from = get_option('mailfrom') def send_mail(to_list,sub,content): ''' to_list:发给谁 sub:主题 content:内容 send_mail("[email protected]","sub","content") ''' #me=mail_user+"<</span>"+mail_user+"@"+mail_postfix+">" me=mail_send_from msg = MIMEText(content, _subtype='html', _charset='utf8') msg['Subject'] = "Camelbell %s" % (Header(sub,'utf8')) msg['From'] = Header(me,'utf8') msg['To'] = ";".join(to_list) try: smtp = smtplib.SMTP() smtp.connect(mail_host,mail_port) smtp.login(mail_user,mail_pass) smtp.sendmail(me,to_list, msg.as_string()) smtp.close() return True except Exception, e: print str(e) return False ##################################### db_server_os ############################################## def init_server_os(): try: conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8') conn.select_db(dbname) cursor = conn.cursor() #print "disable os monitor" cursor.execute("update db_servers_os set monitor = 0") conn.commit() # insert/update dbs = ["mysql", "oracle", "mongodb", "redis"] for db in dbs: #print "insert/update %s" % (db) insSql = "insert into db_servers_os (host, tags, monitor) " \ + " SELECT HOST,TAGS,max(monitor_os) as dm from db_servers_%s d group by host " % (db) \ + " ON DUPLICATE KEY UPDATE monitor=IF(monitor=0, VALUES(monitor), monitor)" cursor.execute(insSql) conn.commit() except Exception,e: print "Fail init_server_os: %s" %(e) return False finally: cursor.close() conn.close() return True ##################################### salt ##############################################<|fim▁hole|>def doSaltCmd(saltCmd): #print saltCmd retry = 3 for i in range(0, retry): cmdRes = os.popen(saltCmd).read() if re.search('^No minions matched the target', cmdRes): print "No minions matched the target try %s" % (i+1) continue else: return cmdRes.rstrip("\n") return None def exeSaltCmd(ip, cmd): sCmd = '''salt --async '%s' cmd.run "%s" ''' % (ip, cmd.replace('"','\\"').replace('$','\\$')) # Executed command with job ID: 20160331112308102201 sRes = doSaltCmd(sCmd) if sRes != None: sVals = sRes.split() jobID = sVals[len(sVals)-1] time.sleep(3) retry = 3 for i in range(0, retry): sJobCmd = '''salt-run --out='json' jobs.lookup_jid %s ''' % (jobID) jobRes = doSaltCmd(sJobCmd) #print cmdRes if re.search('^No minions matched the target', jobRes): continue else: saltRes = json.loads(jobRes).get(ip) if re.search('^Minion did not return', str(saltRes)): continue else: return saltRes return None def exeSaltAsyncCmd(ip, cmd): sCmd = '''salt --async '%s' cmd.run "%s" ''' % (ip, cmd.replace('"','\\"').replace('$','\\$')) # Executed command with job ID: 20160331112308102201 sRes = doSaltCmd(sCmd) if sRes != None and cmp('', sRes) and re.search("^Executed", sRes): sVals = sRes.split() jobID = sVals[len(sVals)-1] return jobID #print sCmd, sRes return None def getSaltJobByID(ip, jobID): retry = 3 for i in range(0, retry): sJobCmd = '''salt-run --out='json' jobs.lookup_jid %s ''' % (jobID) jobRes = doSaltCmd(sJobCmd) #print cmdRes if re.search('^No minions matched the target', jobRes): print "No minions matched the target try %s" % (i+1) continue else: saltRes = json.loads(jobRes).get(ip) if re.search('^Minion did not return', str(saltRes)): print "Minion did not return try %s" % (i+1) continue else: return saltRes return None def checkSaltKey(ip): if exeSaltCmd(ip, "hostname") != None: return True else: return False def encode(str): return crypt.sub_encrypt(str) def decode(str): return crypt.sub_decrypt(str)<|fim▁end|>
<|file_name|>document_rule.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/. */ //! [@document rules](https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document) //! initially in CSS Conditional Rules Module Level 3, @document has been postponed to the level 4. //! We implement the prefixed `@-moz-document`. use cssparser::{Parser, Token, SourceLocation, BasicParseError}; use media_queries::Device; use parser::{Parse, ParserContext}; use shared_lock::{DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard}; use std::fmt; use style_traits::{ToCss, ParseError, StyleParseError}; use stylearc::Arc; use stylesheets::CssRules; use values::specified::url::SpecifiedUrl; #[derive(Debug)] /// A @-moz-document rule pub struct DocumentRule { /// The parsed condition pub condition: DocumentCondition, /// Child rules pub rules: Arc<Locked<CssRules>>, /// The line and column of the rule's source code. pub source_location: SourceLocation, } impl ToCssWithGuard for DocumentRule { fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(dest.write_str("@-moz-document ")); try!(self.condition.to_css(dest)); try!(dest.write_str(" {")); for rule in self.rules.read_with(guard).0.iter() { try!(dest.write_str(" ")); try!(rule.to_css(guard, dest)); } dest.write_str(" }") } } impl DeepCloneWithLock for DocumentRule { /// Deep clones this DocumentRule. fn deep_clone_with_lock( &self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard, ) -> Self { let rules = self.rules.read_with(guard); DocumentRule { condition: self.condition.clone(), rules: Arc::new(lock.wrap(rules.deep_clone_with_lock(lock, guard))), source_location: self.source_location.clone(),<|fim▁hole|> /// A URL matching function for a `@document` rule's condition. #[derive(Clone, Debug)] pub enum UrlMatchingFunction { /// Exact URL matching function. It evaluates to true whenever the /// URL of the document being styled is exactly the URL given. Url(SpecifiedUrl), /// URL prefix matching function. It evaluates to true whenever the /// URL of the document being styled has the argument to the /// function as an initial substring (which is true when the two /// strings are equal). When the argument is the empty string, /// it evaluates to true for all documents. UrlPrefix(String), /// Domain matching function. It evaluates to true whenever the URL /// of the document being styled has a host subcomponent and that /// host subcomponent is exactly the argument to the ‘domain()’ /// function or a final substring of the host component is a /// period (U+002E) immediately followed by the argument to the /// ‘domain()’ function. Domain(String), /// Regular expression matching function. It evaluates to true /// whenever the regular expression matches the entirety of the URL /// of the document being styled. RegExp(String), } macro_rules! parse_quoted_or_unquoted_string { ($input:ident, $url_matching_function:expr) => { $input.parse_nested_block(|input| { let start = input.position(); input.parse_entirely(|input| { match input.next() { Ok(Token::QuotedString(value)) => Ok($url_matching_function(value.into_owned())), Ok(t) => Err(BasicParseError::UnexpectedToken(t).into()), Err(e) => Err(e.into()), } }).or_else(|_: ParseError| { while let Ok(_) = input.next() {} Ok($url_matching_function(input.slice_from(start).to_string())) }) }) } } impl UrlMatchingFunction { /// Parse a URL matching function for a`@document` rule's condition. pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<UrlMatchingFunction, ParseError<'i>> { if input.try(|input| input.expect_function_matching("url-prefix")).is_ok() { parse_quoted_or_unquoted_string!(input, UrlMatchingFunction::UrlPrefix) } else if input.try(|input| input.expect_function_matching("domain")).is_ok() { parse_quoted_or_unquoted_string!(input, UrlMatchingFunction::Domain) } else if input.try(|input| input.expect_function_matching("regexp")).is_ok() { input.parse_nested_block(|input| { Ok(UrlMatchingFunction::RegExp(input.expect_string()?.into_owned())) }) } else if let Ok(url) = input.try(|input| SpecifiedUrl::parse(context, input)) { Ok(UrlMatchingFunction::Url(url)) } else { Err(StyleParseError::UnspecifiedError.into()) } } #[cfg(feature = "gecko")] /// Evaluate a URL matching function. pub fn evaluate(&self, device: &Device) -> bool { use gecko_bindings::bindings::Gecko_DocumentRule_UseForPresentation; use gecko_bindings::structs::URLMatchingFunction as GeckoUrlMatchingFunction; use nsstring::nsCString; let func = match *self { UrlMatchingFunction::Url(_) => GeckoUrlMatchingFunction::eURL, UrlMatchingFunction::UrlPrefix(_) => GeckoUrlMatchingFunction::eURLPrefix, UrlMatchingFunction::Domain(_) => GeckoUrlMatchingFunction::eDomain, UrlMatchingFunction::RegExp(_) => GeckoUrlMatchingFunction::eRegExp, }; let pattern = nsCString::from(match *self { UrlMatchingFunction::Url(ref url) => url.as_str(), UrlMatchingFunction::UrlPrefix(ref pat) | UrlMatchingFunction::Domain(ref pat) | UrlMatchingFunction::RegExp(ref pat) => pat, }); unsafe { Gecko_DocumentRule_UseForPresentation(&*device.pres_context, &*pattern, func) } } #[cfg(not(feature = "gecko"))] /// Evaluate a URL matching function. pub fn evaluate(&self, _: &Device) -> bool { false } } impl ToCss for UrlMatchingFunction { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { UrlMatchingFunction::Url(ref url) => { url.to_css(dest) }, UrlMatchingFunction::UrlPrefix(ref url_prefix) => { dest.write_str("url-prefix(")?; url_prefix.to_css(dest)?; dest.write_str(")") }, UrlMatchingFunction::Domain(ref domain) => { dest.write_str("domain(")?; domain.to_css(dest)?; dest.write_str(")") }, UrlMatchingFunction::RegExp(ref regex) => { dest.write_str("regexp(")?; regex.to_css(dest)?; dest.write_str(")") }, } } } /// A `@document` rule's condition. /// /// https://www.w3.org/TR/2012/WD-css3-conditional-20120911/#at-document /// /// The `@document` rule's condition is written as a comma-separated list of /// URL matching functions, and the condition evaluates to true whenever any /// one of those functions evaluates to true. #[derive(Clone, Debug)] pub struct DocumentCondition(Vec<UrlMatchingFunction>); impl DocumentCondition { /// Parse a document condition. pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { input.parse_comma_separated(|input| UrlMatchingFunction::parse(context, input)) .map(DocumentCondition) } /// Evaluate a document condition. pub fn evaluate(&self, device: &Device) -> bool { self.0.iter().any(|ref url_matching_function| url_matching_function.evaluate(device) ) } } impl ToCss for DocumentCondition { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.0.iter(); let first = iter.next() .expect("Empty DocumentCondition, should contain at least one URL matching function"); first.to_css(dest)?; for url_matching_function in iter { dest.write_str(", ")?; url_matching_function.to_css(dest)?; } Ok(()) } }<|fim▁end|>
} } }
<|file_name|>tract2council.py<|end_file_name|><|fim▁begin|>import sys, os, json, time from shapely.geometry import Polygon # http://toblerity.org/shapely/manual.html contains = {} intersects = {} dPoly = {} unmatched = [] TRACTCOL = 'BoroCT2010' # rename this for 2000 census def addPoly(coords): polys = [] if (isinstance(coords[0][0], float)): polys.append(Polygon(coords)) else: for (c) in coords: polys.extend(addPoly(c))<|fim▁hole|> return polys def inDistrict(tract): tPoly = addPoly(tract['geometry']['coordinates']) tractNum = tract['properties'][TRACTCOL] intersects = set() area = 0 intersection = {} iap = {} for (i) in range (0, len(tPoly)): tractPolygon = tPoly[i] area += tractPolygon.area for (dn, dp) in dPoly.items(): for (p) in dp: if (p.contains(tractPolygon)): iap[dn] = 1 break; elif (p.intersects(tractPolygon)): intersects.add(dn) if dn not in intersection: intersection[dn] = p.intersection(tractPolygon).area else: intersection[dn] += p.intersection(tractPolygon).area if (len(intersection) > 0): for (dn, inter) in intersection.items(): iap[dn] = inter / area return (tractNum, iap) if __name__ == '__main__': if (len(sys.argv) < 2): print ("Usage: tract2council.py tract.json council.json") exit() tractfile = sys.argv[1] councilfile = sys.argv[2] for (f) in (tractfile, councilfile): if (not os.path.isfile(f)): print ("File " + f + " is not readable") exit() try: with open(tractfile) as tractfo: tractData = json.load(tractfo) except Exception: print ("Unable to read tract file " + tractfile) exit() try: with open(councilfile) as councilfo: councilData = json.load(councilfo) except Exception as e: print ("Unable to read council file " + councilfile+": {0}".format(e)) exit() for (district) in councilData['features']: dn = district['properties']['CounDist'] c = district['geometry']['coordinates'] dPoly[dn] = addPoly(c) print ("there are " + str(len(tractData['features'])) + " census tracts") for (tract) in tractData['features']: (tn, i) = inDistrict(tract) intersects[tn] = i intersectsFile = 'tracts_' + str(round(time.time())) + '.json' with open(intersectsFile, 'w') as intersectsfo: json.dump(intersects, intersectsfo)<|fim▁end|>
<|file_name|>semver.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Semver parsing and logic use core::char; use core::cmp; use core::io::{ReaderUtil}; use core::io; use core::option::{Option, Some, None}; use core::str; use core::to_str::ToStr; use core::uint; #[deriving(Eq)] pub enum Identifier { Numeric(uint), AlphaNumeric(~str) } impl cmp::Ord for Identifier { #[inline(always)] fn lt(&self, other: &Identifier) -> bool { match (self, other) { (&Numeric(a), &Numeric(b)) => a < b, (&Numeric(_), _) => true, (&AlphaNumeric(ref a), &AlphaNumeric(ref b)) => *a < *b, (&AlphaNumeric(_), _) => false } } #[inline(always)] fn le(&self, other: &Identifier) -> bool { ! (other < self) } #[inline(always)] fn gt(&self, other: &Identifier) -> bool { other < self } #[inline(always)] fn ge(&self, other: &Identifier) -> bool { ! (self < other) } } impl ToStr for Identifier { #[inline(always)] fn to_str(&self) -> ~str { match self { &Numeric(n) => n.to_str(), &AlphaNumeric(ref s) => s.to_str() } } } #[deriving(Eq)] pub struct Version { major: uint, minor: uint, patch: uint, pre: ~[Identifier], build: ~[Identifier], } impl ToStr for Version { #[inline(always)] fn to_str(&self) -> ~str { let s = fmt!("%u.%u.%u", self.major, self.minor, self.patch); let s = if self.pre.is_empty() { s } else { s + "-" + str::connect(self.pre.map(|i| i.to_str()), ".") }; if self.build.is_empty() { s } else { s + "+" + str::connect(self.build.map(|i| i.to_str()), ".") } } } impl cmp::Ord for Version { #[inline(always)] fn lt(&self, other: &Version) -> bool { self.major < other.major || (self.major == other.major && self.minor < other.minor) || (self.major == other.major && self.minor == other.minor && self.patch < other.patch) || (self.major == other.major && self.minor == other.minor && self.patch == other.patch && // NB: semver spec says 0.0.0-pre < 0.0.0 // but the version of ord defined for vec // says that [] < [pre], so we alter it // here. (match (self.pre.len(), other.pre.len()) { (0, 0) => false, (0, _) => false, (_, 0) => true, (_, _) => self.pre < other.pre })) || (self.major == other.major && self.minor == other.minor && self.patch == other.patch && self.pre == other.pre && self.build < other.build) } #[inline(always)] fn le(&self, other: &Version) -> bool { ! (other < self) } #[inline(always)] fn gt(&self, other: &Version) -> bool { other < self } #[inline(always)] fn ge(&self, other: &Version) -> bool { ! (self < other) } } condition! { bad_parse: () -> (); } fn take_nonempty_prefix(rdr: @io::Reader, ch: char, pred: &fn(char) -> bool) -> (~str, char) { let mut buf = ~""; let mut ch = ch; while pred(ch) { str::push_char(&mut buf, ch); ch = rdr.read_char(); } if buf.is_empty() { bad_parse::cond.raise(()) } debug!("extracted nonempty prefix: %s", buf); (buf, ch) } fn take_num(rdr: @io::Reader, ch: char) -> (uint, char) { let (s, ch) = take_nonempty_prefix(rdr, ch, char::is_digit); match uint::from_str(s) { None => { bad_parse::cond.raise(()); (0, ch) }, Some(i) => (i, ch) } } fn take_ident(rdr: @io::Reader, ch: char) -> (Identifier, char) { let (s,ch) = take_nonempty_prefix(rdr, ch, char::is_alphanumeric); if s.all(char::is_digit) { match uint::from_str(s) { None => { bad_parse::cond.raise(()); (Numeric(0), ch) }, Some(i) => (Numeric(i), ch) } } else { (AlphaNumeric(s), ch) } } fn expect(ch: char, c: char) { if ch != c { bad_parse::cond.raise(()) } } fn parse_reader(rdr: @io::Reader) -> Version { let (major, ch) = take_num(rdr, rdr.read_char()); expect(ch, '.'); let (minor, ch) = take_num(rdr, rdr.read_char()); expect(ch, '.'); let (patch, ch) = take_num(rdr, rdr.read_char()); let mut pre = ~[]; let mut build = ~[]; let mut ch = ch; if ch == '-' { loop { let (id, c) = take_ident(rdr, rdr.read_char()); pre.push(id); ch = c; if ch != '.' { break; } } } if ch == '+' { loop { let (id, c) = take_ident(rdr, rdr.read_char()); build.push(id); ch = c; if ch != '.' { break; } } } Version { major: major, minor: minor, patch: patch, pre: pre, build: build, } } pub fn parse(s: &str) -> Option<Version> { if !s.is_ascii() { return None; } let s = s.trim(); let mut bad = false; do bad_parse::cond.trap(|_| { debug!("bad"); bad = true }).in { do io::with_str_reader(s) |rdr| { let v = parse_reader(rdr); if bad || v.to_str() != s.to_owned() { None } else { Some(v) } } } } #[test] fn test_parse() { assert!(parse("") == None); assert!(parse(" ") == None); assert!(parse("1") == None); assert!(parse("1.2") == None); assert!(parse("1.2") == None); assert!(parse("1") == None); assert!(parse("1.2") == None); assert!(parse("1.2.3-") == None); assert!(parse("a.b.c") == None); assert!(parse("1.2.3 abc") == None); assert!(parse("1.2.3") == Some(Version { major: 1u, minor: 2u, patch: 3u, pre: ~[], build: ~[], })); assert!(parse(" 1.2.3 ") == Some(Version { major: 1u, minor: 2u, patch: 3u, pre: ~[], build: ~[], })); assert!(parse("1.2.3-alpha1") == Some(Version { major: 1u, minor: 2u, patch: 3u, pre: ~[AlphaNumeric(~"alpha1")], build: ~[] })); assert!(parse(" 1.2.3-alpha1 ") == Some(Version { major: 1u, minor: 2u, patch: 3u, pre: ~[AlphaNumeric(~"alpha1")], build: ~[] })); assert!(parse("1.2.3+build5") == Some(Version { major: 1u, minor: 2u, patch: 3u, pre: ~[], build: ~[AlphaNumeric(~"build5")] })); assert!(parse(" 1.2.3+build5 ") == Some(Version { major: 1u, minor: 2u, patch: 3u, pre: ~[],<|fim▁hole|> })); assert!(parse("1.2.3-alpha1+build5") == Some(Version { major: 1u, minor: 2u, patch: 3u, pre: ~[AlphaNumeric(~"alpha1")], build: ~[AlphaNumeric(~"build5")] })); assert!(parse(" 1.2.3-alpha1+build5 ") == Some(Version { major: 1u, minor: 2u, patch: 3u, pre: ~[AlphaNumeric(~"alpha1")], build: ~[AlphaNumeric(~"build5")] })); assert!(parse("1.2.3-1.alpha1.9+build5.7.3aedf ") == Some(Version { major: 1u, minor: 2u, patch: 3u, pre: ~[Numeric(1),AlphaNumeric(~"alpha1"),Numeric(9)], build: ~[AlphaNumeric(~"build5"), Numeric(7), AlphaNumeric(~"3aedf")] })); } #[test] fn test_eq() { assert!(parse("1.2.3") == parse("1.2.3")); assert!(parse("1.2.3-alpha1") == parse("1.2.3-alpha1")); } #[test] fn test_ne() { assert!(parse("0.0.0") != parse("0.0.1")); assert!(parse("0.0.0") != parse("0.1.0")); assert!(parse("0.0.0") != parse("1.0.0")); assert!(parse("1.2.3-alpha") != parse("1.2.3-beta")); } #[test] fn test_lt() { assert!(parse("0.0.0") < parse("1.2.3-alpha2")); assert!(parse("1.0.0") < parse("1.2.3-alpha2")); assert!(parse("1.2.0") < parse("1.2.3-alpha2")); assert!(parse("1.2.3-alpha1") < parse("1.2.3")); assert!(parse("1.2.3-alpha1") < parse("1.2.3-alpha2")); assert!(!(parse("1.2.3-alpha2") < parse("1.2.3-alpha2"))); } #[test] fn test_le() { assert!(parse("0.0.0") <= parse("1.2.3-alpha2")); assert!(parse("1.0.0") <= parse("1.2.3-alpha2")); assert!(parse("1.2.0") <= parse("1.2.3-alpha2")); assert!(parse("1.2.3-alpha1") <= parse("1.2.3-alpha2")); assert!(parse("1.2.3-alpha2") <= parse("1.2.3-alpha2")); } #[test] fn test_gt() { assert!(parse("1.2.3-alpha2") > parse("0.0.0")); assert!(parse("1.2.3-alpha2") > parse("1.0.0")); assert!(parse("1.2.3-alpha2") > parse("1.2.0")); assert!(parse("1.2.3-alpha2") > parse("1.2.3-alpha1")); assert!(parse("1.2.3") > parse("1.2.3-alpha2")); assert!(!(parse("1.2.3-alpha2") > parse("1.2.3-alpha2"))); } #[test] fn test_ge() { assert!(parse("1.2.3-alpha2") >= parse("0.0.0")); assert!(parse("1.2.3-alpha2") >= parse("1.0.0")); assert!(parse("1.2.3-alpha2") >= parse("1.2.0")); assert!(parse("1.2.3-alpha2") >= parse("1.2.3-alpha1")); assert!(parse("1.2.3-alpha2") >= parse("1.2.3-alpha2")); } #[test] fn test_spec_order() { let vs = ["1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-beta.2", "1.0.0-beta.11", "1.0.0-rc.1", "1.0.0-rc.1+build.1", "1.0.0", "1.0.0+0.3.7", "1.3.7+build", "1.3.7+build.2.b8f12d7", "1.3.7+build.11.e0f985a"]; let mut i = 1; while i < vs.len() { let a = parse(vs[i-1]).get(); let b = parse(vs[i]).get(); assert!(a < b); i += 1; } }<|fim▁end|>
build: ~[AlphaNumeric(~"build5")]
<|file_name|>l2_bell_burst_mod.py<|end_file_name|><|fim▁begin|># Copyright 2011 James McCauley # # This file is part of POX. # # POX 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. # # POX 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 POX. If not, see <http://www.gnu.org/licenses/>. """ An L2 learning switch. It is derived from one written live for an SDN crash course. It is somwhat similar to NOX's pyswitch in that it installs<|fim▁hole|>exact-match rules for each flow. """ from __future__ import division from random import randrange from pox.core import core import pox.openflow.libopenflow_01 as of from pox.lib.util import dpid_to_str from pox.lib.util import str_to_bool import sys, os, commands, time from pox.lib.util import dpidToStr log = core.getLogger() #-------------------------------define flow rate---------- flow_rate = 50 interval = 1/flow_rate print 'current flow modification rate is:', flow_rate global burst burst = {} # We don't want to flood immediately when a switch connects. # Can be overriden on commandline. _flood_delay = 0 class LearningSwitch (object): """ The learning switch "brain" associated with a single OpenFlow switch. When we see a packet, we'd like to output it on a port which will eventually lead to the destination. To accomplish this, we build a table that maps addresses to ports. We populate the table by observing traffic. When we see a packet from some source coming from some port, we know that source is out that port. When we want to forward traffic, we look up the desintation in our table. If we don't know the port, we simply send the message out all ports except the one it came in on. (In the presence of loops, this is bad!). In short, our algorithm looks like this: For each packet from the switch: 1) Use source address and switch port to update address/port table 2) Is transparent = False and either Ethertype is LLDP or the packet's destination address is a Bridge Filtered address? Yes: 2a) Drop packet -- don't forward link-local traffic (LLDP, 802.1x) DONE 3) Is destination multicast? Yes: 3a) Flood the packet DONE 4) Port for destination address in our address/port table? No: 4a) Flood the packet DONE 5) Is output port the same as input port? Yes: 5a) Drop packet and similar ones for a while 6) Install flow table entry in the switch so that this flow goes out the appopriate port 6a) Send the packet out appropriate port """ def __init__ (self, connection, transparent): # Switch we'll be adding L2 learning switch capabilities to self.connection = connection self.transparent = transparent # Our table self.macToPort = {} # We want to hear PacketIn messages, so we listen # to the connection connection.addListeners(self) # We just use this to know when to log a helpful message self.hold_down_expired = _flood_delay == 0 #----------------------- msg = of.ofp_flow_mod(command=of.OFPFC_DELETE) # iterate over all connected switches and delete all their flows connection.send(msg) print "INFO: Clearing all flows..." #for BCM switch only msg = of.ofp_flow_mod() msg.priority = 10 msg.match.dl_type = 0x800 #msg.match.in_port = 5 msg.match.nw_src = '10.0.0.1' msg.idle_timeout = 0 msg.hard_timeout = 0 #msg.actions.append(of.ofp_action_output(port = 1)) self.connection.send(msg) print 'INFO: add a default rule... I am slice 1(BCM only)' for k in xrange(1,65):#the number of rules to install #insert first if k % 2 == 0: msg = of.ofp_flow_mod() #msg.match = of.ofp_match.from_packet(packet, event.port) #msg.priority = 20000 + randrange(1000) msg.priority = 2000 msg.match.dl_type = 0x800 i = int(k / 256) + 56 j = k % 256 dst = '192.168.' + str(i) + '.' + str(j) #msg.match.in_port = 1 msg.match.nw_src = '10.0.0.1' msg.match.nw_dst = dst #print 'INFO',dst, time.time() msg.idle_timeout = 0 msg.hard_timeout = 0 msg.actions.append(of.ofp_action_output(port = 2)) #msg.data = event.ofp # 6a self.connection.send(msg) time.sleep(0.02) #------------------------- # (note that flow_mods match all flows by default) os.system('./simplesniffer eth2 64&') os.system('sudo bash ../pktgen/pktgen.conf.1-1-flow-dist.sh &') time.sleep(5) y = 0 print 'INFO: starting sending flow mod...' for k in xrange(1,65):#the number of rules to install #insert firsti msg = of.ofp_flow_mod() if k % 2 == 0: msg.command = of.OFPFC_MODIFY #msg.match = of.ofp_match.from_packet(packet, event.port) #msg.priority = 20000 + randrange(1000) msg.priority = 2000 msg.match.dl_type = 0x800 i = int(k / 256) + 56 j = k % 256 dst = '192.168.' + str(i) + '.' + str(j) #msg.match.in_port = 1 msg.match.nw_src = '10.0.0.1' msg.match.nw_dst = dst #print 'INFO',dst, time.time() msg.idle_timeout = 0 msg.hard_timeout = 0 msg.actions.append(of.ofp_action_output(port = 5)) #msg.data = event.ofp # 6a self.connection.send(msg) #print 'DATA: 10.0.0.1', dst, '%f' %time.time() #print 'DATA: 10.0.0.1', dst, '%f' %time.time() burst[dst] = time.time() #time.sleep(interval) print 'INFO: flow mod measure finished...' #write file w = open('poxout1','w') for d in burst: w.write('src: 10.0.0.1 dst: %s sec: %f usec: %f\n' %(d, int(burst[d]), (burst[d] - int(burst[d])) * 1000000 )) w.close() os.system('sudo bash cleanpox.sh') #self destrory def _handle_PacketIn (self, event): """ Handle packet in messages from the switch to implement above algorithm. """ packet = event.parsed #print 'PACKET_IN:', event.port, packet.next.dstip,'%f' % time.time() def _handle_flowstats_received (event): stats = flow_stats_to_list(event.stats) print "FlowStatsReceived from %s: %s" % (dpidToStr(event.connection.dpid), stats) class l2_learning (object): """ Waits for OpenFlow switches to connect and makes them learning switches. """ def __init__ (self, transparent): core.openflow.addListeners(self) self.transparent = transparent def _handle_ConnectionUp (self, event): log.debug("Connection %s" % (event.connection,)) LearningSwitch(event.connection, self.transparent) def launch (transparent=False, hold_down=_flood_delay): """ Starts an L2 learning switch. """ try: global _flood_delay _flood_delay = int(str(hold_down), 10) assert _flood_delay >= 0 except: raise RuntimeError("Expected hold-down to be a number") core.registerNew(l2_learning, str_to_bool(transparent))<|fim▁end|>
<|file_name|>VLog.java<|end_file_name|><|fim▁begin|>/* This file is part of VoltDB. * Copyright (C) 2008-2017 VoltDB Inc. * * This program 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb; import java.io.File; /** * This file isn't long for this world. It's just something I've been using * to debug multi-process rejoin stuff. * */ public class VLog { static File m_logfile = new File("vlog.txt"); public synchronized static void setPortNo(int portNo) { m_logfile = new File(String.format("vlog-%d.txt", portNo)); } public synchronized static void log(String str) {<|fim▁hole|> FileWriter log = new FileWriter(m_logfile, true); log.write(str + "\n"); log.flush(); log.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } public static void log(String format, Object... args) { log(String.format(format, args)); } }<|fim▁end|>
// turn off this stupid thing for now /*try {
<|file_name|>buffer-koans.js<|end_file_name|><|fim▁begin|>var events = require('events'), koanize = require('koanizer'), util = require('util'); koanize(this); // Standard and RFC set these values var REFERENCE_CLOCK_FREQUENCY = 90000; // RTP packet constants and masks var RTP_HEADER_SIZE = 12; var RTP_FRAGMENTATION_HEADER_SIZE = 4; var SAMPLES_PER_FRAME = 1152; // ISO 11172-3 var SAMPLING_FREQUENCY = 44100; var TIMESTAMP_DELTA = Math.floor(SAMPLES_PER_FRAME * REFERENCE_CLOCK_FREQUENCY / SAMPLING_FREQUENCY); var SECONDS_PER_FRAME = SAMPLES_PER_FRAME / SAMPLING_FREQUENCY; var RTPProtocol = function(){ events.EventEmitter.call(this); this.setMarker = false; this.ssrc = Math.floor(Math.random() * 100000); this.seqNum = Math.floor(Math.random() * 1000); this.timestamp = Math.floor(Math.random() * 1000); }; util.inherits(RTPProtocol, events.EventEmitter); RTPProtocol.prototype.pack = function(payload){ ++this.seqNum; // RFC3550 says it must increase by the number of samples // sent in a block in case of CBR audio streaming this.timestamp += TIMESTAMP_DELTA; if (!payload) { // Tried to send a packet, but packet was not ready. // Timestamp and Sequence Number should be increased // anyway 'cause interval callback was called and // that's like sending silence this.setMarker = true; return; <|fim▁hole|> var RTPPacket = new Buffer(RTP_HEADER_SIZE + RTP_FRAGMENTATION_HEADER_SIZE + payload.length); // version = 2: 10 // padding = 0: 0 // extension = 0: 0 // CRSCCount = 0: 0000 /* KOAN #1 should write Version, Padding, Extension and Count */ RTPPacket.writeUInt8(128, 0); // Marker = 0: 0 // RFC 1890: RTP Profile for Audio and Video Conferences with Minimal Control // Payload = 14: (MPEG Audio Only) 0001110 RTPPacket.writeUInt8(this.setMarker? 142 : 14, 1); this.setMarker = false; // SequenceNumber /* KOAN #2 should write Sequence Number */ RTPPacket.writeUInt16BE(this.seqNum, 2); // Timestamp /* KOAN #3 should write Timestamp... */ RTPPacket.writeUInt32BE(this.timestamp, 4); // SSRC /* KOAN #3 ...SSRC and... */ RTPPacket.writeUInt32BE(this.ssrc, 8); // RFC 2250: RTP Payload Format for MPEG1/MPEG2 Video // 3.5 MPEG Audio-specific header /* KOAN #3 ...payload Format */ RTPPacket.writeUInt32BE(0, 12); payload.copy(RTPPacket, 16); this.emit('packet', RTPPacket); //return RTPPacket; }; module.exports = exports.RTPProtocol = RTPProtocol;<|fim▁end|>
}
<|file_name|>wl.py<|end_file_name|><|fim▁begin|>import pyautogui, win32api, win32con, ctypes, autoit from PIL import ImageOps, Image, ImageGrab from numpy import * import os import time import cv2 import random from Bot import * def main(): bot = Bot() autoit.win_wait(bot.title, 5) counter = 0 poitonUse = 0 cycle = True fullCounter = 0 while cycle: hpstatus = bot.checkOwnHp() print 'hp ' + str(hpstatus) if hpstatus == 0: autoit.control_send(bot.title, '', '{F9}', 0) bot.sleep(0.3,0.6) print 'Dead' cv2.imwrite('Dead' + str(int(time.time())) + '.png',bot.getScreen(leftCornerx,leftCornery,x2,fullY2)) cycle = False if hpstatus == 1: if poitonUse == 0: autoit.control_send(bot.title, '', '{F10}', 0) poitonUse += 1 if poitonUse > 5: poitonUse = 0 else: poitonUse = 0 res = bot.findHP(); print 'tgs ' + str(res) if res == 3: fullCounter += 1 print 'fc ' + str(fullCounter) autoit.control_send(bot.title, '', '{F1}', 0) else: fullCounter = 0 if fullCounter > 4: autoit.control_send(bot.title, '', '{ESC}', 0) bot.sleep(0.3,0.6) autoit.control_send(bot.title, '', '{F3}', 0) bot.sleep(0.1,0.3)<|fim▁hole|> autoit.control_send(bot.title, '', '{F1}', 0) # bot.mouseRotate() fullCounter = 0 if res > 0: autoit.control_send(bot.title, '', '{F1}', 0) counter = 0 if res == 1 or res == 3: bot.sleep(0.3,0.6) if res > 1 and res < 3: bot.sleep(1,3) if res == 1: autoit.control_send(bot.title, '', '{F3}', 0) bot.sleep(0.3,0.6) autoit.control_send(bot.title, '', '{F2}', 0) bot.sleep(0.3,0.6) autoit.control_send(bot.title, '', '{F1}', 0) else: fullCounter = 0 if counter < 3: autoit.control_send(bot.title, '', '{F3}', 0) bot.sleep(0.5,0.8) autoit.control_send(bot.title, '', '{F1}', 0) print 'F3' if counter > 2: # bot.findTarget() autoit.control_send(bot.title, '', '{F7}', 0) # if counter > 3: # autoit.control_send(bot.title, '', '{F8}', 0) # counter = 0 counter += 1 print 'cnt ' + str(counter) pass if __name__ == '__main__': main()<|fim▁end|>
<|file_name|>wikilinks.py<|end_file_name|><|fim▁begin|>''' WikiLinks Extension for Python-Markdown ====================================== Converts [[WikiLinks]] to relative links. See <https://pythonhosted.org/Markdown/extensions/wikilinks.html> for documentation. Original code Copyright [Waylan Limberg](http://achinghead.com/). All changes Copyright The Python Markdown Project License: [BSD](http://www.opensource.org/licenses/bsd-license.php) ''' from __future__ import absolute_import from __future__ import unicode_literals from . import Extension from ..inlinepatterns import Pattern from ..util import etree import re def build_url(label, base, end): """ Build a url from the label, a base, and an end. """ clean_label = re.sub(r'([ ]+_)|(_[ ]+)|([ ]+)', '_', label) return '%s%s%s'% (base, clean_label, end) class WikiLinkExtension(Extension): def __init__ (self, *args, **kwargs): self.config = { 'base_url' : ['/', 'String to append to beginning or URL.'], 'end_url' : ['/', 'String to append to end of URL.'], 'html_class' : ['wikilink', 'CSS hook. Leave blank for none.'], 'build_url' : [build_url, 'Callable formats URL from label.'], } super(WikiLinkExtension, self).__init__(*args, **kwargs) def extendMarkdown(self, md, md_globals): self.md = md # append to end of inline patterns WIKILINK_RE = r'\[\[([\w0-9_ -]+)\]\]' wikilinkPattern = WikiLinks(WIKILINK_RE, self.getConfigs()) wikilinkPattern.md = md md.inlinePatterns.add('wikilink', wikilinkPattern, "<not_strong") class WikiLinks(Pattern): def __init__(self, pattern, config): super(WikiLinks, self).__init__(pattern) self.config = config def handleMatch(self, m):<|fim▁hole|> if m.group(2).strip(): base_url, end_url, html_class = self._getMeta() label = m.group(2).strip() url = self.config['build_url'](label, base_url, end_url) a = etree.Element('a') a.text = label a.set('href', url) if html_class: a.set('class', html_class) else: a = '' return a def _getMeta(self): """ Return meta data or config data. """ base_url = self.config['base_url'] end_url = self.config['end_url'] html_class = self.config['html_class'] if hasattr(self.md, 'Meta'): if 'wiki_base_url' in self.md.Meta: base_url = self.md.Meta['wiki_base_url'][0] if 'wiki_end_url' in self.md.Meta: end_url = self.md.Meta['wiki_end_url'][0] if 'wiki_html_class' in self.md.Meta: html_class = self.md.Meta['wiki_html_class'][0] return base_url, end_url, html_class def makeExtension(*args, **kwargs) : return WikiLinkExtension(*args, **kwargs)<|fim▁end|>
<|file_name|>add_special.py<|end_file_name|><|fim▁begin|>from django.core.management.base import BaseCommand from django.contrib.auth.models import User from photos.models import PhotoSceneCategory from photos.add import add_photo #from licenses.models import License class Command(BaseCommand): args = '<flickr_dir>' help = 'Adds photos from flickr' def handle(self, *args, **options): admin_user = User.objects.get_or_create( username='admin')[0].get_profile() print 'user:', admin_user name = 'kitchen' scene_category, _ = PhotoSceneCategory.objects \ .get_or_create(name=name) path = args[0] if not path: print 'No path' return <|fim▁hole|> try: photo = add_photo( path=path, user=admin_user, scene_category=scene_category, flickr_user=None, flickr_id=None, license=None, exif='', fov=None, ) except Exception as e: print '\nNot adding photo:', e else: print '\nAdded photo:', path photo.synthetic = True photo.save()<|fim▁end|>
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be<|fim▁hole|> * found in the LICENSE file at https://angular.io/license */ export * from './src/api'; export {TypeCheckContext} from './src/context'; export {TypeCheckProgramHost} from './src/host'; export {typeCheckFilePath} from './src/type_check_file';<|fim▁end|>
<|file_name|>jquery.flipper.js<|end_file_name|><|fim▁begin|>/* jquery.flipper (c) MrKMG 2012 */ (function( $ ){ var methods = { init : function( o ) { return this.each(function(){ var $this = $(this), data = $this.data('flipper'), text = $this.text(); // If the plugin hasn't been initialized yet if ( ! data ) { var options = $.extend({ type:'fall', speed:'normal', queueSuper:true },o); $this .addClass('flipper') .addClass('fl-animate') .addClass('fl-'+options.type) .addClass('fl-'+options.speed); $this.css('line-height',($this.height()+1)+'px') var new1 = $('<span class="fl-new fl-top fl-num"></span>'); var new2 = $('<span class="fl-new fl-bottom fl-num"></span>'); var cur1 = $('<span class="fl-show fl-top fl-num">'+text+'</span>'); var cur2 = $('<span class="fl-show fl-bottom fl-num">'+text+'</span>'); $this.html('').append(new1,new2,cur1,cur2); $this.data('flipper', { new1:new1, new2:new2, cur1:cur1, cur2:cur2, type:options.type, speed:options.speed, queueSuper:options.queueSuper, running:false, insuper:false, presuperspeed:null, queue:[] }); } }); }, destroy : function( ) { return this.each(function(){ var $this = $(this), data = $this.data('flipper'); data.flipper.remove(); $this.removeData('flipper'); }); }, option:function(key,val){ if(key=="speed"){ var $this = $(this), o = $this.data().flipper; var oldspeed = o.speed; o.speed = val; $this.removeClass('fl-'+oldspeed).addClass('fl-'+val); $this.data('flipper',o); return true; } else if(key=="type"){ var $this = $(this), o = $this.data().flipper; var oldtype = o.type; o.type = val; $this.removeClass('fl-'+oldtype).addClass('fl-'+val); $this.data('flipper',o); return true; } else { return false; } }, update: function( newtext, callback ) { var $this = $(this); var o = $this.data().flipper; if(o.running){ o.queue.push([newtext,callback]); $this.data('flipper',o); return; }else{ o.running = true; methods._process(this,newtext,callback); } }, _process:function(obj,newtext,callback){ var $this = $(obj); var o = $this.data().flipper; $this.data('flipper',o); console.log(o.insuper,o.queue.length); if(o.queueSuper &&!o.insuper && o.queue.length){ var oldspeed = o.speed; o.speed = 'super'; $this.removeClass('fl-'+oldspeed).addClass('fl-super'); o.oldspeed = oldspeed; o.insuper = true; $this.data('flipper',o); }else if(o.queueSuper && o.insuper && !o.queue.length){ o.speed = o.oldspeed; $this.removeClass('fl-super').addClass('fl-'+o.speed); o.insuper = false; $this.data('flipper',o); } setTimeout(function(){ animators[o.type](obj,newtext,function(){ if(o.queue.length){ var q = o.queue.shift(); setTimeout(function(){methods._process(obj,q[0],q[1]);},1); if(typeof(callback) == 'function') callback(false); }else{ if(typeof(callback) == 'function') callback(true); o.running = false; $this.data('flipper',o); } }); },1); }, clearqueue: function(){ var $this = $(this); var o = $this.data().flipper; o.queue.length = 0; $this.data('flipper',o); } }; var animators = { fall:function(obj,newtext,finished){ var $this = $(obj); var o = $this.data().flipper; $this.addClass('fl-animate'); $this.addClass('fl-go'); o.new1.text(newtext); o.new2.text(newtext); if(o.speed=='slow') var t = 2000; else if(o.speed=='normal') var t = 1000; else if(o.speed=='fast') var t = 500; else if(o.speed=='super') var t = 50; setTimeout(function(){ $this.removeClass('fl-animate'); o.cur1.text(newtext); o.cur2.text(newtext); o.new1.text(''); o.new2.text(''); $this.removeClass('fl-go'); finished(); },t); }, rise:function(obj,newtext,finished){ var $this = $(obj); var o = $this.data().flipper; $this.addClass('fl-animate'); $this.addClass('fl-go'); o.new1.text(newtext); o.new2.text(newtext); if(o.speed=='slow') var t = 2000; else if(o.speed=='normal') var t = 1000; else if(o.speed=='fast') var t = 500; else if(o.speed=='super') var t = 50; setTimeout(function(){ $this.removeClass('fl-animate'); o.cur1.text(newtext); o.cur2.text(newtext); o.new1.text(''); o.new2.text(''); $this.removeClass('fl-go'); finished(); },t); }, clap:function(obj,newtext,finished){ var $this = $(obj); var o = $this.data().flipper; $this.addClass('fl-animate'); $this.addClass('fl-go'); o.new1.text(newtext); o.new2.text(o.cur2.text()); o.cur2.text(newtext); if(o.speed=='slow') var t = 2000; else if(o.speed=='normal') var t = 1000; else if(o.speed=='fast') var t = 500; else if(o.speed=='super') var t = 50; setTimeout(function(){ $this.removeClass('fl-animate'); o.cur1.text(newtext); o.new1.text(''); o.new2.text(''); $this.removeClass('fl-go'); finished(); },t); }, slide:function(obj,newtext,finished){ var $this = $(obj); var o = $this.data().flipper; $this.addClass('fl-animate'); $this.addClass('fl-go'); o.new1.text(newtext); if(o.speed=='slow'){ var t1 = 2000; var t2 = 1000; } else if(o.speed=='normal'){ var t1 = 1000; var t2 = 500; } else if(o.speed=='fast'){ var t1 = 500; var t2 = 250; } else if(o.speed=='super'){ var t1 = 50; var t2 = 25; } setTimeout(function(){ $this.removeClass('fl-go').addClass('fl-zfix'); o.cur2.text(newtext); },t2); setTimeout(function(){ $this.removeClass('fl-animate'); o.cur1.text(newtext); o.new1.text(''); $this.removeClass('fl-zfix'); finished(); },t1); }, open:function(obj,newtext,finished){ var $this = $(obj); var o = $this.data().flipper; $this.addClass('fl-animate'); $this.addClass('fl-go'); o.new1.text(newtext); o.new2.text(newtext); if(o.speed=='slow'){ var t1 = 2000; var t2 = 1000; } else if(o.speed=='normal'){ var t1 = 1000; var t2 = 500; } else if(o.speed=='fast'){ var t1 = 500; var t2 = 250; } else if(o.speed=='super'){ var t1 = 50; var t2 = 25; } setTimeout(function(){ $this.addClass('fl-zfix'); },t2); setTimeout(function(){ $this.removeClass('fl-animate'); o.cur1.text(newtext); o.cur2.text(newtext); o.new1.text(''); o.new2.text(''); $this.removeClass('fl-go').removeClass('fl-zfix'); finished(); },t1); }, close:function(obj,newtext,finished){ var $this = $(obj); var o = $this.data().flipper; $this.addClass('fl-animate'); $this.addClass('fl-go'); o.new1.text(o.cur1.text()); o.new2.text(o.cur2.text()); o.cur1.text(newtext); o.cur2.text(newtext); if(o.speed=='slow'){ var t1 = 2000; var t2 = 1000; } else if(o.speed=='normal'){ var t1 = 1000; var t2 = 500; } else if(o.speed=='fast'){ var t1 = 500; var t2 = 250; } else if(o.speed=='super'){ var t1 = 50; var t2 = 25; } $this.addClass('fl-zfix');<|fim▁hole|> $this.removeClass('fl-zfix'); },t2); setTimeout(function(){ $this.removeClass('fl-animate'); o.cur1.text(newtext); o.cur2.text(newtext); o.new1.text(''); o.new2.text(''); $this.removeClass('fl-go'); finished(); },t1); } }; $.fn.flipper = function( method ) { if ( methods[method] ) { return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.flipper' ); } }; })( jQuery );<|fim▁end|>
setTimeout(function(){
<|file_name|>quotes.component.ts<|end_file_name|><|fim▁begin|>import { Component, OnInit } from '@angular/core'; <|fim▁hole|>import { Observable } from 'rxjs'; @Component({ selector: 'app-quotes', templateUrl: './quotes.component.html', styleUrls: ['./quotes.component.css'] }) export class QuotesComponent implements OnInit { quotes: Observable<Quote[]>; selectedQuote: Quote; mode: String; pagination: boolean; page: number; size: number; constructor(private quoteReactiveService: QuoteReactiveService, private quoteBlockingService: QuoteBlockingService) { this.mode = "reactive"; this.pagination = true; this.page = 0; this.size = 50; } ngOnInit(): void { } requestQuoteStream(): void { if (this.pagination === true) { this.quotes = this.quoteReactiveService.getQuoteStream(this.page, this.size); } else { this.quotes = this.quoteReactiveService.getQuoteStream(); } } requestQuoteBlocking(): void { if (this.pagination === true) { this.quotes = this.quoteBlockingService.getQuotes(this.page, this.size); } else { this.quotes = this.quoteBlockingService.getQuotes(); } } onSelect(quote: Quote): void { this.selectedQuote = quote; } }<|fim▁end|>
import { Quote } from '../model/quote'; import { QuoteReactiveService } from '../quote-reactive.service'; import { QuoteBlockingService } from '../quote-blocking.service';
<|file_name|>Main.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import feedparser import wget import sqlite3 import time RssUrlList = ['http://postitforward.tumblr.com/rss','http://for-war3-blog-blog.tumblr.com/rss'] sleep=3600/len(RssUrlList) def mkdir(path): import os path=path.strip() path=path.rstrip("\\") isExists=os.path.exists(path) if not isExists: os.makedirs(path) conn = sqlite3.connect('tumblr.db') def DownloadVideo(rss_url): feeds = feedparser.parse(rss_url) table=rss_url[7:-15].replace('-','') try: conn.execute('''CREATE TABLE %s(BLOG TEXT, ADDRESS TEXT PRIMARY KEY, DATE REAL)'''% table) conn.execute("INSERT INTO %s (BLOG ,ADDRESS, DATE) VALUES ('%s','new','0')" % (table,rss_url)) # conn.execute("SELECT * FROM TUMBLR WHERE BLOG == %s").next() except:<|fim▁hole|> mkdir(rss_url[7:-4]) for post in feeds.entries: thisposttime=float(time.mktime(time.strptime(post.published[:-6],"%a, %d %b %Y %H:%M:%S"))) if conn.execute("SELECT MAX(DATE) FROM %s"%table).next()[0] == thisposttime: break if post.description.find("video_file") == -1: continue sourceadd= post.description.find("source src=") tumblradd= post.description[sourceadd:].find("tumblr_") typeadd = post.description[sourceadd:][tumblradd:].find("type=\"video") video_id=post.description[sourceadd:][tumblradd:][:typeadd-2] if video_id.find("/") !=-1: video_id=video_id[:video_id.find("/")] try: list(conn.execute("SELECT * FROM %s WHERE ADDRESS == '%s'"%(table,video_id)).next()) except: print(post.title + ": " + post.link + post.published+"\n") wget.download("http://vt.tumblr.com/"+video_id+".mp4",rss_url[7:-4]) print("\n") conn.execute("INSERT INTO %s (BLOG ,ADDRESS, DATE) VALUES ('%s','%s','%f')" % (table,rss_url,video_id,time.mktime(time.strptime(post.published[:-6],"%a, %d %b %Y %H:%M:%S")))) #wget.download(get_download_url("https://your.appspot.com/fetch.php?url="+post.link),rss_url[7:-4]) conn.commit() while(1): for rss_url in RssUrlList: print("Downloading "+rss_url) DownloadVideo(rss_url) print("Sleep "+str(sleep)+" seconds") time.sleep(sleep)<|fim▁end|>
pass # conn.execute('''CREATE TABLE(BLOG TEXT, ADDRESS TEXT PRIMARY KEY, DATE TEXT);''') # conn.execute("INSERT INTO %s (BLOG ,ADDRESS, DATE) VALUES ('rss_url','TEST','TEST')" % table)
<|file_name|>omaps.py<|end_file_name|><|fim▁begin|>from .utils.dataIO import fileIO from .utils import checks from __main__ import send_cmd_help from __main__ import settings as bot_settings # Sys. from operator import itemgetter, attrgetter import discord from discord.ext import commands #from copy import deepcopy import aiohttp import asyncio import json import os import http.client DIR_DATA = "data/omaps" POINTER = DIR_DATA+"/pointer.png" MAP = DIR_DATA+"/map.png" class OpenStreetMaps: """The openstreetmap.org cog""" def __init__(self,bot): self.bot = bot @commands.command(pass_context=True, no_pm=False) async def prevmap(self, ctx): """Resend the last openstreetmap.org result""" user = ctx.message.author channel = ctx.message.channel if not fileIO(MAP, "check"): await self.bot.say("` No previous map available.`") else: await self.bot.send_file(channel, MAP) @commands.command(pass_context=True, no_pm=False) async def maps(self, ctx, zoom, *country): """Search at openstreetmap.org\n zoom: upclose, street, city, country, world Type: 'none' to skip""" user = ctx.message.author channel = ctx.message.channel country = "+".join(country) longitude = 0.0 latitude = 0.0 adressNum = 1 limitResult = 0 # Set tile zoom if zoom == 'upclose': zoomMap = 18 elif zoom == 'street': zoomMap = 16 elif zoom == 'city': zoomMap = 11 elif zoom == 'country': zoomMap = 8 elif zoom == 'world': zoomMap = 2 else: zoomMap = 16 # Get input data search = country await self.bot.say("` What city?`") response = await self.bot.wait_for_message(author=ctx.message.author) response = response.content.lower().strip().replace(" ", "+") if response == "none": pass else: search = search+","+response #http://wiki.openstreetmap.org/wiki/Nominatim await self.bot.say("` Enter your search term for the given location (building, company, address...) or type: none`") response = await self.bot.wait_for_message(author=ctx.message.author) response = response.content.lower().strip().replace(" ", "+") if response == "none": pass else: search = search+","+response #print (search) # Get xml result from openstreetmap.org try: domain = "nominatim.openstreetmap.org" search = "/search?q={}&format=xml&polygon=1&addressdetails=1".format(search) #print(domain+search) conn = http.client.HTTPConnection(domain) conn.request("GET", search) r1 = conn.getresponse() data = r1.read() conn.close() except Exception as e: await self.bot.say("` Error getting GPS data.`") print("Error getting GPS data.") print(e) return try: display_name = "-" soup = BeautifulSoup(data, 'html.parser') links = soup.findAll('place', lon=True) results = len(links) if results == 0: await self.bot.say("`No results, try to rephrase`") return #print("results:\n"+str(results)) #print("display_name:\n"+display_name) #print("longitude/latitude:\n"+str(longitude)+","+str(latitude)) except Exception as e: await self.bot.say("`Something went wrong while parsing xml data...`") print('parse XML failed') print(e) return await self.bot.send_typing(channel) if results > 1: list = "```erlang\nResults\n-\n" index = 0 for link in links: index += 1 list = list + "(" +str(index) + "): "+ link["display_name"] + "\n" list = list +"```` Enter result number...`" await self.bot.say(list) response = await self.bot.wait_for_message(author=ctx.message.author) input = response.content.lower().strip() # Set values for geotiler try: input = int(input)-1 except: input = 0<|fim▁hole|> place_id = (links[input]["place_id"]) display_name = (links[input]["display_name"]) longitude = (links[input]['lon']) latitude = (links[input]['lat']) else: # Set values for geotiler place_id = (links[0]["place_id"]) display_name = (links[0]["display_name"]) longitude = (links[0]['lon']) latitude = (links[0]['lat']) await self.bot.send_typing(channel) #print([latitude, longitude, zoomMap]) map = geotiler.Map(center=(float(longitude), float(latitude)), zoom=zoomMap, size=(720, 720)) map.extent image = await geotiler.render_map_async(map) image.save(MAP) await self.bot.send_typing(channel) # Add pointer and text. savedMap = Image(filename=MAP) pointer = Image(filename=POINTER) for o in COMPOSITE_OPERATORS: w = savedMap.clone() r = pointer.clone() with Drawing() as draw: draw.composite(operator='atop', left=311, top=311, width=90, height=90, image=r) #720 draw(w) # Text draw.fill_color = Color("#7289DA") draw.stroke_color = Color("#5370D7") draw.stroke_width = 0.3 draw.fill_opacity = 0.7 draw.stroke_opacity = 0.7 draw.font_style = 'oblique' draw.font_size = 32 splitDisplayName = display_name.split(',') # Object name/number draw.text(x=20, y=35, body=splitDisplayName[0]) draw(w) del splitDisplayName[0] # Print location info on map. line0 = "" line1 = "" draw.font_size = 18 for i in splitDisplayName: if len(str(line0)) > 30: line1 = line1 + i + "," else: line0 = line0 + i + "," # line 0 if len(str(line0)) > 2: draw.text(x=15, y=60, body=line0) draw(w) # line 1 if len(str(line1)) > 2: draw.text(x=15, y=80, body=line1) draw(w) # Copyright Open Street Map draw.fill_color = Color("#000000") draw.stroke_color = Color("#333333") draw.fill_opacity = 0.3 draw.stroke_opacity = 0.3 draw.font_style = 'normal' draw.font_size = 14 draw.text(x=550, y=700, body="© OpenStreetMap.org") #720 draw(w) w.save(filename=MAP) await self.bot.send_file(channel, MAP) #-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- # Set-up #-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def check_folders(): if not os.path.exists(DIR_DATA): print("Creating {} folder...".format(DIR_DATA)) os.makedirs(DIR_DATA) def check_files(): if not os.path.isfile(POINTER): print("pointer.png is missing!") class ModuleNotFound(Exception): def __init__(self, m): self.message = m def __str__(self): return self.message def setup(bot): global geotiler global Color, Drawing, display, Image, Color, Image, COMPOSITE_OPERATORS global BeautifulSoup check_folders() check_files() try: import geotiler except: raise ModuleNotFound("geotiler is not installed. Do 'pip3 install geotiler --upgrade' to use this cog.") try: from bs4 import BeautifulSoup except: raise ModuleNotFound("BeautifulSoup is not installed. Do 'pip3 install BeautifulSoup --upgrade' to use this cog.") try: from wand.image import Image, COMPOSITE_OPERATORS from wand.drawing import Drawing from wand.display import display from wand.image import Image from wand.color import Color except: raise ModuleNotFound("Wand is not installed. Do 'pip3 install Wand --upgrade' and make sure you have ImageMagick installed http://docs.wand-py.org/en/0.4.2/guide/install.html") bot.add_cog(OpenStreetMaps(bot))<|fim▁end|>
<|file_name|>struct_list.rs<|end_file_name|><|fim▁begin|>// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //! List of structs. use private::layout::{ListReader, ListBuilder, PointerReader, PointerBuilder, InlineComposite}; use traits::{FromPointerReader, FromPointerBuilder, FromStructBuilder, FromStructReader, HasStructSize, IndexMove, ListIter}; use Result; #[derive(Copy, Clone)] pub struct Owned<T> where T: for<'a> ::traits::OwnedStruct<'a> { marker: ::std::marker::PhantomData<T>, } impl<'a, T> ::traits::Owned<'a> for Owned<T> where T: for<'b> ::traits::OwnedStruct<'b> { type Reader = Reader<'a, T>; type Builder = Builder<'a, T>; } pub struct Reader<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> { marker: ::std::marker::PhantomData<T>, reader: ListReader<'a> } impl <'a, T> Clone for Reader<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> { fn clone(&self) -> Reader<'a, T> { Reader { marker : self.marker, reader : self.reader } } } impl <'a, T> Copy for Reader<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> {} impl <'a, T> Reader<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> { pub fn new<'b>(reader : ListReader<'b>) -> Reader<'b, T> { Reader::<'b, T> { reader : reader, marker : ::std::marker::PhantomData } } pub fn len(&self) -> u32 { self.reader.len() } pub fn iter(self) -> ListIter<Reader<'a, T>, <T as ::traits::OwnedStruct<'a>>::Reader> { ListIter::new(self, self.len()) } } impl <'a, T> Reader<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> { pub fn borrow<'b>(&'b self) -> Reader<'b, T> { Reader {reader : self.reader, marker : ::std::marker::PhantomData} } } impl <'a, T> FromPointerReader<'a> for Reader<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> { fn get_from_pointer(reader : &PointerReader<'a>) -> Result<Reader<'a, T>> { Ok(Reader { reader : try!(reader.get_list(InlineComposite, ::std::ptr::null())), marker : ::std::marker::PhantomData }) } } impl <'a, T> IndexMove<u32, <T as ::traits::OwnedStruct<'a>>::Reader> for Reader<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> { fn index_move(&self, index : u32) -> <T as ::traits::OwnedStruct<'a>>::Reader { self.get(index) } } impl <'a, T> Reader<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> { pub fn get(self, index: u32) -> <T as ::traits::OwnedStruct<'a>>::Reader { assert!(index < self.len()); FromStructReader::new(self.reader.get_struct_element(index)) } } pub struct Builder<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> { marker : ::std::marker::PhantomData<T>, builder : ListBuilder<'a> } impl <'a, T> Builder<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> {<|fim▁hole|> Builder { builder : builder, marker : ::std::marker::PhantomData } } pub fn len(&self) -> u32 { self.builder.len() } // pub fn set(&self, index : uint, value : T) { // } } impl <'a, T> Builder<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> { pub fn borrow<'b>(&'b mut self) -> Builder<'b, T> { Builder {builder : self.builder, marker : ::std::marker::PhantomData} } } impl <'a, T> FromPointerBuilder<'a> for Builder<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> { fn init_pointer(builder : PointerBuilder<'a>, size : u32) -> Builder<'a, T> { Builder { marker : ::std::marker::PhantomData, builder : builder.init_struct_list( size, <<T as ::traits::OwnedStruct>::Builder as HasStructSize>::struct_size()) } } fn get_from_pointer(builder : PointerBuilder<'a>) -> Result<Builder<'a, T>> { Ok(Builder { marker : ::std::marker::PhantomData, builder : try!(builder.get_struct_list(<<T as ::traits::OwnedStruct>::Builder as HasStructSize>::struct_size(), ::std::ptr::null())) }) } } impl <'a, T> Builder<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> { pub fn get(self, index: u32) -> <T as ::traits::OwnedStruct<'a>>::Builder { assert!(index < self.len()); FromStructBuilder::new(self.builder.get_struct_element(index)) } } impl <'a, T> ::traits::SetPointerBuilder<Builder<'a, T>> for Reader<'a, T> where T: for<'b> ::traits::OwnedStruct<'b> { fn set_pointer_builder<'b>(pointer : ::private::layout::PointerBuilder<'b>, value : Reader<'a, T>) -> Result<()> { pointer.set_list(&value.reader) } }<|fim▁end|>
pub fn new(builder : ListBuilder<'a>) -> Builder<'a, T> {
<|file_name|>PharmacologyByTargetTest.js<|end_file_name|><|fim▁begin|>describe('Targets can be searched', function() { var store_records, store_operation, store_success; beforeEach(function() { this.application = Ext.create('Ext.app.Application', { name:'LSP', appFolder:'./app', requires:['LDA.helper.LDAConstants'], // Define all the controllers that should initialize at boot up of your application controllers:[ // 'LDAParserController', // 'Users',<|fim▁hole|> 'NavigationTree', // 'Queryform', 'SimSearchForm', 'CmpdByNameForm', 'TargetByNameForm', 'PharmByTargetNameForm', 'PharmByCmpdNameForm', 'PharmByEnzymeFamily', // 'SummeryForm', 'Settings', // 'pmidTextMiningHitsForm', // 'pathwayByCompoundForm', // 'pathwayByProteinForm', // 'PharmByTargetNameFormInf', 'CW.controller.ConceptWikiLookup' ], // autoCreateViewport:true, launch:function () { //include the tests in the test.html head //jasmine.getEnv().addReporter(new jasmine.TrivialReporter()); //jasmine.getEnv().execute(); } }); }); it('and results can be paginated', function() { var store = Ext.create('LDA.store.TargetPharmacologyPaginatedStore',{}); store.uri = 'http://www.conceptwiki.org/concept/b932a1ed-b6c3-4291-a98a-e195668eda49'; store.load(function(records, operation, success) { store_records = records; store_operation = operation; store_success = operation.success; }); waitsFor( function(){ return !store.isLoading(); }, "load never completed", 4000 ); runs(function() { expect(store_success).toEqual(true); }); }); it('and results can be filtered for activities', function() { var store = Ext.create('LDA.store.TargetPharmacologyPaginatedStore',{}); store.uri = 'http://www.conceptwiki.org/concept/b932a1ed-b6c3-4291-a98a-e195668eda49'; store.setActivityType('IC50'); store.setActivityValue('10000'); store.setActivityCondition('<'); store.load(function(records, operation, success) { store_records = records; store_operation = operation; store_success = operation.success; }); waitsFor( function(){ return !store.isLoading(); }, "load never completed", 4000 ); runs(function() { expect(store_success).toEqual(true); }); }); it('and specific pages can be requested', function() { var store = Ext.create('LDA.store.TargetPharmacologyPaginatedStore',{}); store.uri = 'http://www.conceptwiki.org/concept/b932a1ed-b6c3-4291-a98a-e195668eda49'; store.page = 10; store.setActivityType('IC50'); store.setActivityValue('10000'); store.setActivityCondition('<'); store.load(function(records, operation, success) { store_records = records; store_operation = operation; store_success = operation.success; }); waitsFor( function(){ return !store.isLoading(); }, "load never completed", 4000 ); runs(function() { expect(store_success).toEqual(true); }); }); });<|fim▁end|>
'grids.DynamicGrid', // 'grids.PharmaGridInf', // 'Grid',