<commit_before>#!/usr/bin/env python
# encoding: utf-8

import objc
from Foundation import *
from AppKit import *
import sys, os, re

MainBundle = NSBundle.mainBundle()
path = MainBundle.bundlePath() + "/Contents/Scripts"
if not path in sys.path:
	sys.path.append( path )

import GlyphsApp

GlyphsReporterProtocol = objc.protocolNamed( "GlyphsReporter" )

class ShowBlackFill ( NSObject, GlyphsReporterProtocol ):

	def init( self ):
		try:
			#Bundle = NSBundle.bundleForClass_( NSClassFromString( self.className() ));
			return self
		except Exception as e:
			self.logToConsole( "init: %s" % str(e) )

	def interfaceVersion( self ):
		try:
			return 1
		except Exception as e:
			self.logToConsole( "interfaceVersion: %s" % str(e) )

	def title( self ):
		try:
			return "Black Fill"
		except Exception as e:
			self.logToConsole( "title: %s" % str(e) )

	def keyEquivalent( self ):
		try:
			return None
		except Exception as e:
			self.logToConsole( "keyEquivalent: %s" % str(e) )

	def modifierMask( self ):
		try:
			return 0
		except Exception as e:
			self.logToConsole( "modifierMask: %s" % str(e) )

	def setController_( self, Controller ):
		self.controller = Controller

	def getScale( self ):
		"""
		Returns the current scale factor of the Edit View UI.
		Divide any scalable size by this value in order to keep the same pixel size.
		"""
		try:
			return self.controller.graphicView().scale()
		except:
			self.logToConsole( "Scale defaulting to 1.0" )
			return 1.0

	def getNodeSize( self ):
		"""
		Returns the current handle size as set in user preferences.
		"""
		try:
			Selected = NSUserDefaults.standardUserDefaults().integerForKey_( "GSHandleSize" )
			if Selected == 0:
				return 5.0
			elif Selected == 2:
				return 10.0
			else:
				return 7.0
		except:
			self.logToConsole( "HandleSize defaulting to 7.0" )
			return 7.0

	def getListOfNodesToBeMarked( self, thisLayer ):
		"""
		Returns a list of all On-curve nodes.
		"""
		try:
			returnList = []

			for thisPath in thisLayer.paths:
				for i in range( len( thisPath.nodes )):
					thisNode = thisPath.nodes[ i ]
					returnList.append( thisNode )

			return returnList
		except Exception as e:
			self.logToConsole( "getListOfNodesToBeMarked: " + str(e) )

	def getListOfSelectedSmooth( self, thisLayer ):
		"""
		Returns a list of all selected smooth On-curve nodes.
		"""
		try:
			returnList = []
			currentSelection = thisLayer.selection()

			for thisObject in currentSelection:
				if type( thisObject ) == GSNode:
					if thisObject.connection == 4096:
						returnList.append( thisObject )
			# It doesn't work. Disables all nodes when connected.
			#if not currentSelection.closed:
			#	del returnList[0, -1]
			return returnList
		except Exception as e:
			self.logToConsole( "getListOfSelectedNodes_ " + str(e) )

	def getListOfSelectedSharp( self, thisLayer ):
		"""
		Returns a list of all selected sharp On-curve nodes.
		"""
		try:
			returnList = []
			currentSelection = thisLayer.selection()

			for thisObject in currentSelection:
				if type( thisObject ) == GSNode:
					if thisObject.type != 65 and thisObject.connection !=4096:
							returnList.append( thisObject )
			# It doesn't work. Disables all nodes when connected.
			#if not currentSelection.closed:
			#	del returnList[0, -1]
			return returnList
		except Exception as e:
			self.logToConsole( "getListOfSelectedNodes_ " + str(e) )

	def getListOfSelectedOffCurve( self, thisLayer ):
		"""
		Returns a list of all selected Off-curve nodes.
		"""
		try:
			returnList = []
			currentSelection = thisLayer.selection()

			for thisObject in currentSelection:
				if type( thisObject ) == GSNode:
					if thisObject.type == 65:
						returnList.append( thisObject )
			return returnList
		except Exception as e:
			self.logToConsole( "getListOfSelectedNodes_ " + str(e) )

	def getListOfHandlesToBeMarked( self, thisLayer ):
		"""
		Returns a list of Handles that need to be outlined.
		"""
		try:
			returnList = []
			currentSelection = thisLayer.selection()

			for thisPath in thisLayer.paths:
				thisPathLength = len( thisPath.nodes )

				for i in range( len( thisPath.nodes )):
					thisNode = thisPath.nodes[ i ]
					if thisNode in currentSelection:
						prevNode = thisPath.nodes[ (i-1) % thisPathLength]
						nextNode = thisPath.nodes[ (i+1) % thisPathLength]

						if thisNode.type == 65:
							# a selected off-curve
							if prevNode.type != 65:
								returnList.append( (prevNode, thisNode) )
								if not nextNode in currentSelection:
									returnList.append( ( thisPath.nodes[ (i+2) % thisPathLength], nextNode ) )
							elif nextNode.type != 65:
								returnList.append( (nextNode, thisNode) )
								if not prevNode in currentSelection:
									returnList.append( ( thisPath.nodes[ (i-2) % thisPathLength], prevNode ) )
						else:
							# a selected on-curve
							if prevNode.type == 65 and not prevNode in currentSelection:
								returnList.append( (thisNode, prevNode) )
								prevPrevNode = thisPath.nodes[ (i-2) ]
								prevPrevPrevNode = thisPath.nodes[ (i-3) ]
								if prevPrevNode not in currentSelection and prevPrevPrevNode not in currentSelection:
									returnList.append( (prevPrevPrevNode, prevPrevNode) )
							if nextNode.type == 65 and not nextNode in currentSelection:
								returnList.append( (thisNode, nextNode) )
								nextNextNode = thisPath.nodes[ (i+2) % thisPathLength ]
								nextNextNextNode = thisPath.nodes[ (i+3) % thisPathLength ]
								if nextNextNode not in currentSelection and nextNextNextNode not in currentSelection:
									returnList.append( (nextNextNextNode, nextNextNode) )

			return list(set(returnList))
		except Exception as e:
			self.logToConsole( "getListOfHandlesToBeMarked_ " + str(e) )

	def markerForPoint( self, thisPoint, markerWidth ):
		"""
		Returns a circle with thisRadius around thisPoint.
		"""
		try:
			myRect = NSRect( ( thisPoint.x - markerWidth * 0.5, thisPoint.y - markerWidth * 0.5 ), ( markerWidth, markerWidth ) )
			return NSBezierPath.bezierPathWithOvalInRect_( myRect )
		except Exception as e:
			self.logToConsole( "markerForPoint_ " + str(e) )

	def drawForegroundForLayer_( self, Layer ):
		"""
		Fills closed outline, outlines handles, and paints nodes.
		"""
		#Black fill
		try:
						NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.0, 0.0, 0.0, 0.85 ).set() # sets RGBA values between 0.0 and 1.0
						Layer.bezierPath().fill()
		except Exception as e:
			self.logToConsole( "drawForegroundForLayer_: %s" % str(e) )

		try:
			NodeSize = self.getNodeSize()
			Scale = self.getScale()
			circleRadius = NodeSize / Scale
			handleStroke = 1.0 / Scale

			# Selected handles
			NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.5, 0.5, 0.5, 0.5).set()
			circlesToBeDrawn = NSBezierPath.alloc().init()
			linesToBeDrawn   = NSBezierPath.alloc().init()
			for thisPointPair in self.getListOfHandlesToBeMarked( Layer ):
				fromPoint = thisPointPair[0]
				toPoint   = thisPointPair[1]
				linesToBeDrawn.moveToPoint_( NSPoint(fromPoint.x, fromPoint.y) )
				linesToBeDrawn.lineToPoint_( NSPoint(toPoint.x, toPoint.y) )
				circlesToBeDrawn.appendBezierPath_( self.markerForPoint( toPoint, circleRadius ) )
			linesToBeDrawn.setLineWidth_( handleStroke )
			linesToBeDrawn.stroke()
			circlesToBeDrawn.setLineWidth_( handleStroke )
			circlesToBeDrawn.stroke()

			# Unselected nodes
			NSColor.colorWithCalibratedRed_green_blue_alpha_( 1.0, 1.0, 1.0, 0.15 ).set()
			circlesToBeDrawn = NSBezierPath.alloc().init()
			for thisPoint in self.getListOfNodesToBeMarked( Layer ):
				circlesToBeDrawn.appendBezierPath_( self.markerForPoint( thisPoint, circleRadius ) )
			circlesToBeDrawn.fill()

			# Selected Smooth On-curve
			NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.0, 0.7, 0.4, 0.3 ).set()
			circlesToBeDrawn = NSBezierPath.alloc().init()
			for thisPoint in self.getListOfSelectedSmooth( Layer ):
				circlesToBeDrawn.appendBezierPath_( self.markerForPoint( thisPoint, circleRadius ) )
			circlesToBeDrawn.fill()

			# Selected Sharp On-Curve
			NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.2, 0.4, 0.8, 0.3 ).set()
			circlesToBeDrawn = NSBezierPath.alloc().init()
			for thisPoint in self.getListOfSelectedSharp( Layer ):
				circlesToBeDrawn.appendBezierPath_( self.markerForPoint( thisPoint, circleRadius ) )
			circlesToBeDrawn.fill()

			# Selected Off-curve
			NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.5, 0.5, 0.5, 0.2 ).set()
			circlesToBeDrawn = NSBezierPath.alloc().init()
			for thisPoint in self.getListOfSelectedOffCurve( Layer ):
				circlesToBeDrawn.appendBezierPath_( self.markerForPoint( thisPoint, circleRadius ) )
			circlesToBeDrawn.fill()

		except Exception as e:
			self.logToConsole( "drawForegroundForLayer_ " + str(e) )

	def drawBackgroundForLayer_( self, Layer ):
		"""
		Whatever you draw here will be displayed BEHIND the paths.
		"""
		try:
			pass
		except Exception as e:
			self.logToConsole( "drawBackgroundForLayer_: %s" % str(e) )

	def drawBackgroundForInactiveLayer_( self, Layer ):
		"""
		Whatever you draw here will be displayed behind the paths, but for inactive masters.
		"""
		try:
			pass
		except Exception as e:
			self.logToConsole( "drawBackgroundForInactiveLayer_: %s" % str(e) )

	def needsExtraMainOutlineDrawingForInactiveLayer_( self, Layer ):
		"""
		Return False to disable the black outline. Otherwise remove the method.
		"""
		return False

	def getScale( self ):
		"""
		self.getScale() returns the current scale factor of the Edit View UI.
		Divide any scalable size by this value in order to keep the same apparent pixel size.
		"""
		try:
			return self.controller.graphicView().scale()
		except:
			self.logToConsole( "Scale defaulting to 1.0" )
			return 1.0

	def setController_( self, Controller ):
		"""
		Use self.controller as object for the current view controller.
		"""
		try:
			self.controller = Controller
		except Exception as e:
			self.logToConsole( "Could not set controller" )

	def logToConsole( self, message ):
		"""
		The variable 'message' will be passed to Console.app.
		Use self.logToConsole( "bla bla" ) for debugging.
		"""
		myLog = "Show %s plugin:\n%s" % ( self.title(), message )
		NSLog( myLog )
<commit_msg>Stronger component colour<commit_after>#!/usr/bin/env python
# encoding: utf-8

import objc
from Foundation import *
from AppKit import *
import sys, os, re

MainBundle = NSBundle.mainBundle()
path = MainBundle.bundlePath() + "/Contents/Scripts"
if not path in sys.path:
	sys.path.append( path )

import GlyphsApp

GlyphsReporterProtocol = objc.protocolNamed( "GlyphsReporter" )

class ShowBlackFill ( NSObject, GlyphsReporterProtocol ):

	def init( self ):
		try:
			#Bundle = NSBundle.bundleForClass_( NSClassFromString( self.className() ));
			return self
		except Exception as e:
			self.logToConsole( "init: %s" % str(e) )

	def interfaceVersion( self ):
		try:
			return 1
		except Exception as e:
			self.logToConsole( "interfaceVersion: %s" % str(e) )

	def title( self ):
		try:
			return "Black Fill"
		except Exception as e:
			self.logToConsole( "title: %s" % str(e) )

	def keyEquivalent( self ):
		try:
			return None
		except Exception as e:
			self.logToConsole( "keyEquivalent: %s" % str(e) )

	def modifierMask( self ):
		try:
			return 0
		except Exception as e:
			self.logToConsole( "modifierMask: %s" % str(e) )

	def setController_( self, Controller ):
		self.controller = Controller

	def getScale( self ):
		"""
		Returns the current scale factor of the Edit View UI.
		Divide any scalable size by this value in order to keep the same pixel size.
		"""
		try:
			return self.controller.graphicView().scale()
		except:
			self.logToConsole( "Scale defaulting to 1.0" )
			return 1.0

	def getNodeSize( self ):
		"""
		Returns the current handle size as set in user preferences.
		"""
		try:
			Selected = NSUserDefaults.standardUserDefaults().integerForKey_( "GSHandleSize" )
			if Selected == 0:
				return 5.0
			elif Selected == 2:
				return 10.0
			else:
				return 7.0
		except:
			self.logToConsole( "HandleSize defaulting to 7.0" )
			return 7.0

	def getListOfNodesToBeMarked( self, thisLayer ):
		"""
		Returns a list of all On-curve nodes.
		"""
		try:
			returnList = []

			for thisPath in thisLayer.paths:
				for i in range( len( thisPath.nodes )):
					thisNode = thisPath.nodes[ i ]
					returnList.append( thisNode )

			return returnList
		except Exception as e:
			self.logToConsole( "getListOfNodesToBeMarked: " + str(e) )

	def getListOfSelectedSmooth( self, thisLayer ):
		"""
		Returns a list of all selected smooth On-curve nodes.
		"""
		try:
			returnList = []
			currentSelection = thisLayer.selection()

			for thisObject in currentSelection:
				if type( thisObject ) == GSNode:
					if thisObject.connection == 4096:
						returnList.append( thisObject )
			# It doesn't work. Disables all nodes when connected.
			#if not currentSelection.closed:
			#	del returnList[0, -1]
			return returnList
		except Exception as e:
			self.logToConsole( "getListOfSelectedNodes_ " + str(e) )

	def getListOfSelectedSharp( self, thisLayer ):
		"""
		Returns a list of all selected sharp On-curve nodes.
		"""
		try:
			returnList = []
			currentSelection = thisLayer.selection()

			for thisObject in currentSelection:
				if type( thisObject ) == GSNode:
					if thisObject.type != 65 and thisObject.connection !=4096:
							returnList.append( thisObject )
			# It doesn't work. Disables all nodes when connected.
			#if not currentSelection.closed:
			#	del returnList[0, -1]
			return returnList
		except Exception as e:
			self.logToConsole( "getListOfSelectedNodes_ " + str(e) )

	def getListOfSelectedOffCurve( self, thisLayer ):
		"""
		Returns a list of all selected Off-curve nodes.
		"""
		try:
			returnList = []
			currentSelection = thisLayer.selection()

			for thisObject in currentSelection:
				if type( thisObject ) == GSNode:
					if thisObject.type == 65:
						returnList.append( thisObject )
			return returnList
		except Exception as e:
			self.logToConsole( "getListOfSelectedNodes_ " + str(e) )

	def getListOfHandlesToBeMarked( self, thisLayer ):
		"""
		Returns a list of Handles that need to be outlined.
		"""
		try:
			returnList = []
			currentSelection = thisLayer.selection()

			for thisPath in thisLayer.paths:
				thisPathLength = len( thisPath.nodes )

				for i in range( len( thisPath.nodes )):
					thisNode = thisPath.nodes[ i ]
					if thisNode in currentSelection:
						prevNode = thisPath.nodes[ (i-1) % thisPathLength]
						nextNode = thisPath.nodes[ (i+1) % thisPathLength]

						if thisNode.type == 65:
							# a selected off-curve
							if prevNode.type != 65:
								returnList.append( (prevNode, thisNode) )
								if not nextNode in currentSelection:
									returnList.append( ( thisPath.nodes[ (i+2) % thisPathLength], nextNode ) )
							elif nextNode.type != 65:
								returnList.append( (nextNode, thisNode) )
								if not prevNode in currentSelection:
									returnList.append( ( thisPath.nodes[ (i-2) % thisPathLength], prevNode ) )
						else:
							# a selected on-curve
							if prevNode.type == 65 and not prevNode in currentSelection:
								returnList.append( (thisNode, prevNode) )
								prevPrevNode = thisPath.nodes[ (i-2) ]
								prevPrevPrevNode = thisPath.nodes[ (i-3) ]
								if prevPrevNode not in currentSelection and prevPrevPrevNode not in currentSelection:
									returnList.append( (prevPrevPrevNode, prevPrevNode) )
							if nextNode.type == 65 and not nextNode in currentSelection:
								returnList.append( (thisNode, nextNode) )
								nextNextNode = thisPath.nodes[ (i+2) % thisPathLength ]
								nextNextNextNode = thisPath.nodes[ (i+3) % thisPathLength ]
								if nextNextNode not in currentSelection and nextNextNextNode not in currentSelection:
									returnList.append( (nextNextNextNode, nextNextNode) )

			return list(set(returnList))
		except Exception as e:
			self.logToConsole( "getListOfHandlesToBeMarked_ " + str(e) )

	def markerForPoint( self, thisPoint, markerWidth ):
		"""
		Returns a circle with thisRadius around thisPoint.
		"""
		try:
			myRect = NSRect( ( thisPoint.x - markerWidth * 0.5, thisPoint.y - markerWidth * 0.5 ), ( markerWidth, markerWidth ) )
			return NSBezierPath.bezierPathWithOvalInRect_( myRect )
		except Exception as e:
			self.logToConsole( "markerForPoint_ " + str(e) )

	def drawForegroundForLayer_( self, Layer ):
		"""
		Fills closed outline, outlines handles, and paints nodes.
		"""
		# Components filled
		try:
			NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.0, 0.0, 0.0, 0.7 ).set()
			myComponents = Layer.components
			numberOfMyComponents = len( myComponents )
			for i in range( numberOfMyComponents ):
				myComponentArea = myComponents[i].bezierPath()
				myComponentArea.fill()
		except Exception as e:
			self.logToConsole( "drawForegroundForLayer_: %s" % str(e) )
		# Outlines filled
		try:
			NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.0, 0.0, 0.0, 0.85 ).set()
			Layer.bezierPath().fill()
		except Exception as e:
			self.logToConsole( "drawForegroundForLayer_: %s" % str(e) )

		try:
			NodeSize = self.getNodeSize()
			Scale = self.getScale()
			circleRadius = NodeSize / Scale
			handleStroke = 1.0 / Scale

			# Selected handles lined
			NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.5, 0.5, 0.5, 0.5).set()
			circlesToBeDrawn = NSBezierPath.alloc().init()
			linesToBeDrawn   = NSBezierPath.alloc().init()
			for thisPointPair in self.getListOfHandlesToBeMarked( Layer ):
				fromPoint = thisPointPair[0]
				toPoint   = thisPointPair[1]
				linesToBeDrawn.moveToPoint_( NSPoint(fromPoint.x, fromPoint.y) )
				linesToBeDrawn.lineToPoint_( NSPoint(toPoint.x, toPoint.y) )
				circlesToBeDrawn.appendBezierPath_( self.markerForPoint( toPoint, circleRadius ) )
			linesToBeDrawn.setLineWidth_( handleStroke )
			linesToBeDrawn.stroke()
			circlesToBeDrawn.setLineWidth_( handleStroke )
			circlesToBeDrawn.stroke()

			# Unselected nodes filled
			NSColor.colorWithCalibratedRed_green_blue_alpha_( 1.0, 1.0, 1.0, 0.15 ).set()
			circlesToBeDrawn = NSBezierPath.alloc().init()
			for thisPoint in self.getListOfNodesToBeMarked( Layer ):
				circlesToBeDrawn.appendBezierPath_( self.markerForPoint( thisPoint, circleRadius ) )
			circlesToBeDrawn.fill()

			# Selected Smooth On-curve filled
			NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.0, 0.7, 0.4, 0.3 ).set()
			circlesToBeDrawn = NSBezierPath.alloc().init()
			for thisPoint in self.getListOfSelectedSmooth( Layer ):
				circlesToBeDrawn.appendBezierPath_( self.markerForPoint( thisPoint, circleRadius ) )
			circlesToBeDrawn.fill()

			# Selected Sharp On-Curve filled
			NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.2, 0.4, 0.8, 0.3 ).set()
			circlesToBeDrawn = NSBezierPath.alloc().init()
			for thisPoint in self.getListOfSelectedSharp( Layer ):
				circlesToBeDrawn.appendBezierPath_( self.markerForPoint( thisPoint, circleRadius ) )
			circlesToBeDrawn.fill()

			# Selected Off-curve filled
			NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.5, 0.5, 0.5, 0.2 ).set()
			circlesToBeDrawn = NSBezierPath.alloc().init()
			for thisPoint in self.getListOfSelectedOffCurve( Layer ):
				circlesToBeDrawn.appendBezierPath_( self.markerForPoint( thisPoint, circleRadius ) )
			circlesToBeDrawn.fill()

		except Exception as e:
			self.logToConsole( "drawForegroundForLayer_ " + str(e) )

	def drawBackgroundForLayer_( self, Layer ):
		"""
		Whatever you draw here will be displayed BEHIND the paths.
		"""
		try:
			pass
		except Exception as e:
			self.logToConsole( "drawBackgroundForLayer_: %s" % str(e) )

	def drawBackgroundForInactiveLayer_( self, Layer ):
		"""
		Whatever you draw here will be displayed behind the paths, but for inactive masters.
		"""
		try:
			pass
		except Exception as e:
			self.logToConsole( "drawBackgroundForInactiveLayer_: %s" % str(e) )

	def needsExtraMainOutlineDrawingForInactiveLayer_( self, Layer ):
		"""
		Return False to disable the black outline. Otherwise remove the method.
		"""
		return False

	def getScale( self ):
		"""
		self.getScale() returns the current scale factor of the Edit View UI.
		Divide any scalable size by this value in order to keep the same apparent pixel size.
		"""
		try:
			return self.controller.graphicView().scale()
		except:
			self.logToConsole( "Scale defaulting to 1.0" )
			return 1.0

	def setController_( self, Controller ):
		"""
		Use self.controller as object for the current view controller.
		"""
		try:
			self.controller = Controller
		except Exception as e:
			self.logToConsole( "Could not set controller" )

	def logToConsole( self, message ):
		"""
		The variable 'message' will be passed to Console.app.
		Use self.logToConsole( "bla bla" ) for debugging.
		"""
		myLog = "Show %s plugin:\n%s" % ( self.title(), message )
		NSLog( myLog )
<|endoftext|>


<commit_before>#
#  Copyright 2019 The FATE Authors. All Rights Reserved.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#

import numpy as np
from collections import Iterable
from Cryptodome import Random
from Cryptodome.PublicKey import RSA

# from arch.api.utils import log_utils
from federatedml.secureprotol import gmpy_math
from federatedml.secureprotol.affine import AffineCipher
from federatedml.secureprotol.fate_paillier import PaillierKeypair
from federatedml.secureprotol.random import RandomPads

# LOGGER = log_utils.getLogger()
from federatedml.secureprotol.iterative_affine import IterativeAffineCipher

class Encrypt(object):
    def __init__(self):
        self.public_key = None
        self.privacy_key = None

    def generate_key(self, n_length=0):
        pass

    def set_public_key(self, public_key):
        pass

    def get_public_key(self):
        pass

    def set_privacy_key(self, privacy_key):
        pass

    def get_privacy_key(self):
        pass

    def encrypt(self, value):
        pass

    def decrypt(self, value):
        pass

    def encrypt_list(self, values):
        result = [self.encrypt(msg) for msg in values]
        return result

    def decrypt_list(self, values):
        result = [self.decrypt(msg) for msg in values]
        return result

    def distribute_decrypt(self, X):
        decrypt_table = X.mapValues(lambda x: self.decrypt(x))
        return decrypt_table

    def distribute_encrypt(self, X):
        encrypt_table = X.mapValues(lambda x: self.encrypt(x))
        return encrypt_table

    def _recursive_func(self, obj, func):
        if isinstance(obj, np.ndarray):
            if len(obj.shape) == 1:
                return np.reshape([func(val) for val in obj], obj.shape)
            else:
                return np.reshape([self._recursive_func(o, func) for o in obj], obj.shape)
        elif isinstance(obj, Iterable):
            return type(obj)(
                self._recursive_func(o, func) if isinstance(o, Iterable) else func(o) for o in obj)
        else:
            return func(obj)

    def recursive_encrypt(self, X):
        return self._recursive_func(X, self.encrypt)

    def recursive_decrypt(self, X):
        return self._recursive_func(X, self.decrypt)

class RsaEncrypt(Encrypt):
    def __init__(self):
        super(RsaEncrypt, self).__init__()
        self.e = None
        self.d = None
        self.n = None

    def generate_key(self, rsa_bit=1024):
        random_generator = Random.new().read
        rsa = RSA.generate(rsa_bit, random_generator)
        self.e = rsa.e
        self.d = rsa.d
        self.n = rsa.n

    def get_key_pair(self):
        return self.e, self.d, self.n

    def set_public_key(self, public_key):
        self.e = public_key["e"]
        self.n = public_key["n"]

    def get_public_key(self):
        return self.e, self.n

    def set_privacy_key(self, privacy_key):
        self.d = privacy_key["d"]
        self.n = privacy_key["n"]

    def get_privacy_key(self):
        return self.d, self.n

    def encrypt(self, value):
        if self.e is not None and self.n is not None:
            return gmpy_math.powmod(value, self.e, self.n)
        else:
            return None

    def decrypt(self, value):
        if self.d is not None and self.n is not None:
            return gmpy_math.powmod(value, self.d, self.n)
        else:
            return None

class PaillierEncrypt(Encrypt):
    def __init__(self):
        super(PaillierEncrypt, self).__init__()

    def generate_key(self, n_length=1024):
        self.public_key, self.privacy_key = \
            PaillierKeypair.generate_keypair(n_length=n_length)

    def get_key_pair(self):
        return self.public_key, self.privacy_key

    def set_public_key(self, public_key):
        self.public_key = public_key

    def get_public_key(self):
        return self.public_key

    def set_privacy_key(self, privacy_key):
        self.privacy_key = privacy_key

    def get_privacy_key(self):
        return self.privacy_key

    def encrypt(self, value):
        if self.public_key is not None:
            return self.public_key.encrypt(value)
        else:
            return None

    def decrypt(self, value):
        if self.privacy_key is not None:
            return self.privacy_key.decrypt(value)
        else:
            return None

class FakeEncrypt(Encrypt):
    def encrypt(self, value):
        return value

    def decrypt(self, value):
        return value

class SymmetricEncrypt(object):
    def __init__(self):
        self.key = None

    def encrypt(self, plaintext):
        pass

class AffineEncrypt(SymmetricEncrypt):
    def __init__(self):
        super(AffineEncrypt, self).__init__()

    def generate_key(self, key_size=1024):
        self.key = AffineCipher.generate_keypair(key_size=key_size)

    def encrypt(self, plaintext):
        if self.key is not None:
            return self.key.encrypt(plaintext)
        else:
            return None

    def decrypt(self, ciphertext):
        if self.key is not None:
            return self.key.decrypt(ciphertext)
        else:
            return None

class PadsCipher(Encrypt):

    def __init__(self):
        super().__init__()
        self._uuid = None
        self._rands = None

    def set_self_uuid(self, uuid):
        self._uuid = uuid

    def set_exchanged_keys(self, keys):
        self._seeds = {uid: v & 0xffffffff for uid, v in keys.items() if uid != self._uuid}
        self._rands = {uid: RandomPads(v & 0xffffffff) for uid, v in keys.items() if uid != self._uuid}

    def encrypt(self, value):
        if isinstance(value, np.ndarray):
            ret = value
            for uid, rand in self._rands.items():
                if uid > self._uuid:
                    ret = rand.add_rand_pads(ret, 1.0)
                else:
                    ret = rand.add_rand_pads(ret, -1.0)
            return ret
        else:
            ret = value
            for uid, rand in self._rands.items():
                if uid > self._uuid:
                    ret += rand.rand(1)[0]
                else:
                    ret -= rand.rand(1)[0]
            return ret

    def decrypt(self, value):
        return value

class IterativeAffineEncrypt(SymmetricEncrypt):
    def __init__(self):
        super(IterativeAffineEncrypt, self).__init__()

    def generate_key(self, key_size=1024, key_round=5):
        self.key = IterativeAffineCipher.generate_keypair(key_size=key_size, key_round=key_round)

    def encrypt(self, plaintext):
        if self.key is not None:
            return self.key.encrypt(plaintext)
        else:
            return None

    def decrypt(self, ciphertext):
        if self.key is not None:
            return self.key.decrypt(ciphertext)
        else:
            return None
<commit_msg>modify SymmetricEncrypt to inherits Encrypt for using Encrypt's function interface like recursive_encrypt/decrypt<commit_after>#
#  Copyright 2019 The FATE Authors. All Rights Reserved.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#

import numpy as np
from collections import Iterable
from Cryptodome import Random
from Cryptodome.PublicKey import RSA

# from arch.api.utils import log_utils
from federatedml.secureprotol import gmpy_math
from federatedml.secureprotol.affine import AffineCipher
from federatedml.secureprotol.fate_paillier import PaillierKeypair
from federatedml.secureprotol.random import RandomPads

# LOGGER = log_utils.getLogger()
from federatedml.secureprotol.iterative_affine import IterativeAffineCipher

class Encrypt(object):
    def __init__(self):
        self.public_key = None
        self.privacy_key = None

    def generate_key(self, n_length=0):
        pass

    def set_public_key(self, public_key):
        pass

    def get_public_key(self):
        pass

    def set_privacy_key(self, privacy_key):
        pass

    def get_privacy_key(self):
        pass

    def encrypt(self, value):
        pass

    def decrypt(self, value):
        pass

    def encrypt_list(self, values):
        result = [self.encrypt(msg) for msg in values]
        return result

    def decrypt_list(self, values):
        result = [self.decrypt(msg) for msg in values]
        return result

    def distribute_decrypt(self, X):
        decrypt_table = X.mapValues(lambda x: self.decrypt(x))
        return decrypt_table

    def distribute_encrypt(self, X):
        encrypt_table = X.mapValues(lambda x: self.encrypt(x))
        return encrypt_table

    def _recursive_func(self, obj, func):
        if isinstance(obj, np.ndarray):
            if len(obj.shape) == 1:
                return np.reshape([func(val) for val in obj], obj.shape)
            else:
                return np.reshape([self._recursive_func(o, func) for o in obj], obj.shape)
        elif isinstance(obj, Iterable):
            return type(obj)(
                self._recursive_func(o, func) if isinstance(o, Iterable) else func(o) for o in obj)
        else:
            return func(obj)

    def recursive_encrypt(self, X):
        return self._recursive_func(X, self.encrypt)

    def recursive_decrypt(self, X):
        return self._recursive_func(X, self.decrypt)

class RsaEncrypt(Encrypt):
    def __init__(self):
        super(RsaEncrypt, self).__init__()
        self.e = None
        self.d = None
        self.n = None

    def generate_key(self, rsa_bit=1024):
        random_generator = Random.new().read
        rsa = RSA.generate(rsa_bit, random_generator)
        self.e = rsa.e
        self.d = rsa.d
        self.n = rsa.n

    def get_key_pair(self):
        return self.e, self.d, self.n

    def set_public_key(self, public_key):
        self.e = public_key["e"]
        self.n = public_key["n"]

    def get_public_key(self):
        return self.e, self.n

    def set_privacy_key(self, privacy_key):
        self.d = privacy_key["d"]
        self.n = privacy_key["n"]

    def get_privacy_key(self):
        return self.d, self.n

    def encrypt(self, value):
        if self.e is not None and self.n is not None:
            return gmpy_math.powmod(value, self.e, self.n)
        else:
            return None

    def decrypt(self, value):
        if self.d is not None and self.n is not None:
            return gmpy_math.powmod(value, self.d, self.n)
        else:
            return None

class PaillierEncrypt(Encrypt):
    def __init__(self):
        super(PaillierEncrypt, self).__init__()

    def generate_key(self, n_length=1024):
        self.public_key, self.privacy_key = \
            PaillierKeypair.generate_keypair(n_length=n_length)

    def get_key_pair(self):
        return self.public_key, self.privacy_key

    def set_public_key(self, public_key):
        self.public_key = public_key

    def get_public_key(self):
        return self.public_key

    def set_privacy_key(self, privacy_key):
        self.privacy_key = privacy_key

    def get_privacy_key(self):
        return self.privacy_key

    def encrypt(self, value):
        if self.public_key is not None:
            return self.public_key.encrypt(value)
        else:
            return None

    def decrypt(self, value):
        if self.privacy_key is not None:
            return self.privacy_key.decrypt(value)
        else:
            return None

class FakeEncrypt(Encrypt):
    def encrypt(self, value):
        return value

    def decrypt(self, value):
        return value

class SymmetricEncrypt(Encrypt):
    def __init__(self):
        self.key = None

    def encrypt(self, plaintext):
        pass

class AffineEncrypt(SymmetricEncrypt):
    def __init__(self):
        super(AffineEncrypt, self).__init__()

    def generate_key(self, key_size=1024):
        self.key = AffineCipher.generate_keypair(key_size=key_size)

    def encrypt(self, plaintext):
        if self.key is not None:
            return self.key.encrypt(plaintext)
        else:
            return None

    def decrypt(self, ciphertext):
        if self.key is not None:
            return self.key.decrypt(ciphertext)
        else:
            return None

class PadsCipher(Encrypt):

    def __init__(self):
        super().__init__()
        self._uuid = None
        self._rands = None

    def set_self_uuid(self, uuid):
        self._uuid = uuid

    def set_exchanged_keys(self, keys):
        self._seeds = {uid: v & 0xffffffff for uid, v in keys.items() if uid != self._uuid}
        self._rands = {uid: RandomPads(v & 0xffffffff) for uid, v in keys.items() if uid != self._uuid}

    def encrypt(self, value):
        if isinstance(value, np.ndarray):
            ret = value
            for uid, rand in self._rands.items():
                if uid > self._uuid:
                    ret = rand.add_rand_pads(ret, 1.0)
                else:
                    ret = rand.add_rand_pads(ret, -1.0)
            return ret
        else:
            ret = value
            for uid, rand in self._rands.items():
                if uid > self._uuid:
                    ret += rand.rand(1)[0]
                else:
                    ret -= rand.rand(1)[0]
            return ret

    def decrypt(self, value):
        return value

class IterativeAffineEncrypt(SymmetricEncrypt):
    def __init__(self):
        super(IterativeAffineEncrypt, self).__init__()

    def generate_key(self, key_size=1024, key_round=5):
        self.key = IterativeAffineCipher.generate_keypair(key_size=key_size, key_round=key_round)

    def encrypt(self, plaintext):
        if self.key is not None:
            return self.key.encrypt(plaintext)
        else:
            return None

    def decrypt(self, ciphertext):
        if self.key is not None:
            return self.key.decrypt(ciphertext)
        else:
            return None
<|endoftext|>


<commit_before>__all__ = ['Server']

import socket, threading, os
import pydy_viz
import sys
class Server(threading.Thread):
    """
    A basic Socket server.
    This server is used for fetching
    static files from the pydy_viz
    source and rendering them to
    the browser.

    """
    def __init__(self, json='data.json'):
        """
        Initiate a server instance.

        Parameters
        ==========
        json : str, optional
        path to the saved json file
        for visualization, relative to
        current working directory.

        """
        threading.Thread.__init__(self)
        self.saved_json_file = json
        self.port = 8000
        host = ''
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.socket.bind((host, self.port))
        except:
            self.port+=1
            try:
                self.socket.bind((host, self.port))
            except:
                self.port+=1
                self.socket.bind((host, self.port))
        self.socket.listen(5)

    def _parse_data(self, data):

        static_path = os.path.dirname(pydy_viz.__file__)
        static_path = os.path.join(static_path, 'static')
        request = data.split(' ')[1]
        if request == '/':
        #If requested to http://localhost:port/
        #Send index.html file
            file_path = os.path.join(static_path, 'index.html')
            send_buffer = ''

        elif request == '/data.json':
            print 'data file requested'
        #If data.json is requested, get it from scene method
            file_path = os.path.join(os.getcwd(), self.saved_json_file)
            send_buffer = 'var JSONObj = '

        elif request == '/close-server':
            print "Server closed successfully!"
            self.close()

        else:
        #Else, try to use relative path from url for other files
            file_path_list = request.split('/')
            for val in file_path_list:
                static_path = os.path.join(static_path, val)
            file_path = static_path
            send_buffer = ''

        try:
            send_buffer += open(file_path).read()

        except IOError:
            print '''404 File not found. Sent No Data'''

        return send_buffer

    def listen_once(self):
        conn, addr = self.socket.accept()
        data = conn.recv(1024)
        sent_data = self._parse_data(data)
        conn.send(sent_data)
        return sent_data

    def run(self):
        print 'server started successfully, on port:', self.port

        while 1:
            try:
                self.socket.listen(1)
                conn, addr = self.socket.accept()
                self.data = conn.recv(1024)
                sent_data = self._parse_data(self.data)
                conn.send(sent_data)
                print 'sent data'
                conn.close()
            except KeyboardInterrupt:
                print "Are you sure you want to shutdown[Y/N]?"
                a = raw_input()
                if a == "Y" or a == "y":
                    self.close()
                else:
                    pass

    def close(self):
        self.socket.shutdown(socket.SHUT_RDWR)
        sys.exit()

if __name__ == "__main__":
    a = Server()
    a.run()
<commit_msg>Removed some extra test being printed by server<commit_after>__all__ = ['Server']

import socket, threading, os
import pydy_viz
import sys
class Server(threading.Thread):
    """
    A basic Socket server.
    This server is used for fetching
    static files from the pydy_viz
    source and rendering them to
    the browser.

    """
    def __init__(self, json='data.json'):
        """
        Initiate a server instance.

        Parameters
        ==========
        json : str, optional
        path to the saved json file
        for visualization, relative to
        current working directory.

        """
        threading.Thread.__init__(self)
        self.saved_json_file = json
        self.port = 8000
        host = ''
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.socket.bind((host, self.port))
        except:
            self.port+=1
            try:
                self.socket.bind((host, self.port))
            except:
                self.port+=1
                self.socket.bind((host, self.port))
        self.socket.listen(5)

    def _parse_data(self, data):

        static_path = os.path.dirname(pydy_viz.__file__)
        static_path = os.path.join(static_path, 'static')
        request = data.split(' ')[1]
        if request == '/':
        #If requested to http://localhost:port/
        #Send index.html file
            file_path = os.path.join(static_path, 'index.html')
            send_buffer = ''

        elif request == '/data.json':
            print 'data file requested'
        #If data.json is requested, get it from scene method
            file_path = os.path.join(os.getcwd(), self.saved_json_file)
            send_buffer = 'var JSONObj = '

        elif request == '/close-server':
            print "Server closed successfully!"
            self.close()

        else:
        #Else, try to use relative path from url for other files
            file_path_list = request.split('/')
            for val in file_path_list:
                static_path = os.path.join(static_path, val)
            file_path = static_path
            send_buffer = ''

        try:
            send_buffer += open(file_path).read()

        except IOError:
            print '''404 File not found. Sent No Data'''

        return send_buffer

    def listen_once(self):
        conn, addr = self.socket.accept()
        data = conn.recv(1024)
        sent_data = self._parse_data(data)
        conn.send(sent_data)
        return sent_data

    def run(self):
        print 'server started successfully, on port:', self.port

        while 1:
            try:
                self.socket.listen(1)
                conn, addr = self.socket.accept()
                self.data = conn.recv(1024)
                sent_data = self._parse_data(self.data)
                conn.send(sent_data)
                conn.close()
            except KeyboardInterrupt:
                print "Are you sure you want to shutdown[Y/N]?"
                a = raw_input()
                if a == "Y" or a == "y":
                    self.close()
                else:
                    pass

    def close(self):
        self.socket.shutdown(socket.SHUT_RDWR)
        sys.exit()

if __name__ == "__main__":
    a = Server()
    a.run()
<|endoftext|>


<commit_before># encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""

from __future__ import absolute_import
import abc
from decimal import Decimal

import six

from .converter import NopConverterCreator
from .converter import IntegerConverterCreator
from .converter import FloatConverterCreator
from .converter import BoolConverterCreator
from .converter import DateTimeConverterCreator
from ._error import TypeConversionError
from ._function import is_nan
from ._typecode import Typecode

@six.add_metaclass(abc.ABCMeta)
class TypeCheckerInterface(object):

    @abc.abstractproperty
    def typecode(self):   # pragma: no cover
        pass

    @abc.abstractmethod
    def is_type(self):   # pragma: no cover
        pass

class TypeChecker(TypeCheckerInterface):

    @abc.abstractproperty
    def _converter_creator(self):   # pragma: no cover
        pass

    def __init__(self, value, is_convert=True):
        self._value = value
        self._converted_value = None
        self._is_convert = is_convert

    def is_type(self):
        if self._is_instance():
            return True

        if self._is_exclude_instance():
            return False

        if not self._is_convert:
            return False

        try:
            self._try_convert()
        except TypeConversionError:
            return False

        if not self._is_valid_after_convert():
            return False

        return True

    @abc.abstractmethod
    def _is_instance(self):
        pass

    def _is_exclude_instance(self):
        return False

    def _try_convert(self):
        self._converted_value = self._converter_creator.create(
            self._value).convert()

    def _is_valid_after_convert(self):
        return True

class NoneTypeChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.NONE

    @property
    def _converter_creator(self):
        return NopConverterCreator()

    def _is_instance(self):
        return self._value is None

    def _is_valid_after_convert(self):
        return self._value is None

class IntegerTypeChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.INT

    @property
    def _converter_creator(self):
        return IntegerConverterCreator()

    def _is_instance(self):
        if isinstance(self._value, six.integer_types):
            return not isinstance(self._value, bool)

        return False

    def _is_exclude_instance(self):
        return any([
            isinstance(self._value, bool),
            isinstance(self._value, float),
        ])

class FloatTypeChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.FLOAT

    @property
    def _converter_creator(self):
        return FloatConverterCreator()

    def _is_instance(self):
        return any([
            isinstance(self._value, float),
            isinstance(self._value, Decimal),
            self._value == float("inf"),
        ])

    def _is_exclude_instance(self):
        return isinstance(self._value, bool)

    def _is_valid_after_convert(self):
        return self._converted_value != float("inf")

class BoolTypeChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.BOOL

    @property
    def _converter_creator(self):
        return BoolConverterCreator()

    def _is_instance(self):
        return isinstance(self._value, bool)

    def _is_valid_after_convert(self):
        return isinstance(self._converted_value, bool)

class DateTimeTypeChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.DATETIME

    @property
    def _converter_creator(self):
        return DateTimeConverterCreator()

    def _is_instance(self):
        import datetime

        return isinstance(self._value, datetime.datetime)

class InfinityChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.INFINITY

    @property
    def _converter_creator(self):
        return FloatConverterCreator()

    def _is_instance(self):
        return any([
            self._value == float("inf"),
            self._value == Decimal("inf"),
        ])

    def _is_valid_after_convert(self):
        return self._converted_value == float("inf")

class NanChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.NAN

    @property
    def _converter_creator(self):
        return FloatConverterCreator()

    def _is_instance(self):
        return is_nan(self._value)

    def _is_valid_after_convert(self):
        return is_nan(self._converted_value)
<commit_msg>Delete condition check that no longer needed<commit_after># encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""

from __future__ import absolute_import
import abc
from decimal import Decimal

import six

from .converter import NopConverterCreator
from .converter import IntegerConverterCreator
from .converter import FloatConverterCreator
from .converter import BoolConverterCreator
from .converter import DateTimeConverterCreator
from ._error import TypeConversionError
from ._function import is_nan
from ._typecode import Typecode

@six.add_metaclass(abc.ABCMeta)
class TypeCheckerInterface(object):

    @abc.abstractproperty
    def typecode(self):   # pragma: no cover
        pass

    @abc.abstractmethod
    def is_type(self):   # pragma: no cover
        pass

class TypeChecker(TypeCheckerInterface):

    @abc.abstractproperty
    def _converter_creator(self):   # pragma: no cover
        pass

    def __init__(self, value, is_convert=True):
        self._value = value
        self._converted_value = None
        self._is_convert = is_convert

    def is_type(self):
        if self._is_instance():
            return True

        if self._is_exclude_instance():
            return False

        if not self._is_convert:
            return False

        try:
            self._try_convert()
        except TypeConversionError:
            return False

        if not self._is_valid_after_convert():
            return False

        return True

    @abc.abstractmethod
    def _is_instance(self):
        pass

    def _is_exclude_instance(self):
        return False

    def _try_convert(self):
        self._converted_value = self._converter_creator.create(
            self._value).convert()

    def _is_valid_after_convert(self):
        return True

class NoneTypeChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.NONE

    @property
    def _converter_creator(self):
        return NopConverterCreator()

    def _is_instance(self):
        return self._value is None

    def _is_valid_after_convert(self):
        return self._value is None

class IntegerTypeChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.INT

    @property
    def _converter_creator(self):
        return IntegerConverterCreator()

    def _is_instance(self):
        if isinstance(self._value, six.integer_types):
            return not isinstance(self._value, bool)

        return False

    def _is_exclude_instance(self):
        return any([
            isinstance(self._value, bool),
            isinstance(self._value, float),
        ])

class FloatTypeChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.FLOAT

    @property
    def _converter_creator(self):
        return FloatConverterCreator()

    def _is_instance(self):
        return any([
            isinstance(self._value, float),
            isinstance(self._value, Decimal),
        ])

    def _is_exclude_instance(self):
        return isinstance(self._value, bool)

    def _is_valid_after_convert(self):
        return self._converted_value != float("inf")

class BoolTypeChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.BOOL

    @property
    def _converter_creator(self):
        return BoolConverterCreator()

    def _is_instance(self):
        return isinstance(self._value, bool)

    def _is_valid_after_convert(self):
        return isinstance(self._converted_value, bool)

class DateTimeTypeChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.DATETIME

    @property
    def _converter_creator(self):
        return DateTimeConverterCreator()

    def _is_instance(self):
        import datetime

        return isinstance(self._value, datetime.datetime)

class InfinityChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.INFINITY

    @property
    def _converter_creator(self):
        return FloatConverterCreator()

    def _is_instance(self):
        return any([
            self._value == float("inf"),
            self._value == Decimal("inf"),
        ])

    def _is_valid_after_convert(self):
        return self._converted_value == float("inf")

class NanChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.NAN

    @property
    def _converter_creator(self):
        return FloatConverterCreator()

    def _is_instance(self):
        return is_nan(self._value)

    def _is_valid_after_convert(self):
        return is_nan(self._converted_value)
<|endoftext|>


<commit_before>import csv
import matplotlib.pyplot as plt

queries_by_sf = {}  # SF => Query => [Rows]
with open('results.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        sf = row['sf']
        if sf not in queries_by_sf:
            queries_by_sf[sf] = {}
        query = row['query']
        if query not in queries_by_sf[sf]:
            queries_by_sf[sf][query] = []
        queries_by_sf[sf][query].append(row)

for (sf, queries) in queries_by_sf.items():
    for (query, rows) in queries.items():
        # New figure per (query, sf) combination
        plt.figure()
        f, ax = plt.subplots()

        # Plot raw (#nodes, time) points
        xs = [row['#nodes'] for row in rows]
        ys = [row['time'] for row in rows]
        plt.plot(xs, ys, 'o-')

        # Labels
        plt.title('Query %s Scale Factor %s' % (query, sf))
        plt.xlabel('Number of Nodes')
        plt.ylabel('Time (ms)')

        # Dashed-line and Limits
        max_x = max([int(row['#nodes']) for row in rows])
        max_y = max([int(row['time']) for row in rows])
        plt.plot([0, max_x], [0, max_y], '--k')
        plt.xlim([0, max_x])
        plt.ylim([0, max_y])

        # Save results to file
        plt.savefig('results/plot-query-%s-sf-%s.png' % (query, sf))
<commit_msg>Work in progress on mosaic postprocessing script<commit_after>import csv
#import matplotlib.pyplot as plt

# Compute averages over repeated trials
files = ['mosaic_trial1-small/trials1.csv', 'mosaic_trial2-small/trials2.csv', 'mosaic_trial3-small/trials3.csv']
queries_by_sf = {}  # SF => Query => #Nodes => [Rows]
for path in files:
    with open(path) as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            sf = row['sf']
            if sf not in queries_by_sf:
                queries_by_sf[sf] = {}

            query = row['query']
            if query not in queries_by_sf[sf]:
                queries_by_sf[sf][query] = {}

            nodes = int(row['#nodes'])
            if nodes not in queries_by_sf[sf][query]:
                queries_by_sf[sf][query][nodes] = []
            if row['time'] != '-1':
                queries_by_sf[sf][query][nodes].append(row)

# Group into lines for plotting / Compute averages
lines = {}
for (sf, queries) in sorted(queries_by_sf.items()):
    if sf not in lines:
        lines[sf] = {}
    for (query, nodes) in sorted(queries.items()):
        if query not in lines[sf]:
            lines[sf][query] = []
        for (num, rows) in sorted(nodes.items()):
            avg = float(sum([int(x['time']) for x in rows])) / len(rows) if len(rows) > 0 else 0
            lines[sf][query].append(avg)

for (sf, queries) in sorted(lines.items()):
    print("------- SF %s -----" %sf)
    for (query, avgs) in sorted(queries.items()):
        print("%s: %s" % (query, str(avgs)))

#for (sf, queries) in queries_by_sf.items():
#    for (query, rows) in queries.items():
#        # New figure per (query, sf) combination
#        plt.figure()
#        f, ax = plt.subplots()
#
#        # Plot raw (#nodes, time) points
#        xs = [row['#nodes'] for row in rows]
#        ys = [row['time'] for row in rows]
#        plt.plot(xs, ys, 'o-')
#
#        # Labels
#        plt.title('Query %s Scale Factor %s' % (query, sf))
#        plt.xlabel('Number of Nodes')
#        plt.ylabel('Time (ms)')
#
#        # Dashed-line and Limits
#        max_x = max([int(row['#nodes']) for row in rows])
#        max_y = max([int(row['time']) for row in rows])
#        plt.plot([0, max_x], [0, max_y], '--k')
#        plt.xlim([0, max_x])
#        plt.ylim([0, max_y])
#
#        # Save results to file
#        plt.savefig('results/plot-query-%s-sf-%s.png' % (query, sf))
<|endoftext|>


<commit_before>import discord
from discord.ext import commands

from utils import checks

class Moderation:

    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    @checks.perms_ban()
    async def ban(self, ctx, user: discord.Member, delete_days=1):
        """Bans a user from the guild"""
        self.bot.cmd_log(ctx, "ban")
        if delete_days > 7:
            delete_days = 7
        if user:
            await ctx.guild.ban(user, delete_message_days=delete_days)
            self.bot.log.notice("Kicked {} from {}".format(user, ctx.guild.name))

    @commands.command()
    @checks.perms_ban()
    async def xban(self, ctx, user_id: int):
        """Allows the banning of a user not int he guild via ID"""
        # Stolen from Joku
        # k thnx Laura
        # https://github.com/SunDwarf/Jokusoramame/blob/master/joku/cogs/mod.py#L135
        try:
            await ctx.bot.http.ban(user_id, ctx.message.guild.id, 0)
        except discord.Forbidden:
            await ctx.channel.send(":x: 403 FORBIDDEN")
        except discord.NotFound:
            await ctx.channel.send(":x: User not found.")
        else:
            await ctx.channel.send(":negative_squared_cross_mark:  Banned user {}.".format(user_id))

    @commands.command()
    @checks.perms_kick()
    async def kick(self, ctx, user: discord.Member):
        """Kicks a user from the guild"""
        if user:
            await ctx.guild.kick(user)
            self.bot.log.notice("Kicked {} from {}".format(user, ctx.guild.name))

    @commands.command()
    @checks.perms_manage_messages()
    async def purge(self, ctx, limit: int, user: discord.Member = None):
        """Purges messages from a channel"""
        def predicate(m):
            return m.author == user
        if ctx.message.author.id != 95953002774413312:
            if limit > 100:
                limit = 100
        if user is None:
            messages = await ctx.channel.purge(limit=limit, check=None)
            await ctx.send("Purged {} messages in #{}".format(len(messages), ctx.channel))
            self.bot.log.notice("Purged {} messages in #{}".format(len(messages), ctx.channel))
        else:
            messages = await ctx.channel.purge(limit=limit, check=predicate)
            await ctx.send("Purged {} messages from {} in #{}".format(len(messages), user, ctx.channel))
            self.bot.log.notice("Purged {} messages from {} in #{}".format(len(messages), user, ctx.channel))

    @commands.group(invoke_without_command=True)
    @checks.perms_manage_messages()
    async def mute(self, ctx, user: discord.Member):
        """Mutes a user"""
        guild_settings = await self.bot.get_server_data(ctx.guild.id)
        if guild_settings["mute_role"] == "":
            await ctx.send("No mute role set! Please set one with $mute role <role>")
            return
        if user is None:
            await ctx.send("Not a valid user")
            return
        if user.top_role.position >= ctx.author.top_role.position:
            return
        mute_role = None
        for role in ctx.guild.roles:
            if role.id == int(guild_settings["mute_role"]):
                mute_role = role
        if mute_role is None:
            return
        if mute_role is None:
            await ctx.send("Invalid mute role")
            return
        if mute_role in user.roles:
            roles = user.roles
            roles.remove(mute_role)
            await user.edit(roles=roles)
            await ctx.send("`{}` -> :100:".format(user))
        else:
            roles = user.roles
            roles.append(mute_role)
            await user.edit(roles=roles)
            await ctx.send("`{}` -> :speak_no_evil:".format(user))

    @mute.command()
    @checks.perms_manage_messages()
    async def role(self, ctx, role: discord.Role = None):
        if role is None:
            return
        if role.position >= ctx.author.top_role.position:
            await ctx.send("Unable to add role due to Hierarchy")
        else:
            guild_settings = await self.bot.get_server_data(ctx.guild.id)
            guild_settings["mute_role"] = role.id
            await self.bot.update_server_data(ctx.guild.id, guild_settings)
            await ctx.send("Set the guilds mute role")

    async def on_guild_role_delete(self, role):
        guild = role.guild
        guild_data = await self.bot.get_server_data(guild.id)
        mute_role = guild_data["mute_role"]
        if mute_role == role.id:
            guild_data["mute_role"] = ""
            await self.bot.update_server_data(guild.id, guild_data)

def setup(bot):
    bot.add_cog(Moderation(bot))
<commit_msg>AAAAAAAAAAAAAAAAAAA<commit_after>import discord
from discord.ext import commands

from utils import checks

class Moderation:

    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    @checks.perms_ban()
    async def ban(self, ctx, user: discord.Member, delete_days=1):
        """Bans a user from the guild"""
        if delete_days > 7:
            delete_days = 7
        if user:
            await ctx.guild.ban(user, delete_message_days=delete_days)
            self.bot.log.notice("Kicked {} from {}".format(user, ctx.guild.name))

    @commands.command()
    @checks.perms_ban()
    async def xban(self, ctx, user_id: int):
        """Allows the banning of a user not int he guild via ID"""
        # Stolen from Joku
        # k thnx Laura
        # https://github.com/SunDwarf/Jokusoramame/blob/master/joku/cogs/mod.py#L135
        try:
            await ctx.bot.http.ban(user_id, ctx.message.guild.id, 0)
        except discord.Forbidden:
            await ctx.channel.send(":x: 403 FORBIDDEN")
        except discord.NotFound:
            await ctx.channel.send(":x: User not found.")
        else:
            await ctx.channel.send(":negative_squared_cross_mark:  Banned user {}.".format(user_id))

    @commands.command()
    @checks.perms_kick()
    async def kick(self, ctx, user: discord.Member):
        """Kicks a user from the guild"""
        if user:
            await ctx.guild.kick(user)
            self.bot.log.notice("Kicked {} from {}".format(user, ctx.guild.name))

    @commands.command()
    @checks.perms_manage_messages()
    async def purge(self, ctx, limit: int, user: discord.Member = None):
        """Purges messages from a channel"""
        def predicate(m):
            return m.author == user
        if ctx.message.author.id != 95953002774413312:
            if limit > 100:
                limit = 100
        if user is None:
            messages = await ctx.channel.purge(limit=limit, check=None)
            await ctx.send("Purged {} messages in #{}".format(len(messages), ctx.channel))
            self.bot.log.notice("Purged {} messages in #{}".format(len(messages), ctx.channel))
        else:
            messages = await ctx.channel.purge(limit=limit, check=predicate)
            await ctx.send("Purged {} messages from {} in #{}".format(len(messages), user, ctx.channel))
            self.bot.log.notice("Purged {} messages from {} in #{}".format(len(messages), user, ctx.channel))

    @commands.group(invoke_without_command=True)
    @checks.perms_manage_messages()
    async def mute(self, ctx, user: discord.Member):
        """Mutes a user"""
        guild_settings = await self.bot.get_server_data(ctx.guild.id)
        if guild_settings["mute_role"] == "":
            await ctx.send("No mute role set! Please set one with $mute role <role>")
            return
        if user is None:
            await ctx.send("Not a valid user")
            return
        if user.top_role.position >= ctx.author.top_role.position:
            return
        mute_role = None
        for role in ctx.guild.roles:
            if role.id == int(guild_settings["mute_role"]):
                mute_role = role
        if mute_role is None:
            return
        if mute_role is None:
            await ctx.send("Invalid mute role")
            return
        if mute_role in user.roles:
            roles = user.roles
            roles.remove(mute_role)
            await user.edit(roles=roles)
            await ctx.send("`{}` -> :100:".format(user))
        else:
            roles = user.roles
            roles.append(mute_role)
            await user.edit(roles=roles)
            await ctx.send("`{}` -> :speak_no_evil:".format(user))

    @mute.command()
    @checks.perms_manage_messages()
    async def role(self, ctx, role: discord.Role = None):
        if role is None:
            return
        if role.position >= ctx.author.top_role.position:
            await ctx.send("Unable to add role due to Hierarchy")
        else:
            guild_settings = await self.bot.get_server_data(ctx.guild.id)
            guild_settings["mute_role"] = role.id
            await self.bot.update_server_data(ctx.guild.id, guild_settings)
            await ctx.send("Set the guilds mute role")

    async def on_guild_role_delete(self, role):
        guild = role.guild
        guild_data = await self.bot.get_server_data(guild.id)
        mute_role = guild_data["mute_role"]
        if mute_role == role.id:
            guild_data["mute_role"] = ""
            await self.bot.update_server_data(guild.id, guild_data)

def setup(bot):
    bot.add_cog(Moderation(bot))
<|endoftext|>


<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015 Ministerio de Fomento
#                    Instituto de Ciencias de la Construcción Eduardo Torroja (IETcc-CSIC)
#
# 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.

"""Default values for energy efficiency calculation

These are aimed towards energy efficiency evaluation in the spanish
building code regulations (Código Técnico de la Edificación CTE).

Weighting factors are based on primary energy use.
"""

import pandas as pd

# These are all provisional values subject to change

K_EXP = 1.0

K_RDEL = 1.0

# FpA - weighting factors accounting for the resources used to produce this energy
# FpB - weighting factors accounting for the resources avoided by the external grid due to the export
FACTORESDEPASO = [
#  Energy carrier         origin          use         step Fpren  Fpnren
    ['ELECTRICIDAD',        'grid',         'input',    'A', 0.414, 1.954], # Delivered energy
    ['ELECTRICIDAD',        'INSITU',       'input',    'A', 1.000, 0.000], # Produced energy
    ['ELECTRICIDAD',        'INSITU',       'to_grid',  'A', 1.000, 0.000], # Produced and exported to the grid
    ['ELECTRICIDAD',        'INSITU',       'to_nEPB',  'A', 1.000, 0.000], # Produced and exported to nEPB uses
    ['ELECTRICIDAD',        'INSITU',       'to_grid',  'B', 0.414, 1.954], # Savings to the grid due to produced and exported to the grid energy
    ['ELECTRICIDAD',        'INSITU',       'to_nEPB',  'B', 0.414, 1.954], # Savings to the grid due to produced and exported to nEPB uses
    ['ELECTRICIDAD',        'COGENERACION', 'input',    'A', 0.000, 0.000], # There is no delivery from grid for this carrier
    ['ELECTRICIDAD',        'COGENERACION', 'to_grid',  'A', 0.000, 2.500], # User defined!
    ['ELECTRICIDAD',        'COGENERACION', 'to_nEPB',  'A', 0.000, 2.500], # User defined!
    ['ELECTRICIDAD',        'COGENERACION', 'to_grid',  'B', 0.414, 1.954], # Savings to the grid when exporting to the grid
    ['ELECTRICIDAD',        'COGENERACION', 'to_nEPB',  'B', 0.414, 1.954], # Savings to the grid when exporting to nEPB uses

    ['ELECTRICIDADBALEARES','grid',         'input',    'A', 0.082, 2.968], # Delivered energy
    ['ELECTRICIDADBALEARES','INSITU',       'input',    'A', 1.000, 0.000], # Produced energy
    ['ELECTRICIDADBALEARES','INSITU',       'to_grid',  'A', 1.000, 0.000], # Produced and exported to the grid
    ['ELECTRICIDADBALEARES','INSITU',       'to_nEPB',  'A', 1.000, 0.000], # Produced and exported to nEPB uses
    ['ELECTRICIDADBALEARES','INSITU',       'to_grid',  'B', 0.082, 2.968], # Savings to the grid due to produced and exported to the grid energy
    ['ELECTRICIDADBALEARES','INSITU',       'to_nEPB',  'B', 0.082, 2.968], # Savings to the grid due to produced and exported to nEPB uses
    ['ELECTRICIDADBALEARES','COGENERACION', 'input',    'A', 0.000, 0.000], # There is no delivery from grid for this carrier
    ['ELECTRICIDADBALEARES','COGENERACION', 'to_grid',  'A', 0.000, 2.500], # User defined!
    ['ELECTRICIDADBALEARES','COGENERACION', 'to_nEPB',  'A', 0.000, 2.500], # User defined!
    ['ELECTRICIDADBALEARES','COGENERACION', 'to_grid',  'B', 0.082, 2.968], # Savings to the grid when exporting to the grid
    ['ELECTRICIDADBALEARES','COGENERACION', 'to_nEPB',  'B', 0.082, 2.968], # Savings to the grid when exporting to nEPB uses

    ['ELECTRICIDADCANARIAS','grid',         'input',    'A', 0.070, 2.924], # Delivered energy
    ['ELECTRICIDADCANARIAS','INSITU',       'input',    'A', 1.000, 0.000], # Produced energy
    ['ELECTRICIDADCANARIAS','INSITU',       'to_grid',  'A', 1.000, 0.000], # Produced and exported to the grid
    ['ELECTRICIDADCANARIAS','INSITU',       'to_nEPB',  'A', 1.000, 0.000], # Produced and exported to nEPB uses
    ['ELECTRICIDADCANARIAS','INSITU',       'to_grid',  'B', 0.070, 2.924], # Savings to the grid due to produced and exported to the grid energy
    ['ELECTRICIDADCANARIAS','INSITU',       'to_nEPB',  'B', 0.070, 2.924], # Savings to the grid due to produced and exported to nEPB uses
    ['ELECTRICIDADCANARIAS','COGENERACION', 'input',    'A', 0.000, 0.000], # There is no delivery from grid for this carrier
    ['ELECTRICIDADCANARIAS','COGENERACION', 'to_grid',  'A', 0.000, 2.500], # User defined!
    ['ELECTRICIDADCANARIAS','COGENERACION', 'to_nEPB',  'A', 0.000, 2.500], # User defined!
    ['ELECTRICIDADCANARIAS','COGENERACION', 'to_grid',  'B', 0.070, 2.924], # Savings to the grid when exporting to the grid
    ['ELECTRICIDADCANARIAS','COGENERACION', 'to_nEPB',  'B', 0.070, 2.924], # Savings to the grid when exporting to nEPB uses

    ['ELECTRICIDADCEUTAMELILLA','grid',     'input',    'A', 0.072, 2.718], # Delivered energy
    ['ELECTRICIDADCEUTAMELILLA','INSITU',   'input',    'A', 1.000, 0.000], # Produced energy
    ['ELECTRICIDADCEUTAMELILLA','INSITU',   'to_grid',  'A', 1.000, 0.000], # Produced and exported to the grid
    ['ELECTRICIDADCEUTAMELILLA','INSITU',   'to_nEPB',  'A', 1.000, 0.000], # Produced and exported to nEPB uses
    ['ELECTRICIDADCEUTAMELILLA','INSITU',   'to_grid',  'B', 0.072, 2.718], # Savings to the grid due to produced and exported to the grid energy
    ['ELECTRICIDADCEUTAMELILLA','INSITU',   'to_nEPB',  'B', 0.072, 2.718], # Savings to the grid due to produced and exported to nEPB uses
    ['ELECTRICIDADCEUTAMELILLA','COGENERACION','input', 'A', 0.000, 0.000], # There is no delivery from grid for this carrier
    ['ELECTRICIDADCEUTAMELILLA','COGENERACION','to_grid','A', 0.000, 2.500], # User defined!
    ['ELECTRICIDADCEUTAMELILLA','COGENERACION','to_nEPB','A', 0.000, 2.500], # User defined!
    ['ELECTRICIDADCEUTAMELILLA','COGENERACION','to_grid','B', 0.072, 2.718], # Savings to the grid when exporting to the grid
    ['ELECTRICIDADCEUTAMELILLA','COGENERACION','to_nEPB','B', 0.072, 2.718], # Savings to the grid when exporting to nEPB uses

    ['MEDIOAMBIENTE',       'grid',         'input',    'A', 1.000, 0.000], # Grid is able to deliver this carrier
    ['MEDIOAMBIENTE',       'INSITU',       'input',    'A', 1.000, 0.000], # in-situ production of this carrier
    ['MEDIOAMBIENTE',       'INSITU',       'to_grid',  'A', 0.000, 0.000], # export to grid is not accounted for
    ['MEDIOAMBIENTE',       'INSITU',       'to_nEPB',  'A', 1.000, 0.000], # export to nEPB uses in step A
    ['MEDIOAMBIENTE',       'INSITU',       'to_grid',  'B', 0.000, 0.000], # Savings to the grid when exporting to grid
    ['MEDIOAMBIENTE',       'INSITU',       'to_nEPB',  'B', 1.000, 0.000], # Savings to the grid when exporting to nEPB uses

    # BIOCARBURANTE == BIOMASA DENSIFICADA (PELLETS)
    ['BIOCARBURANTE',       'grid',         'input',    'A', 1.028, 0.085], # Delivered energy
    ['BIOMASA',             'grid',         'input',    'A', 1.003, 0.034], # Delivered energy
    ['BIOMASADENSIFICADA',  'grid',         'input',    'A', 1.028, 0.085], # Delivered energy
    ['CARBON',              'grid',         'input',    'A', 0.002, 1.082], # Delivered energy
    # FUELOIL == GASOLEO
    ['FUELOIL',             'grid',         'input',    'A', 0.003, 1.179], # Delivered energy
    ['GASNATURAL',          'grid',         'input',    'A', 0.005, 1.190], # Delivered energy
    ['GASOLEO',             'grid',         'input',    'A', 0.003, 1.179], # Delivered energy
    ['GLP',                 'grid',         'input',    'A', 0.030, 1.201], # Delivered energy
    ['RED1',                'grid',         'input',    'A', 0.000, 1.300], # User defined!, district heating/cooling carrier
    ['RED2',                'grid',         'input',    'A', 0.000, 1.300], # User defined!, district heating/cooling carrier
]

FACTORESDEPASOOFICIALES = pd.DataFrame(
    FACTORESDEPASO,
    columns=['vector', 'fuente', 'uso', 'step', 'ren', 'nren'])
<commit_msg>settings: usa kexp=0, krdel=0<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015 Ministerio de Fomento
#                    Instituto de Ciencias de la Construcción Eduardo Torroja (IETcc-CSIC)
#
# 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.

"""Default values for energy efficiency calculation

These are aimed towards energy efficiency evaluation in the spanish
building code regulations (Código Técnico de la Edificación CTE).

Weighting factors are based on primary energy use.
"""

import pandas as pd

# These are all provisional values subject to change

K_EXP = 0.0

K_RDEL = 0.0

# FpA - weighting factors accounting for the resources used to produce this energy
# FpB - weighting factors accounting for the resources avoided by the external grid due to the export
FACTORESDEPASO = [
#  Energy carrier         origin          use         step Fpren  Fpnren
    ['ELECTRICIDAD',        'grid',         'input',    'A', 0.414, 1.954], # Delivered energy
    ['ELECTRICIDAD',        'INSITU',       'input',    'A', 1.000, 0.000], # Produced energy
    ['ELECTRICIDAD',        'INSITU',       'to_grid',  'A', 1.000, 0.000], # Produced and exported to the grid
    ['ELECTRICIDAD',        'INSITU',       'to_nEPB',  'A', 1.000, 0.000], # Produced and exported to nEPB uses
    ['ELECTRICIDAD',        'INSITU',       'to_grid',  'B', 0.414, 1.954], # Savings to the grid due to produced and exported to the grid energy
    ['ELECTRICIDAD',        'INSITU',       'to_nEPB',  'B', 0.414, 1.954], # Savings to the grid due to produced and exported to nEPB uses
    ['ELECTRICIDAD',        'COGENERACION', 'input',    'A', 0.000, 0.000], # There is no delivery from grid for this carrier
    ['ELECTRICIDAD',        'COGENERACION', 'to_grid',  'A', 0.000, 2.500], # User defined!
    ['ELECTRICIDAD',        'COGENERACION', 'to_nEPB',  'A', 0.000, 2.500], # User defined!
    ['ELECTRICIDAD',        'COGENERACION', 'to_grid',  'B', 0.414, 1.954], # Savings to the grid when exporting to the grid
    ['ELECTRICIDAD',        'COGENERACION', 'to_nEPB',  'B', 0.414, 1.954], # Savings to the grid when exporting to nEPB uses

    ['ELECTRICIDADBALEARES','grid',         'input',    'A', 0.082, 2.968], # Delivered energy
    ['ELECTRICIDADBALEARES','INSITU',       'input',    'A', 1.000, 0.000], # Produced energy
    ['ELECTRICIDADBALEARES','INSITU',       'to_grid',  'A', 1.000, 0.000], # Produced and exported to the grid
    ['ELECTRICIDADBALEARES','INSITU',       'to_nEPB',  'A', 1.000, 0.000], # Produced and exported to nEPB uses
    ['ELECTRICIDADBALEARES','INSITU',       'to_grid',  'B', 0.082, 2.968], # Savings to the grid due to produced and exported to the grid energy
    ['ELECTRICIDADBALEARES','INSITU',       'to_nEPB',  'B', 0.082, 2.968], # Savings to the grid due to produced and exported to nEPB uses
    ['ELECTRICIDADBALEARES','COGENERACION', 'input',    'A', 0.000, 0.000], # There is no delivery from grid for this carrier
    ['ELECTRICIDADBALEARES','COGENERACION', 'to_grid',  'A', 0.000, 2.500], # User defined!
    ['ELECTRICIDADBALEARES','COGENERACION', 'to_nEPB',  'A', 0.000, 2.500], # User defined!
    ['ELECTRICIDADBALEARES','COGENERACION', 'to_grid',  'B', 0.082, 2.968], # Savings to the grid when exporting to the grid
    ['ELECTRICIDADBALEARES','COGENERACION', 'to_nEPB',  'B', 0.082, 2.968], # Savings to the grid when exporting to nEPB uses

    ['ELECTRICIDADCANARIAS','grid',         'input',    'A', 0.070, 2.924], # Delivered energy
    ['ELECTRICIDADCANARIAS','INSITU',       'input',    'A', 1.000, 0.000], # Produced energy
    ['ELECTRICIDADCANARIAS','INSITU',       'to_grid',  'A', 1.000, 0.000], # Produced and exported to the grid
    ['ELECTRICIDADCANARIAS','INSITU',       'to_nEPB',  'A', 1.000, 0.000], # Produced and exported to nEPB uses
    ['ELECTRICIDADCANARIAS','INSITU',       'to_grid',  'B', 0.070, 2.924], # Savings to the grid due to produced and exported to the grid energy
    ['ELECTRICIDADCANARIAS','INSITU',       'to_nEPB',  'B', 0.070, 2.924], # Savings to the grid due to produced and exported to nEPB uses
    ['ELECTRICIDADCANARIAS','COGENERACION', 'input',    'A', 0.000, 0.000], # There is no delivery from grid for this carrier
    ['ELECTRICIDADCANARIAS','COGENERACION', 'to_grid',  'A', 0.000, 2.500], # User defined!
    ['ELECTRICIDADCANARIAS','COGENERACION', 'to_nEPB',  'A', 0.000, 2.500], # User defined!
    ['ELECTRICIDADCANARIAS','COGENERACION', 'to_grid',  'B', 0.070, 2.924], # Savings to the grid when exporting to the grid
    ['ELECTRICIDADCANARIAS','COGENERACION', 'to_nEPB',  'B', 0.070, 2.924], # Savings to the grid when exporting to nEPB uses

    ['ELECTRICIDADCEUTAMELILLA','grid',     'input',    'A', 0.072, 2.718], # Delivered energy
    ['ELECTRICIDADCEUTAMELILLA','INSITU',   'input',    'A', 1.000, 0.000], # Produced energy
    ['ELECTRICIDADCEUTAMELILLA','INSITU',   'to_grid',  'A', 1.000, 0.000], # Produced and exported to the grid
    ['ELECTRICIDADCEUTAMELILLA','INSITU',   'to_nEPB',  'A', 1.000, 0.000], # Produced and exported to nEPB uses
    ['ELECTRICIDADCEUTAMELILLA','INSITU',   'to_grid',  'B', 0.072, 2.718], # Savings to the grid due to produced and exported to the grid energy
    ['ELECTRICIDADCEUTAMELILLA','INSITU',   'to_nEPB',  'B', 0.072, 2.718], # Savings to the grid due to produced and exported to nEPB uses
    ['ELECTRICIDADCEUTAMELILLA','COGENERACION','input', 'A', 0.000, 0.000], # There is no delivery from grid for this carrier
    ['ELECTRICIDADCEUTAMELILLA','COGENERACION','to_grid','A', 0.000, 2.500], # User defined!
    ['ELECTRICIDADCEUTAMELILLA','COGENERACION','to_nEPB','A', 0.000, 2.500], # User defined!
    ['ELECTRICIDADCEUTAMELILLA','COGENERACION','to_grid','B', 0.072, 2.718], # Savings to the grid when exporting to the grid
    ['ELECTRICIDADCEUTAMELILLA','COGENERACION','to_nEPB','B', 0.072, 2.718], # Savings to the grid when exporting to nEPB uses

    ['MEDIOAMBIENTE',       'grid',         'input',    'A', 1.000, 0.000], # Grid is able to deliver this carrier
    ['MEDIOAMBIENTE',       'INSITU',       'input',    'A', 1.000, 0.000], # in-situ production of this carrier
    ['MEDIOAMBIENTE',       'INSITU',       'to_grid',  'A', 0.000, 0.000], # export to grid is not accounted for
    ['MEDIOAMBIENTE',       'INSITU',       'to_nEPB',  'A', 1.000, 0.000], # export to nEPB uses in step A
    ['MEDIOAMBIENTE',       'INSITU',       'to_grid',  'B', 0.000, 0.000], # Savings to the grid when exporting to grid
    ['MEDIOAMBIENTE',       'INSITU',       'to_nEPB',  'B', 1.000, 0.000], # Savings to the grid when exporting to nEPB uses

    # BIOCARBURANTE == BIOMASA DENSIFICADA (PELLETS)
    ['BIOCARBURANTE',       'grid',         'input',    'A', 1.028, 0.085], # Delivered energy
    ['BIOMASA',             'grid',         'input',    'A', 1.003, 0.034], # Delivered energy
    ['BIOMASADENSIFICADA',  'grid',         'input',    'A', 1.028, 0.085], # Delivered energy
    ['CARBON',              'grid',         'input',    'A', 0.002, 1.082], # Delivered energy
    # FUELOIL == GASOLEO
    ['FUELOIL',             'grid',         'input',    'A', 0.003, 1.179], # Delivered energy
    ['GASNATURAL',          'grid',         'input',    'A', 0.005, 1.190], # Delivered energy
    ['GASOLEO',             'grid',         'input',    'A', 0.003, 1.179], # Delivered energy
    ['GLP',                 'grid',         'input',    'A', 0.030, 1.201], # Delivered energy
    ['RED1',                'grid',         'input',    'A', 0.000, 1.300], # User defined!, district heating/cooling carrier
    ['RED2',                'grid',         'input',    'A', 0.000, 1.300], # User defined!, district heating/cooling carrier
]

FACTORESDEPASOOFICIALES = pd.DataFrame(
    FACTORESDEPASO,
    columns=['vector', 'fuente', 'uso', 'step', 'ren', 'nren'])
<|endoftext|>


<commit_before># encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""

from __future__ import absolute_import
import abc

import six

from .converter import NoneConverterCreator
from .converter import IntegerConverterCreator
from .converter import FloatConverterCreator
from .converter import DateTimeConverterCreator
from ._error import TypeConversionError
from ._typecode import Typecode

@six.add_metaclass(abc.ABCMeta)
class TypeCheckerInterface(object):

    @abc.abstractproperty
    def typecode(self):   # pragma: no cover
        pass

    @abc.abstractmethod
    def is_type(self):   # pragma: no cover
        pass

class TypeChecker(TypeCheckerInterface):

    @abc.abstractproperty
    def creator(self):   # pragma: no cover
        pass

    def __init__(self, value, is_convert=True):
        self._value = value
        self._converted_value = None
        self._is_convert = is_convert

    def is_type(self):
        if self._is_instance():
            return True

        if self._is_exclude_instance():
            return False

        if not self._is_convert:
            return False

        try:
            self._try_convert()
        except TypeConversionError:
            return False

        if not self._is_valid_after_convert():
            return False

        return True

    @abc.abstractmethod
    def _is_instance(self):
        pass

    def _is_exclude_instance(self):
        return False

    def _try_convert(self):
        self._converted_value = self.creator.create(self._value).convert()

    def _is_valid_after_convert(self):
        return True

class NoneTypeChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.NONE

    @property
    def creator(self):
        return NoneConverterCreator()

    def _is_instance(self):
        return self._value is None

class IntegerTypeChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.INT

    @property
    def creator(self):
        return IntegerConverterCreator()

    def _is_instance(self):
        if isinstance(self._value, six.integer_types):
            return not isinstance(self._value, bool)

        return False

    def _is_exclude_instance(self):
        return any([
            isinstance(self._value, bool),
            isinstance(self._value, float),
        ])

    def _is_valid_after_convert(self):
        return True

class FloatTypeChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.FLOAT

    @property
    def creator(self):
        return FloatConverterCreator()

    def _is_instance(self):
        return any(
            [isinstance(self._value, float), self._value == float("inf")])

    def _is_exclude_instance(self):
        return isinstance(self._value, bool)

    def _is_valid_after_convert(self):
        return self._converted_value != float("inf")

class DateTimeTypeChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.DATETIME

    @property
    def creator(self):
        return DateTimeConverterCreator()

    def _is_instance(self):
        import datetime

        return isinstance(self._value, datetime.datetime)
<commit_msg>Fix NoneTypeChecker<commit_after># encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""

from __future__ import absolute_import
import abc

import six

from .converter import NoneConverterCreator
from .converter import IntegerConverterCreator
from .converter import FloatConverterCreator
from .converter import DateTimeConverterCreator
from ._error import TypeConversionError
from ._typecode import Typecode

@six.add_metaclass(abc.ABCMeta)
class TypeCheckerInterface(object):

    @abc.abstractproperty
    def typecode(self):   # pragma: no cover
        pass

    @abc.abstractmethod
    def is_type(self):   # pragma: no cover
        pass

class TypeChecker(TypeCheckerInterface):

    @abc.abstractproperty
    def creator(self):   # pragma: no cover
        pass

    def __init__(self, value, is_convert=True):
        self._value = value
        self._converted_value = None
        self._is_convert = is_convert

    def is_type(self):
        if self._is_instance():
            return True

        if self._is_exclude_instance():
            return False

        if not self._is_convert:
            return False

        try:
            self._try_convert()
        except TypeConversionError:
            return False

        if not self._is_valid_after_convert():
            return False

        return True

    @abc.abstractmethod
    def _is_instance(self):
        pass

    def _is_exclude_instance(self):
        return False

    def _try_convert(self):
        self._converted_value = self.creator.create(self._value).convert()

    def _is_valid_after_convert(self):
        return True

class NoneTypeChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.NONE

    @property
    def creator(self):
        return NoneConverterCreator()

    def _is_instance(self):
        return self._value is None

    def _is_valid_after_convert(self):
        return self._value is None

class IntegerTypeChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.INT

    @property
    def creator(self):
        return IntegerConverterCreator()

    def _is_instance(self):
        if isinstance(self._value, six.integer_types):
            return not isinstance(self._value, bool)

        return False

    def _is_exclude_instance(self):
        return any([
            isinstance(self._value, bool),
            isinstance(self._value, float),
        ])

    def _is_valid_after_convert(self):
        return True

class FloatTypeChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.FLOAT

    @property
    def creator(self):
        return FloatConverterCreator()

    def _is_instance(self):
        return any(
            [isinstance(self._value, float), self._value == float("inf")])

    def _is_exclude_instance(self):
        return isinstance(self._value, bool)

    def _is_valid_after_convert(self):
        return self._converted_value != float("inf")

class DateTimeTypeChecker(TypeChecker):

    @property
    def typecode(self):
        return Typecode.DATETIME

    @property
    def creator(self):
        return DateTimeConverterCreator()

    def _is_instance(self):
        import datetime

        return isinstance(self._value, datetime.datetime)
<|endoftext|>