<commit_before># -*- coding: utf-8 -*-
from collections import defaultdict
from hackarena.player import Player
from hackarena.spell import Spell
from hackarena.team import Team
from hackarena.messages import AllMainBroadcast
from hackarena.messages import FEMessages
from hackarena.messages import WelcomeBroadcast
from hackarena.utilities import Utilities
from hackarena.constants import MAP_TILES_WIDTH
from hackarena.constants import MAP_TILES_HEIGHT
from hackarena.constants import MAP_TILE_SIZE
from hackarena.constants import MAP_OBSTACLES
from sockjs.tornado import SockJSConnection
import hackarena.constants
import itertools
import json
import time

class WebSocketHandler(SockJSConnection):

    clients = defaultdict(dict)
    teams = {}
    players = {}
    spells = []

    @property
    def player(self):
        return self.players[self.session_string]

    @player.setter
    def player(self, player):
        self.players[self.session_string] = player

    @property
    def room(self):
        try:
            return self.player.room
        except:
            return hackarena.constants.DEFAULT_ROOM

    @room.setter
    def room(self, room):
        self.player.room = room

    def on_open(self, info):
        self.session_string = Utilities.get_session_string(str(self.session))

        self.clients[self.room][self.session_string] = self
        WelcomeBroadcast(message='Welcome to HackArena!').send(self)
        WelcomeBroadcast(message='Welcome to HackArena! (to all)').broadcast_to_all(self)

    def on_close(self):
        self.teams[self.room][self.player.team].remove_player(self.player)

        self.broadcast_game_state()

        del self.players[self.session_string]
        del self.clients[self.room][self.session_string]

    def on_message(self, message):
        try:
            data = json.loads(message)
        except:
            print 'Received unsupported message type'
            return

        if data['type'] == FEMessages.FE_JOIN_ROOM:
            new_room = data['content']['room']
            self.player = Player(
                username=data['content']['username'],
                character_class=data['content']['characterClass'],
                team=data['content']['team'],
            )

            self.change_room(new_room)

            if new_room not in self.teams:
                self.teams[new_room] = {
                    'red': Team('red'),
                    'blue': Team('blue'),
                }

            self.teams[new_room][self.player.team].add_player(self.player)
            self.broadcast_game_state()

        if data['type'] == FEMessages.FE_HERO_MOVE:
            char_pos_x = self.player.position['x']
            char_pos_y = self.player.position['y']
            move_allowed, new_pos_x, new_pos_y = self.move_request(char_pos_x, char_pos_y, data['content']['direction'])
            self.player.position['x'] = new_pos_x
            char_pos_y = self.player.position['y'] = new_pos_y
            self.broadcast_game_state()

        if data['type'] == FEMessages.FE_HERO_SPELL:
            content = data['content']
            self.spell_request(content['spell_type'], content['position_x'], content['position_y'], content['direction'])
            self.broadcast_game_state()
            del self.spells[:]

    def spell_request(self, spell_type, position_x, position_y, direction):
        if spell_type in self.player.available_spells:
            spell = Spell.create_spell(spell_type, position_x, position_y, direction)

            time_since_last_cast = (time.time() - self.player.spell_cast_times[spell_type]) * 1000

            if time_since_last_cast >= spell.cooldown:
                self.spells.append(spell)
                self.calculate_damage(spell)
                self.player.spell_cast_times[spell_type] = time.time()

    def calculate_damage(self, spell):
        for team in self.teams[self.room].values():
            for player in team.players:
                # If we're trying to heal and it's an enemy,
                # or trying to damage and it's a friend, don't do anything
                if (
                    spell.damage < 0 and player.team != self.player.team
                    or spell.damage > 0 and player.team == self.player.team
                ):
                    return

                if self.calculate_intersection(player, spell):
                    player.hp -= spell.damage
                    if player.hp <= 0:
                        player.reset()
                        if player.team == 'red':
                            self.teams[self.room]['blue'].kills += 1
                        if player.team == 'blue':
                            self.teams[self.room]['red'].kills += 1
                        player.last_death = time.time()
                    elif player.hp > player.MAX_HP:
                        player.hp = player.MAX_HP

        if spell.spell_type != hackarena.constants.Spell.HEALER_HEAL:
            # TODO: check for dead building
            if self.calculate_intersection_with_tower(spell):
                enemy_team = 'red' if self.player.team == 'blue' else 'blue'
                self.teams[self.room][enemy_team].building_hp -= spell.damage

    def calculate_intersection(self, player, spell):
        # Stop hitting yourself!
        if player == self.player:
            return False

        player_x = player.position['x']
        player_y = player.position['y']
        spell_start_x = spell.start_position['x']
        spell_start_y = spell.start_position['y']
        spell_end_x = spell.end_position['x']
        spell_end_y = spell.end_position['y']
        return bool(
            (spell.direction == 'DOWN' and spell_start_y < player_y * MAP_TILE_SIZE < spell_end_y and player_x * MAP_TILE_SIZE == spell_start_x)
            or (spell.direction == 'UP' and spell_start_y > player_y * MAP_TILE_SIZE > spell_end_y and player_x * MAP_TILE_SIZE == spell_start_x)
            or (spell.direction == 'RIGHT' and spell_start_x < player_x * MAP_TILE_SIZE < spell_end_x and player_y * MAP_TILE_SIZE == spell_start_y)
            or (spell.direction == 'LEFT' and spell_start_x > player_x * MAP_TILE_SIZE > spell_end_x and player_y * MAP_TILE_SIZE == spell_start_y)
        )

    def calculate_intersection_with_tower(self, spell):
        # No friendly-fire on towers
        enemy_team = 'red' if self.player.team == 'blue' else 'blue'
        t = self.teams[self.room][enemy_team]

        spell_pixels = self.calculate_spell_hit_area(spell)

        tower_pixels_x = xrange(t.building_position['x'], t.building_position['x'] + t.building_size['width'] + MAP_TILE_SIZE, MAP_TILE_SIZE)
        tower_pixels_y = xrange(t.building_position['y'], t.building_position['y'] + t.building_size['height'] + MAP_TILE_SIZE, MAP_TILE_SIZE)
        for pixel in itertools.product(tower_pixels_x, tower_pixels_y):
            if pixel in spell_pixels:
                return True

        return False

    def calculate_spell_hit_area(self, spell):
        spell_start_x = spell.start_position['x']
        spell_start_y = spell.start_position['y']
        spell_end_x = spell.end_position['x']
        spell_end_y = spell.end_position['y']

        # TODO: work out pixels other than a line
        if spell_start_x == spell_end_x:
            y0 = min(spell_start_y, spell_end_y)
            y1 = max(spell_start_y, spell_end_y)
            hit_pixels = [(spell_start_x, y) for y in xrange(y0 + MAP_TILE_SIZE, y1, MAP_TILE_SIZE)]
        else:
            x0 = min(spell_start_x, spell_end_x)
            x1 = max(spell_start_x, spell_end_x)
            hit_pixels = [(x, spell_start_y) for x in xrange(x0 + MAP_TILE_SIZE, x1, MAP_TILE_SIZE)]

        return hit_pixels

    def change_room(self, room):
        old_room = self.room
        self.room = room

        del self.clients[old_room][self.session_string]
        self.clients[room][self.session_string] = self

    def broadcast_game_state(self):
        AllMainBroadcast(
            teams=self.teams[self.room],
            spells=self.spells,
        ).broadcast_to_all(self)

    def move_request(self, char_pos_x, char_pos_y, direction):
        if (
            char_pos_x <= 0 and direction == 'LEFT' or
            char_pos_x >= MAP_TILES_WIDTH - 1 and direction == 'RIGHT' or
            char_pos_y <= 0 and direction == 'UP' or
            char_pos_y >= MAP_TILES_HEIGHT - 1 and direction == 'DOWN' or
            self.has_obstacle_there(char_pos_x, char_pos_y, direction)
        ):
            return False, char_pos_x, char_pos_y

        new_position_x = char_pos_x
        new_position_y = char_pos_y

        if (direction == 'LEFT'):
            new_position_x = new_position_x - 1
        elif (direction == 'RIGHT'):
            new_position_x = new_position_x + 1
        elif (direction == 'UP'):
            new_position_y = new_position_y - 1
        elif (direction == 'DOWN'):
            new_position_y = new_position_y + 1

        return True, new_position_x, new_position_y

    def has_obstacle_there(self, char_pos_x, char_pos_y, direction):
        if (
            direction == 'LEFT' and MAP_OBSTACLES[63 * char_pos_y + char_pos_x - 1] != 0 or
            direction == 'RIGHT' and MAP_OBSTACLES[63 * char_pos_y + char_pos_x + 1] != 0 or
            direction == 'DOWN' and MAP_OBSTACLES[63 * char_pos_y + char_pos_x + 63] != 0 or
            direction == 'UP' and MAP_OBSTACLES[63 * char_pos_y + char_pos_x - 63] != 0
        ):
            return True
        return False
<commit_msg>Fix damage not doing anything<commit_after># -*- coding: utf-8 -*-
from collections import defaultdict
from hackarena.player import Player
from hackarena.spell import Spell
from hackarena.team import Team
from hackarena.messages import AllMainBroadcast
from hackarena.messages import FEMessages
from hackarena.messages import WelcomeBroadcast
from hackarena.utilities import Utilities
from hackarena.constants import MAP_TILES_WIDTH
from hackarena.constants import MAP_TILES_HEIGHT
from hackarena.constants import MAP_TILE_SIZE
from hackarena.constants import MAP_OBSTACLES
from sockjs.tornado import SockJSConnection
import hackarena.constants
import itertools
import json
import time

class WebSocketHandler(SockJSConnection):

    clients = defaultdict(dict)
    teams = {}
    players = {}
    spells = []

    @property
    def player(self):
        return self.players[self.session_string]

    @player.setter
    def player(self, player):
        self.players[self.session_string] = player

    @property
    def room(self):
        try:
            return self.player.room
        except:
            return hackarena.constants.DEFAULT_ROOM

    @room.setter
    def room(self, room):
        self.player.room = room

    def on_open(self, info):
        self.session_string = Utilities.get_session_string(str(self.session))

        self.clients[self.room][self.session_string] = self
        WelcomeBroadcast(message='Welcome to HackArena!').send(self)
        WelcomeBroadcast(message='Welcome to HackArena! (to all)').broadcast_to_all(self)

    def on_close(self):
        self.teams[self.room][self.player.team].remove_player(self.player)

        self.broadcast_game_state()

        del self.players[self.session_string]
        del self.clients[self.room][self.session_string]

    def on_message(self, message):
        try:
            data = json.loads(message)
        except:
            print 'Received unsupported message type'
            return

        if data['type'] == FEMessages.FE_JOIN_ROOM:
            new_room = data['content']['room']
            self.player = Player(
                username=data['content']['username'],
                character_class=data['content']['characterClass'],
                team=data['content']['team'],
            )

            self.change_room(new_room)

            if new_room not in self.teams:
                self.teams[new_room] = {
                    'red': Team('red'),
                    'blue': Team('blue'),
                }

            self.teams[new_room][self.player.team].add_player(self.player)
            self.broadcast_game_state()

        if data['type'] == FEMessages.FE_HERO_MOVE:
            char_pos_x = self.player.position['x']
            char_pos_y = self.player.position['y']
            move_allowed, new_pos_x, new_pos_y = self.move_request(char_pos_x, char_pos_y, data['content']['direction'])
            self.player.position['x'] = new_pos_x
            char_pos_y = self.player.position['y'] = new_pos_y
            self.broadcast_game_state()

        if data['type'] == FEMessages.FE_HERO_SPELL:
            content = data['content']
            self.spell_request(content['spell_type'], content['position_x'], content['position_y'], content['direction'])
            self.broadcast_game_state()
            del self.spells[:]

    def spell_request(self, spell_type, position_x, position_y, direction):
        if spell_type in self.player.available_spells:
            spell = Spell.create_spell(spell_type, position_x, position_y, direction)

            time_since_last_cast = (time.time() - self.player.spell_cast_times[spell_type]) * 1000

            if time_since_last_cast >= spell.cooldown:
                self.spells.append(spell)
                self.calculate_damage(spell)
                self.player.spell_cast_times[spell_type] = time.time()

    def calculate_damage(self, spell):
        for team in self.teams[self.room].values():
            for player in team.players:
                # If we're trying to heal and it's an enemy,
                # or trying to damage and it's a friend, don't do anything
                if (
                    spell.damage < 0 and player.team != self.player.team
                    or spell.damage > 0 and player.team == self.player.team
                ):
                    continue

                if self.calculate_intersection(player, spell):
                    player.hp -= spell.damage
                    if player.hp <= 0:
                        player.reset()
                        if player.team == 'red':
                            self.teams[self.room]['blue'].kills += 1
                        if player.team == 'blue':
                            self.teams[self.room]['red'].kills += 1
                        player.last_death = time.time()
                    elif player.hp > player.MAX_HP:
                        player.hp = player.MAX_HP

        if spell.spell_type != hackarena.constants.Spell.HEALER_HEAL:
            # TODO: check for dead building
            if self.calculate_intersection_with_tower(spell):
                enemy_team = 'red' if self.player.team == 'blue' else 'blue'
                self.teams[self.room][enemy_team].building_hp -= spell.damage

    def calculate_intersection(self, player, spell):
        # Stop hitting yourself!
        if player == self.player:
            return False

        player_x = player.position['x']
        player_y = player.position['y']
        spell_start_x = spell.start_position['x']
        spell_start_y = spell.start_position['y']
        spell_end_x = spell.end_position['x']
        spell_end_y = spell.end_position['y']
        return bool(
            (spell.direction == 'DOWN' and spell_start_y < player_y * MAP_TILE_SIZE < spell_end_y and player_x * MAP_TILE_SIZE == spell_start_x)
            or (spell.direction == 'UP' and spell_start_y > player_y * MAP_TILE_SIZE > spell_end_y and player_x * MAP_TILE_SIZE == spell_start_x)
            or (spell.direction == 'RIGHT' and spell_start_x < player_x * MAP_TILE_SIZE < spell_end_x and player_y * MAP_TILE_SIZE == spell_start_y)
            or (spell.direction == 'LEFT' and spell_start_x > player_x * MAP_TILE_SIZE > spell_end_x and player_y * MAP_TILE_SIZE == spell_start_y)
        )

    def calculate_intersection_with_tower(self, spell):
        # No friendly-fire on towers
        enemy_team = 'red' if self.player.team == 'blue' else 'blue'
        t = self.teams[self.room][enemy_team]

        spell_pixels = self.calculate_spell_hit_area(spell)

        tower_pixels_x = xrange(t.building_position['x'], t.building_position['x'] + t.building_size['width'] + MAP_TILE_SIZE, MAP_TILE_SIZE)
        tower_pixels_y = xrange(t.building_position['y'], t.building_position['y'] + t.building_size['height'] + MAP_TILE_SIZE, MAP_TILE_SIZE)
        for pixel in itertools.product(tower_pixels_x, tower_pixels_y):
            if pixel in spell_pixels:
                return True

        return False

    def calculate_spell_hit_area(self, spell):
        spell_start_x = spell.start_position['x']
        spell_start_y = spell.start_position['y']
        spell_end_x = spell.end_position['x']
        spell_end_y = spell.end_position['y']

        # TODO: work out pixels other than a line
        if spell_start_x == spell_end_x:
            y0 = min(spell_start_y, spell_end_y)
            y1 = max(spell_start_y, spell_end_y)
            hit_pixels = [(spell_start_x, y) for y in xrange(y0 + MAP_TILE_SIZE, y1, MAP_TILE_SIZE)]
        else:
            x0 = min(spell_start_x, spell_end_x)
            x1 = max(spell_start_x, spell_end_x)
            hit_pixels = [(x, spell_start_y) for x in xrange(x0 + MAP_TILE_SIZE, x1, MAP_TILE_SIZE)]

        return hit_pixels

    def change_room(self, room):
        old_room = self.room
        self.room = room

        del self.clients[old_room][self.session_string]
        self.clients[room][self.session_string] = self

    def broadcast_game_state(self):
        AllMainBroadcast(
            teams=self.teams[self.room],
            spells=self.spells,
        ).broadcast_to_all(self)

    def move_request(self, char_pos_x, char_pos_y, direction):
        if (
            char_pos_x <= 0 and direction == 'LEFT' or
            char_pos_x >= MAP_TILES_WIDTH - 1 and direction == 'RIGHT' or
            char_pos_y <= 0 and direction == 'UP' or
            char_pos_y >= MAP_TILES_HEIGHT - 1 and direction == 'DOWN' or
            self.has_obstacle_there(char_pos_x, char_pos_y, direction)
        ):
            return False, char_pos_x, char_pos_y

        new_position_x = char_pos_x
        new_position_y = char_pos_y

        if (direction == 'LEFT'):
            new_position_x = new_position_x - 1
        elif (direction == 'RIGHT'):
            new_position_x = new_position_x + 1
        elif (direction == 'UP'):
            new_position_y = new_position_y - 1
        elif (direction == 'DOWN'):
            new_position_y = new_position_y + 1

        return True, new_position_x, new_position_y

    def has_obstacle_there(self, char_pos_x, char_pos_y, direction):
        if (
            direction == 'LEFT' and MAP_OBSTACLES[63 * char_pos_y + char_pos_x - 1] != 0 or
            direction == 'RIGHT' and MAP_OBSTACLES[63 * char_pos_y + char_pos_x + 1] != 0 or
            direction == 'DOWN' and MAP_OBSTACLES[63 * char_pos_y + char_pos_x + 63] != 0 or
            direction == 'UP' and MAP_OBSTACLES[63 * char_pos_y + char_pos_x - 63] != 0
        ):
            return True
        return False
<|endoftext|>


<commit_before>import copy
import hashlib
import logging
import os
import pickle
import random
import struct
import time

from halocoin import custom

alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'

def init_logging(DEBUG, working_dir, log_file):
    if DEBUG:
        logging.basicConfig(level=logging.INFO,
                            format='%(levelname)s on %(asctime)s\n%(message)s',
                            datefmt='%m/%d/%Y %I:%M:%S %p')
    else:
        logging.basicConfig(filename=os.path.join(working_dir, log_file),
                            level=logging.DEBUG,
                            format='%(levelname)s on %(asctime)s\n%(message)s',
                            datefmt='%m/%d/%Y %I:%M:%S %p')
    log = logging.getLogger('werkzeug')
    log.setLevel(logging.ERROR)

def get_default_dir():
    from os.path import expanduser
    home = expanduser("~")
    default_dir = os.path.join(home, '.halocoin')
    return os.environ.get("HALOCOIN_DATA_DIR", default_dir)

def log(message):
    import traceback
    if isinstance(message, Exception):
        logging.exception(message)
        logging.critical(traceback.format_exc())
    else:
        logging.info('{}'.format(message))

def tx_owner_address(tx):
    return make_address(tx['pubkeys'], len(tx['signatures']))

def reward_owner_name(tx):
    if 'auth' in tx:
        return tx['auth']
    else:
        return get_commonname_from_certificate(tx['certificate'])

def sign(msg, privkey):
    from ecdsa import SigningKey
    if isinstance(privkey, bytes):
        privkey = SigningKey.from_string(privkey)
    return privkey.sign(msg)

def block_reward(length):
    import math
    a = length // custom.halve_at
    b = custom.block_reward / math.pow(2, a)
    return int(b)

def det_hash(x):
    """Deterministically takes sha256 of dict, list, int, or string."""
    return hashlib.sha384(pickle.dumps(x)).digest()[0:32]

def hash_without_nonce(block):
    a = copy.deepcopy(block)
    a.pop('nonce')
    return {'nonce': block['nonce'], 'halfHash': det_hash(a)}

def base58_encode(num):
    num = int(num.hex(), 16)
    base_count = len(alphabet)
    encode = ''
    if num < 0:
        return ''
    while num >= base_count:
        mod = num % base_count
        encode = alphabet[mod] + encode
        num = num // base_count
    if num:
        encode = alphabet[num] + encode
    return encode

def is_address_valid(address):
    if len(address) < 32:
        return False
    if not str(address[:2]).isdigit():
        return False
    if not str(address[2:]).isalnum():
        return False
    return True

def make_address(pubkeys, n):
    """
    n is the number of pubkeys required to spend from this address.
    This function is compatible with string or VerifyingKey representation of keys.
    """
    from ecdsa import VerifyingKey
    pubkeys_as_string = [p.to_string() if isinstance(p, VerifyingKey) else p for p in pubkeys]
    hashed = det_hash({str(n): pubkeys_as_string})
    return str(len(pubkeys_as_string)) + str(n) + base58_encode(hashed[0:29])

def buffer_(str_to_pad, size):
    return str_to_pad.rjust(size, '0')

def exponential_random(r, i=0):
    if random.random() < r:
        return i
    return exponential_random(r, i + 1)

def median(mylist):
    if len(mylist) < 1:
        return 0
    return sorted(mylist)[len(mylist) // 2]

def hex_sum(a, b):
    # Sum of numbers expressed as hexidecimal strings
    if isinstance(a, bytearray):
        a = a.hex()
        b = b.hex()
    return buffer_(format(int(a, 16) + int(b, 16), 'x'), 64)

def hex_invert(n):
    # Use double-size for division, to reduce information leakage.
    if isinstance(n, bytearray):
        n = n.hex()
    return buffer_(format(int('f' * 128, 16) // int(n, 16), 'x'), 64)

def encrypt(key, content, chunksize=64 * 1024):
    import io
    import Crypto.Random
    from Crypto.Cipher import AES
    infile = io.BytesIO()
    infile.write(content)
    infile.seek(0)
    outfile = io.BytesIO()
    if isinstance(key, str):
        key = key.encode()
    key = hashlib.sha256(key).digest()

    iv = Crypto.Random.OSRNG.posix.new().read(AES.block_size)
    encryptor = AES.new(key, AES.MODE_CBC, iv)
    filesize = len(content)

    outfile.write(struct.pack('<Q', filesize))
    outfile.write(iv)
    while True:
        chunk = infile.read(chunksize)
        if len(chunk) == 0:
            break
        elif len(chunk) % 16 != 0:
            chunk += '\0'.encode() * (16 - len(chunk) % 16)
        outfile.write(encryptor.encrypt(chunk))
    return outfile.getvalue()

def decrypt(key, content, chunksize=24 * 1024):
    from Crypto.Cipher import AES
    import io
    infile = io.BytesIO(content)
    outfile = io.BytesIO()

    if isinstance(key, str):
        key = key.encode()
    key = hashlib.sha256(key).digest()

    origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
    iv = infile.read(16)
    decryptor = AES.new(key, AES.MODE_CBC, iv)

    while True:
        chunk = infile.read(chunksize)
        if len(chunk) == 0:
            break
        outfile.write(decryptor.decrypt(chunk))

    outfile.truncate(origsize)
    return outfile.getvalue()

def signature_verify(message, signature, pubkey):
    from ecdsa import VerifyingKey, SECP256k1
    if isinstance(pubkey, str):
        pubkey = VerifyingKey.from_string(pubkey, curve=SECP256k1)
    elif isinstance(pubkey, bytes):
        pubkey = VerifyingKey.from_string(pubkey, curve=SECP256k1)

    if isinstance(pubkey, VerifyingKey):
        try:
            return pubkey.verify(signature, message)
        except:
            return False
    else:
        return False

def validate_uuid4(uuid_string):

    """
    Validate that a UUID string is in
    fact a valid uuid4.
    Happily, the uuid module does the actual
    checking for us.
    It is vital that the 'version' kwarg be passed
    to the UUID() call, otherwise any 32-character
    hex string is considered valid.
    """

    try:
        from uuid import UUID
        val = UUID(uuid_string, version=4)
    except ValueError:
        # If it's a value error, then the string
        # is not a valid hex code for a UUID.
        return False

    # If the uuid_string is a valid hex code,
    # but an invalid uuid4,
    # the UUID.__init__ will convert it to a
    # valid uuid4. This is bad for validation purposes.

    return val.hex == uuid_string.replace('-', '')

def check_certificate_chain(intermediate_cert_pem):
    from OpenSSL.crypto import load_certificate, FILETYPE_PEM, X509Store, X509StoreContext
    root_cert = load_certificate(FILETYPE_PEM, custom.root_cert_pem)
    intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
    try:
        store = X509Store()
        store.add_cert(root_cert)
        store_ctx = X509StoreContext(store, intermediate_cert)
        store_ctx.verify_certificate()
        return True
    except:
        return False

def get_pubkey_from_certificate(intermediate_cert_pem):
    from OpenSSL.crypto import load_certificate, FILETYPE_PEM, dump_publickey
    from ecdsa import VerifyingKey
    intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
    pubkey_pem = dump_publickey(FILETYPE_PEM, intermediate_cert.get_pubkey())
    return VerifyingKey.from_pem(pubkey_pem)

def get_commonname_from_certificate(intermediate_cert_pem):
    from OpenSSL.crypto import load_certificate, FILETYPE_PEM
    from slugify import slugify
    intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
    return slugify(intermediate_cert.get_subject().commonName)

last = 0

def echo(text):
    global last
    print(text)
    last = time.time()

def techo(text):
    global last
    if last == 0:
        print(text)
    else:
        print(text + ": {}".format(time.time()-last))
        last = time.time()

def readable_bytes(num, suffix='B'):
    for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', suffix)<commit_msg>yaml for det hash<commit_after>import copy
import hashlib
import logging
import os
import random
import struct
import time

from halocoin import custom

alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'

def init_logging(DEBUG, working_dir, log_file):
    if DEBUG:
        logging.basicConfig(level=logging.INFO,
                            format='%(levelname)s on %(asctime)s\n%(message)s',
                            datefmt='%m/%d/%Y %I:%M:%S %p')
    else:
        logging.basicConfig(filename=os.path.join(working_dir, log_file),
                            level=logging.DEBUG,
                            format='%(levelname)s on %(asctime)s\n%(message)s',
                            datefmt='%m/%d/%Y %I:%M:%S %p')
    log = logging.getLogger('werkzeug')
    log.setLevel(logging.ERROR)

def get_default_dir():
    from os.path import expanduser
    home = expanduser("~")
    default_dir = os.path.join(home, '.halocoin')
    return os.environ.get("HALOCOIN_DATA_DIR", default_dir)

def log(message):
    import traceback
    if isinstance(message, Exception):
        logging.exception(message)
        logging.critical(traceback.format_exc())
    else:
        logging.info('{}'.format(message))

def tx_owner_address(tx):
    return make_address(tx['pubkeys'], len(tx['signatures']))

def reward_owner_name(tx):
    if 'auth' in tx:
        return tx['auth']
    else:
        return get_commonname_from_certificate(tx['certificate'])

def sign(msg, privkey):
    from ecdsa import SigningKey
    if isinstance(privkey, bytes):
        privkey = SigningKey.from_string(privkey)
    return privkey.sign(msg)

def block_reward(length):
    import math
    a = length // custom.halve_at
    b = custom.block_reward / math.pow(2, a)
    return int(b)

def det_hash(x):
    """Deterministically takes sha256 of dict, list, int, or string."""
    import yaml
    return hashlib.sha384(yaml.dump(x).encode()).digest()[0:32]

def hash_without_nonce(block):
    a = copy.deepcopy(block)
    a.pop('nonce')
    return {'nonce': block['nonce'], 'halfHash': det_hash(a)}

def base58_encode(num):
    num = int(num.hex(), 16)
    base_count = len(alphabet)
    encode = ''
    if num < 0:
        return ''
    while num >= base_count:
        mod = num % base_count
        encode = alphabet[mod] + encode
        num = num // base_count
    if num:
        encode = alphabet[num] + encode
    return encode

def is_address_valid(address):
    if len(address) < 32:
        return False
    if not str(address[:2]).isdigit():
        return False
    if not str(address[2:]).isalnum():
        return False
    return True

def make_address(pubkeys, n):
    """
    n is the number of pubkeys required to spend from this address.
    This function is compatible with string or VerifyingKey representation of keys.
    """
    from ecdsa import VerifyingKey
    pubkeys_as_string = [p.to_string() if isinstance(p, VerifyingKey) else p for p in pubkeys]
    hashed = det_hash({str(n): pubkeys_as_string})
    return str(len(pubkeys_as_string)) + str(n) + base58_encode(hashed[0:29])

def buffer_(str_to_pad, size):
    return str_to_pad.rjust(size, '0')

def exponential_random(r, i=0):
    if random.random() < r:
        return i
    return exponential_random(r, i + 1)

def median(mylist):
    if len(mylist) < 1:
        return 0
    return sorted(mylist)[len(mylist) // 2]

def hex_sum(a, b):
    # Sum of numbers expressed as hexidecimal strings
    if isinstance(a, bytearray):
        a = a.hex()
        b = b.hex()
    return buffer_(format(int(a, 16) + int(b, 16), 'x'), 64)

def hex_invert(n):
    # Use double-size for division, to reduce information leakage.
    if isinstance(n, bytearray):
        n = n.hex()
    return buffer_(format(int('f' * 128, 16) // int(n, 16), 'x'), 64)

def encrypt(key, content, chunksize=64 * 1024):
    import io
    import Crypto.Random
    from Crypto.Cipher import AES
    infile = io.BytesIO()
    infile.write(content)
    infile.seek(0)
    outfile = io.BytesIO()
    if isinstance(key, str):
        key = key.encode()
    key = hashlib.sha256(key).digest()

    iv = Crypto.Random.OSRNG.posix.new().read(AES.block_size)
    encryptor = AES.new(key, AES.MODE_CBC, iv)
    filesize = len(content)

    outfile.write(struct.pack('<Q', filesize))
    outfile.write(iv)
    while True:
        chunk = infile.read(chunksize)
        if len(chunk) == 0:
            break
        elif len(chunk) % 16 != 0:
            chunk += '\0'.encode() * (16 - len(chunk) % 16)
        outfile.write(encryptor.encrypt(chunk))
    return outfile.getvalue()

def decrypt(key, content, chunksize=24 * 1024):
    from Crypto.Cipher import AES
    import io
    infile = io.BytesIO(content)
    outfile = io.BytesIO()

    if isinstance(key, str):
        key = key.encode()
    key = hashlib.sha256(key).digest()

    origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
    iv = infile.read(16)
    decryptor = AES.new(key, AES.MODE_CBC, iv)

    while True:
        chunk = infile.read(chunksize)
        if len(chunk) == 0:
            break
        outfile.write(decryptor.decrypt(chunk))

    outfile.truncate(origsize)
    return outfile.getvalue()

def signature_verify(message, signature, pubkey):
    from ecdsa import VerifyingKey, SECP256k1
    if isinstance(pubkey, str):
        pubkey = VerifyingKey.from_string(pubkey, curve=SECP256k1)
    elif isinstance(pubkey, bytes):
        pubkey = VerifyingKey.from_string(pubkey, curve=SECP256k1)

    if isinstance(pubkey, VerifyingKey):
        try:
            return pubkey.verify(signature, message)
        except:
            return False
    else:
        return False

def validate_uuid4(uuid_string):

    """
    Validate that a UUID string is in
    fact a valid uuid4.
    Happily, the uuid module does the actual
    checking for us.
    It is vital that the 'version' kwarg be passed
    to the UUID() call, otherwise any 32-character
    hex string is considered valid.
    """

    try:
        from uuid import UUID
        val = UUID(uuid_string, version=4)
    except ValueError:
        # If it's a value error, then the string
        # is not a valid hex code for a UUID.
        return False

    # If the uuid_string is a valid hex code,
    # but an invalid uuid4,
    # the UUID.__init__ will convert it to a
    # valid uuid4. This is bad for validation purposes.

    return val.hex == uuid_string.replace('-', '')

def check_certificate_chain(intermediate_cert_pem):
    from OpenSSL.crypto import load_certificate, FILETYPE_PEM, X509Store, X509StoreContext
    root_cert = load_certificate(FILETYPE_PEM, custom.root_cert_pem)
    intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
    try:
        store = X509Store()
        store.add_cert(root_cert)
        store_ctx = X509StoreContext(store, intermediate_cert)
        store_ctx.verify_certificate()
        return True
    except:
        return False

def get_pubkey_from_certificate(intermediate_cert_pem):
    from OpenSSL.crypto import load_certificate, FILETYPE_PEM, dump_publickey
    from ecdsa import VerifyingKey
    intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
    pubkey_pem = dump_publickey(FILETYPE_PEM, intermediate_cert.get_pubkey())
    return VerifyingKey.from_pem(pubkey_pem)

def get_commonname_from_certificate(intermediate_cert_pem):
    from OpenSSL.crypto import load_certificate, FILETYPE_PEM
    from slugify import slugify
    intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
    return slugify(intermediate_cert.get_subject().commonName)

last = 0

def echo(text):
    global last
    print(text)
    last = time.time()

def techo(text):
    global last
    if last == 0:
        print(text)
    else:
        print(text + ": {}".format(time.time()-last))
        last = time.time()

def readable_bytes(num, suffix='B'):
    for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', suffix)<|endoftext|>


<commit_before>from eclipsegen.preset import Presets

from eclipsegen.generate import EclipseGenerator, EclipseMultiGenerator

class MetaborgEclipseGenerator(object):
  spoofaxRepo = 'http://buildfarm.metaborg.org/job/metaborg/job/spoofax-releng/job/master/lastSuccessfulBuild/artifact/dist/spoofax/eclipse/site/'
  spoofaxRepoLocal = 'spoofax-eclipse/org.metaborg.spoofax.eclipse.updatesite/target/site'
  spoofaxIUs = ['org.metaborg.spoofax.eclipse.feature.feature.group']
  spoofaxLangDevIUs = [
    'org.metaborg.spoofax.eclipse.meta.feature.feature.group',
    'org.metaborg.spoofax.eclipse.meta.m2e.feature.feature.group',
    'de.jcup.yamleditor.feature.group',
  ]
  eclipsePhotonRepo = 'https://artifacts.metaborg.org/content/groups/eclipse-2020-06/'

  def __init__(self, workingDir, destination, spoofax=True, spoofaxRepo=None, spoofaxRepoLocal=False,
      langDev=True, lwbDev=True, moreRepos=None, moreIUs=None):
    if spoofaxRepoLocal:
      spoofaxRepo = MetaborgEclipseGenerator.spoofaxRepoLocal
    elif not spoofaxRepo:
      spoofaxRepo = MetaborgEclipseGenerator.spoofaxRepo

    if lwbDev:
      langDev = True

    if not moreRepos:
      moreRepos = []
    if not moreIUs:
      moreIUs = []

    presets = [Presets.platform.value, Presets.java.value, Presets.xml.value, Presets.git.value, Presets.maven.value, Presets.gradle.value]
    if langDev or lwbDev:
      presets.extend([Presets.plugin.value, Presets.plugin_maven.value])
    _, ius = Presets.combine_presets(presets)

    repos = {MetaborgEclipseGenerator.eclipsePhotonRepo}
    repos.add(spoofaxRepo)
    ius.update(MetaborgEclipseGenerator.spoofaxIUs)
    if langDev or lwbDev:
      ius.update(MetaborgEclipseGenerator.spoofaxLangDevIUs)

    repos.update(moreRepos)
    ius.update(moreIUs)

    self.workingDir = workingDir
    self.destination = destination
    self.repos = repos
    self.ius = ius

  def generate(self, **kwargs):
    generator = EclipseGenerator(self.workingDir, self.destination, repositories=self.repos, installUnits=self.ius,
      **kwargs)
    return generator.generate()

  def generate_all(self, **kwargs):
    generator = EclipseMultiGenerator(self.workingDir, self.destination, repositories=self.repos, installUnits=self.ius,
      **kwargs)
    return generator.generate()
<commit_msg>Add YAML editor repo.<commit_after>from eclipsegen.preset import Presets

from eclipsegen.generate import EclipseGenerator, EclipseMultiGenerator

class MetaborgEclipseGenerator(object):
  spoofaxRepo = 'http://buildfarm.metaborg.org/job/metaborg/job/spoofax-releng/job/master/lastSuccessfulBuild/artifact/dist/spoofax/eclipse/site/'
  spoofaxRepoLocal = 'spoofax-eclipse/org.metaborg.spoofax.eclipse.updatesite/target/site'
  spoofaxIUs = ['org.metaborg.spoofax.eclipse.feature.feature.group']
  spoofaxLangDevIUs = [
    'org.metaborg.spoofax.eclipse.meta.feature.feature.group',
    'org.metaborg.spoofax.eclipse.meta.m2e.feature.feature.group',
    'de.jcup.yamleditor.feature.group',
  ]
  eclipsePhotonRepo = 'https://artifacts.metaborg.org/content/groups/eclipse-2020-06/'
  yamlEditorRepo = 'https://de-jcup.github.io/update-site-eclipse-yaml-editor/update-site/'

  def __init__(self, workingDir, destination, spoofax=True, spoofaxRepo=None, spoofaxRepoLocal=False,
      langDev=True, lwbDev=True, moreRepos=None, moreIUs=None):
    if spoofaxRepoLocal:
      spoofaxRepo = MetaborgEclipseGenerator.spoofaxRepoLocal
    elif not spoofaxRepo:
      spoofaxRepo = MetaborgEclipseGenerator.spoofaxRepo

    if lwbDev:
      langDev = True

    if not moreRepos:
      moreRepos = []
    if not moreIUs:
      moreIUs = []

    presets = [Presets.platform.value, Presets.java.value, Presets.xml.value, Presets.git.value, Presets.maven.value, Presets.gradle.value]
    if langDev or lwbDev:
      presets.extend([Presets.plugin.value, Presets.plugin_maven.value])
    _, ius = Presets.combine_presets(presets)

    repos = {MetaborgEclipseGenerator.eclipsePhotonRepo}
    repos.add(spoofaxRepo)
    ius.update(MetaborgEclipseGenerator.spoofaxIUs)
    if langDev or lwbDev:
      ius.update(MetaborgEclipseGenerator.spoofaxLangDevIUs)
      repos.add(yamlEditorRepo)

    repos.update(moreRepos)
    ius.update(moreIUs)

    self.workingDir = workingDir
    self.destination = destination
    self.repos = repos
    self.ius = ius

  def generate(self, **kwargs):
    generator = EclipseGenerator(self.workingDir, self.destination, repositories=self.repos, installUnits=self.ius,
      **kwargs)
    return generator.generate()

  def generate_all(self, **kwargs):
    generator = EclipseMultiGenerator(self.workingDir, self.destination, repositories=self.repos, installUnits=self.ius,
      **kwargs)
    return generator.generate()
<|endoftext|>


<commit_before>#!/usr/bin/python
# -*- coding:utf-8 -*-
# Powered By KK Studio
# Domain Page

from BaseHandler import BaseHandler
from tornado.web import authenticated as Auth
from model.models import Domain, Groups, Record

class IndexHandler(BaseHandler):
    @Auth
    def get(self):
        page = int(self.get_argument('page', 1))
        line = int(self.get_argument('line', 20))
        offset = (page - 1) * line
        data = self.db.query(Domain).order_by(Domain.id.desc()).offset(offset).limit(line).all()
        grps = self.db.query(Groups).all()
        group = {}
        for i in grps:
            group[i.id] = i.name
        status = {1:u'已启用',2:u'暂停解析'}
        self.nav_active['/domain'] = 'active'
        self.render('domain/index.html',data=data,group=group,status=status)

# 新增域名
class CreateDomainHandler(BaseHandler):
    @Auth
    def post(self):
        domain = self.get_argument('domain',None)
        gid = self.get_argument('gid',None)
        comment = self.get_argument('comment',None)
        if not domain and not gid:
            return self.jsonReturn({'code': -1, 'msg': u'参数错误'})
        chk = self.db.query(Domain).filter_by(zone=domain).first()
        if chk:
            return self.jsonReturn({'code': -2, 'msg': u'域名重复'})
        # Check Group ID
        grp = self.db.query(Groups).filter_by(id=gid).first()
        if not grp:
            return self.jsonReturn({'code': -3, 'msg': u'分组不存在'})
        d = Domain(zone=domain,gid=gid,comment=comment,create_time=self.time,update_time=self.time)
        self.db.add(d)
        self.db.commit()
        if d.id:
            self.db.query(Groups).filter_by(id=gid).update({'domain_count': Groups.domain_count+1})
            self.db.commit()
            code = 0
            msg = u'成功添加域名'
        else:
            self.db.rollback()
            gid = 0
            code = -4
            msg = u'保存域名失败'
        return self.jsonReturn({'code': code, 'msg': msg, 'gid': gid})

# 编辑域名
class UpdateDomainHandler(BaseHandler):
    @Auth
    def post(self):
        domain_id = self.get_argument('id',None)
        gid = self.get_argument('gid',None)
        comment = self.get_argument('comment',None)
        if not domain_id and not gid:
            return self.jsonReturn({'code': -1, 'msg': u'参数错误'})
        data = self.db.query(Domain).filter_by(id=domain_id).first()
        if not data:
            return self.jsonReturn({'code': -2, 'msg': u'域名不存在'})
        # Check Group ID
        group1 = self.db.query(Groups).filter_by(id=gid).first()
        if not group1:
            return self.jsonReturn({'code': -3, 'msg': u'分组不存在'})
        old_gid = group1.id
        self.db.query(Domain).filter_by(id=domain_id).update({'gid': gid, 'comment': comment, 'update_time': self.time})
        self.db.query(Groups).filter_by(id=old_gid).update({'domain_count': Groups.domain_count-1})
        self.db.query(Groups).filter_by(id=gid).update({'domain_count': Groups.domain_count+1})
        self.db.commit()
        return self.jsonReturn({'code': 0, 'msg': 'Success'})

class GroupHandler(BaseHandler):
    @Auth
    def get(self):
        self.nav_active['/domain/group'] = 'active'
        data = self.db.query(Groups).order_by(Groups.id.desc()).all()
        self.render('domain/group.html',data=data)

class RecordHandler(BaseHandler):
    @Auth
    def get(self):
        zone = self.get_argument('zone',None)
        if zone:
            data = self.db.query(Record).filter_by(zone=zone).order_by(Record.host,Record.type,Record.data).all()
        else:
            zone = ''
            data = []
        status = {1: u'已启用', 2: u'暂停解析'}
        self.nav_active['/domain/record'] = 'active'
        self.render('domain/record.html',data=data,status=status,zone=zone)

<commit_msg>Fix update domain group info logic<commit_after>#!/usr/bin/python
# -*- coding:utf-8 -*-
# Powered By KK Studio
# Domain Page

from BaseHandler import BaseHandler
from tornado.web import authenticated as Auth
from model.models import Domain, Groups, Record

class IndexHandler(BaseHandler):
    @Auth
    def get(self):
        page = int(self.get_argument('page', 1))
        line = int(self.get_argument('line', 20))
        offset = (page - 1) * line
        data = self.db.query(Domain).order_by(Domain.id.desc()).offset(offset).limit(line).all()
        grps = self.db.query(Groups).all()
        group = {}
        for i in grps:
            group[i.id] = i.name
        status = {1:u'已启用',2:u'暂停解析'}
        self.nav_active['/domain'] = 'active'
        self.render('domain/index.html',data=data,group=group,status=status)

# 新增域名
class CreateDomainHandler(BaseHandler):
    @Auth
    def post(self):
        domain = self.get_argument('domain',None)
        gid = self.get_argument('gid',None)
        comment = self.get_argument('comment',None)
        if not domain and not gid:
            return self.jsonReturn({'code': -1, 'msg': u'参数错误'})
        chk = self.db.query(Domain).filter_by(zone=domain).first()
        if chk:
            return self.jsonReturn({'code': -2, 'msg': u'域名重复'})
        # Check Group ID
        grp = self.db.query(Groups).filter_by(id=gid).first()
        if not grp:
            return self.jsonReturn({'code': -3, 'msg': u'分组不存在'})
        d = Domain(zone=domain,gid=gid,comment=comment,create_time=self.time,update_time=self.time)
        self.db.add(d)
        self.db.commit()
        if d.id:
            self.db.query(Groups).filter_by(id=gid).update({'domain_count': Groups.domain_count+1})
            self.db.commit()
            code = 0
            msg = u'成功添加域名'
        else:
            self.db.rollback()
            gid = 0
            code = -4
            msg = u'保存域名失败'
        return self.jsonReturn({'code': code, 'msg': msg, 'gid': gid})

# 编辑域名
class UpdateDomainHandler(BaseHandler):
    @Auth
    def post(self):
        domain_id = self.get_argument('id',None)
        gid = self.get_argument('gid',None)
        comment = self.get_argument('comment',None)
        if not domain_id and not gid:
            return self.jsonReturn({'code': -1, 'msg': u'参数错误'})
        data = self.db.query(Domain).filter_by(id=domain_id).first()
        if not data:
            return self.jsonReturn({'code': -2, 'msg': u'域名不存在'})
        # Check Group ID
        group = self.db.query(Groups).filter_by(id=gid).first()
        if not group:
            return self.jsonReturn({'code': -3, 'msg': u'分组不存在'})
        self.db.query(Domain).filter_by(id=domain_id).update({'gid': gid, 'comment': comment, 'update_time': self.time})
        self.db.query(Groups).filter_by(id=data.gid).update({'domain_count': Groups.domain_count-1})
        self.db.query(Groups).filter_by(id=gid).update({'domain_count': Groups.domain_count+1})
        self.db.commit()
        return self.jsonReturn({'code': 0, 'msg': 'Success'})

class GroupHandler(BaseHandler):
    @Auth
    def get(self):
        self.nav_active['/domain/group'] = 'active'
        data = self.db.query(Groups).order_by(Groups.id.desc()).all()
        self.render('domain/group.html',data=data)

class RecordHandler(BaseHandler):
    @Auth
    def get(self):
        zone = self.get_argument('zone',None)
        if zone:
            data = self.db.query(Record).filter_by(zone=zone).order_by(Record.host,Record.type,Record.data).all()
        else:
            zone = ''
            data = []
        status = {1: u'已启用', 2: u'暂停解析'}
        self.nav_active['/domain/record'] = 'active'
        self.render('domain/record.html',data=data,status=status,zone=zone)

<|endoftext|>


<commit_before>import logging
import os
import time

import fabric.api
import fabric.operations

import cloudenvy.envy

class Provision(cloudenvy.envy.Command):

    def _build_subparser(self, subparsers):
        help_str = 'Uplaod and execute script(s) in your ENVy.'
        subparser = subparsers.add_parser('provision', help=help_str,
                                          description=help_str)
        subparser.set_defaults(func=self.run)

        subparser.add_argument('-n', '--name', action='store', default='',
                               help='Specify custom name for an ENVy.')
        subparser.add_argument('-s', '--scripts', nargs='*', metavar='PATH',
                               help='Specify one or more scripts.')
        return subparser

    def run(self, config, args):
        envy = cloudenvy.envy.Envy(config)

        logging.info('Running provision scripts for ENVy \'%s\'.' %
                     envy.project_config['name'])
        if envy.ip():
            with fabric.api.settings(host_string=envy.ip(), user=envy.remote_user,
                                     forward_agent=True, disable_known_hosts=True):

                if args.scripts:
                    scripts = [os.path.expanduser(script) for
                               script in args.scripts]
                elif 'provision_scripts' in envy.project_config:
                    scripts = [os.path.expanduser(script) for script in
                               envy.project_config['provision_scripts']]
                elif 'provision_script_path' in envy.project_config:
                    provision_script = envy.project_config['provision_script_path']
                    scripts = [os.path.expanduser(provision_script)]
                else:
                    raise SystemExit('Please specify the path to your provision '
                                     'script(s) by either using the `--scripts` '
                                     'flag, or by defining the `provision_scripts`'
                                     ' config option in your Envyfile.')

                for script in scripts:
                    logging.info('Running provision script from \'%s\'', script)

                    for i in range(24):
                        try:
                            path = script
                            filename = os.path.basename(script)
                            remote_path = '~/%s' % filename
                            fabric.operations.put(path, remote_path, mode=0755)
                            fabric.operations.run(remote_path)
                            break
                        except fabric.exceptions.NetworkError:
                            logging.debug('Unable to upload the provision script '
                                          'from `%s`. Trying again in 10 seconds.' % path)
                            time.sleep(10)
                    logging.info('Provision script \'%s\' finished.' % path)
        else:
            logging.error('Could not determine IP.')
<commit_msg>Fix typo s/Uplaod/Upload/<commit_after>import logging
import os
import time

import fabric.api
import fabric.operations

import cloudenvy.envy

class Provision(cloudenvy.envy.Command):

    def _build_subparser(self, subparsers):
        help_str = 'Upload and execute script(s) in your ENVy.'
        subparser = subparsers.add_parser('provision', help=help_str,
                                          description=help_str)
        subparser.set_defaults(func=self.run)

        subparser.add_argument('-n', '--name', action='store', default='',
                               help='Specify custom name for an ENVy.')
        subparser.add_argument('-s', '--scripts', nargs='*', metavar='PATH',
                               help='Specify one or more scripts.')
        return subparser

    def run(self, config, args):
        envy = cloudenvy.envy.Envy(config)

        logging.info('Running provision scripts for ENVy \'%s\'.' %
                     envy.project_config['name'])
        if envy.ip():
            with fabric.api.settings(host_string=envy.ip(), user=envy.remote_user,
                                     forward_agent=True, disable_known_hosts=True):

                if args.scripts:
                    scripts = [os.path.expanduser(script) for
                               script in args.scripts]
                elif 'provision_scripts' in envy.project_config:
                    scripts = [os.path.expanduser(script) for script in
                               envy.project_config['provision_scripts']]
                elif 'provision_script_path' in envy.project_config:
                    provision_script = envy.project_config['provision_script_path']
                    scripts = [os.path.expanduser(provision_script)]
                else:
                    raise SystemExit('Please specify the path to your provision '
                                     'script(s) by either using the `--scripts` '
                                     'flag, or by defining the `provision_scripts`'
                                     ' config option in your Envyfile.')

                for script in scripts:
                    logging.info('Running provision script from \'%s\'', script)

                    for i in range(24):
                        try:
                            path = script
                            filename = os.path.basename(script)
                            remote_path = '~/%s' % filename
                            fabric.operations.put(path, remote_path, mode=0755)
                            fabric.operations.run(remote_path)
                            break
                        except fabric.exceptions.NetworkError:
                            logging.debug('Unable to upload the provision script '
                                          'from `%s`. Trying again in 10 seconds.' % path)
                            time.sleep(10)
                    logging.info('Provision script \'%s\' finished.' % path)
        else:
            logging.error('Could not determine IP.')
<|endoftext|>


<commit_before>#!/usr/bin/env python
# coding=utf-8

<commit_msg>Update error.py<commit_after>#!/usr/bin/env python
# coding=utf-8

from webapp.web import BaseHandler

class ErrorHandler(BaseHandler):

    def get(self):
        self.write("Page Not Exist")
<|endoftext|>


<commit_before>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
import time
from RHS import RHS
from ATVS_reader import *
import random
import os

batch_size = 48
class_num = 350
rate = 0.0001
loop = 1000000

log_dir = './log'
model_dir = './model'

genuine_data = bucket_group()

def get_feed():
    s_feed = []
    label_feed = []
    bucket_index = random.randint(0, len(genuine_data) - 1)
    bucket = genuine_data[bucket_index]
    for i in range(batch_size):
        index = random.randint(0, len(bucket) - 1)
        data = bucket[index]
        s_feed.append(data['signature'])
        label_feed.append(data['label'])

    return bucket_index, s_feed, label_feed

def train():
    sess = tf.Session()
    with sess.as_default():
        global_step = tf.Variable(0, name='global_step')
        update_global_step = tf.assign(global_step, global_step + 1)

        rhs = RHS()
        x = tf.placeholder(tf.float32, shape=(batch_size, None, 7))
        labels = tf.placeholder(tf.int32)
        loss = rhs.train(x, labels)
        train_op = tf.train.AdamOptimizer(learning_rate=rate).minimize(loss)

        summary = tf.summary.merge_all()
        run_metadata = tf.RunMetadata()
        summary_writer = tf.summary.FileWriter(log_dir, sess.graph)
        sess.run(tf.global_variables_initializer())

        saver = tf.train.Saver()
        checkpoint = tf.train.get_checkpoint_state(model_dir)
        if checkpoint:
            saver.restore(sess, checkpoint.model_checkpoint_path)

        step = global_step.eval()
        while step < loop:
            start_time = time.time()
            print('step: {}'.format(step))
            bucket_index, s_feed, labels_feed = get_feed()
            summary_str, step_loss, _ = sess.run([summary, loss, train_op], feed_dict={x: s_feed, labels: labels_feed})
            summary_writer.add_summary(summary_str, step)
            print('bucket: {} loss: {}'.format(bucket_index, step_loss))

            if step % 1000 == 999 and step != 0:
                checkpoint_file = os.path.join(model_dir, 'model')
                saver.save(sess, checkpoint_file, global_step)
                summary_writer.add_run_metadata(run_metadata, 'step%03d' % step)
            print("step cost: {0}".format(time.time() - start_time))
            sess.run(update_global_step)
            step = step + 1

        summary_writer.close()

def normalize(data, max_length=None):
    if (max_length and (len(data) > max_length)):
        data = data[0: max_length]
    data = np.array(data, np.float32)
    data[:, 0], std_x = norm(data[:, 0])
    data[:, 1], _ = norm(data[:, 1], std_x)
    prev_x = 0
    prev_y = 0
    normalized_data = []
    for point in data:
        normalized_data.append([point[0] - prev_x, point[1] - prev_y, point[2], point[3], point[4]])
        prev_x = point[0]
        prev_y = point[1]
    return np.array(normalized_data, np.float32)

def infer(reference, target, max_length=None):
    reference = normalize(reference, max_length)
    target = normalize(target)
    sess = tf.Session()
    with sess.as_default():
        rhs = RHS()
        saver = tf.train.Saver()
        checkpoint = tf.train.get_checkpoint_state(model_dir)
        saver.restore(sess, checkpoint.model_checkpoint_path)
        reference = rhs.run([reference]);
        target = rhs.run([target])
        distance = tf.reduce_mean(tf.square(reference - target))
        distance = sess.run(distance)
        print(distance)

if __name__ == '__main__':
    train()
<commit_msg>bug fix<commit_after>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
import time
from RHS import RHS
from ATVS_reader import *
import random
import os

batch_size = 48
class_num = 350
rate = 0.0001
loop = 1000000

log_dir = './log'
model_dir = './model'

genuine_data = bucket_group()

def get_feed():
    s_feed = []
    label_feed = []
    bucket_index = random.randint(0, len(genuine_data) - 1)
    bucket = genuine_data[bucket_index]
    for i in range(batch_size):
        index = random.randint(0, len(bucket) - 1)
        data = bucket[index]
        s_feed.append(data['signature'])
        label_feed.append(data['label'])

    return bucket_index, s_feed, label_feed

def train():
    sess = tf.Session()
    with sess.as_default():
        global_step = tf.Variable(0, name='global_step')
        update_global_step = tf.assign(global_step, global_step + 1)

        rhs = RHS()
        x = tf.placeholder(tf.float32, shape=(batch_size, None, 5))
        labels = tf.placeholder(tf.int32)
        loss = rhs.train(x, labels)
        train_op = tf.train.AdamOptimizer(learning_rate=rate).minimize(loss)

        summary = tf.summary.merge_all()
        run_metadata = tf.RunMetadata()
        summary_writer = tf.summary.FileWriter(log_dir, sess.graph)
        sess.run(tf.global_variables_initializer())

        saver = tf.train.Saver()
        checkpoint = tf.train.get_checkpoint_state(model_dir)
        if checkpoint:
            saver.restore(sess, checkpoint.model_checkpoint_path)

        step = global_step.eval()
        while step < loop:
            start_time = time.time()
            print('step: {}'.format(step))
            bucket_index, s_feed, labels_feed = get_feed()
            summary_str, step_loss, _ = sess.run([summary, loss, train_op], feed_dict={x: s_feed, labels: labels_feed})
            summary_writer.add_summary(summary_str, step)
            print('bucket: {} loss: {}'.format(bucket_index, step_loss))

            if step % 1000 == 999 and step != 0:
                checkpoint_file = os.path.join(model_dir, 'model')
                saver.save(sess, checkpoint_file, global_step)
                summary_writer.add_run_metadata(run_metadata, 'step%03d' % step)
            print("step cost: {0}".format(time.time() - start_time))
            sess.run(update_global_step)
            step = step + 1

        summary_writer.close()

def normalize(data, max_length=None):
    if (max_length and (len(data) > max_length)):
        data = data[0: max_length]
    data = np.array(data, np.float32)
    data[:, 0], std_x = norm(data[:, 0])
    data[:, 1], _ = norm(data[:, 1], std_x)
    prev_x = 0
    prev_y = 0
    normalized_data = []
    for point in data:
        normalized_data.append([point[0] - prev_x, point[1] - prev_y, point[2], point[3], point[4]])
        prev_x = point[0]
        prev_y = point[1]
    return np.array(normalized_data, np.float32)

def infer(reference, target, max_length=None):
    reference = normalize(reference, max_length)
    target = normalize(target)
    sess = tf.Session()
    with sess.as_default():
        rhs = RHS()
        saver = tf.train.Saver()
        checkpoint = tf.train.get_checkpoint_state(model_dir)
        saver.restore(sess, checkpoint.model_checkpoint_path)
        reference = rhs.run([reference]);
        target = rhs.run([target])
        distance = tf.reduce_mean(tf.square(reference - target))
        distance = sess.run(distance)
        print(distance)

if __name__ == '__main__':
    train()
<|endoftext|>


<commit_before>#
# Copyright (c) 2016, SUSE LLC
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of ceph-auto-aws nor the names of its contributors may be
# used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
import logging
import pyaml
import yaml

from handson.error import error_exit

log = logging.getLogger(__name__)

tree_stanzas = [
    'cluster-definition',
    'delegates',
    'keyname',
    'region',
    'role-definitions',
    'subnets',
    'types',
    'vpc',
]

role_definition_keys = [
    'ami-id',
    'instance',
    'replace-from-environment',
    'type',
    'user-data',
    'volume',
]

class MyYaml(object):

    def __init__(self, yamlfile):
        self._yaml = {}
        self.yaml_file_name(yamlfile)

    def yaml_file_name(self, fn=None):
        if 'yaml_file_name' not in self._yaml:
            self._yaml['yaml_file_name'] = fn
        return self._yaml['yaml_file_name']

    def tree(self):
        # log.debug("{!r}".format(self._yaml))
        if 'tree' not in self._yaml:
            self.load()
            tree = self._yaml['tree']
            if type(tree) is not dict:  # pragma: no cover
                error_exit("yaml file is totally munged")
            for stanza in tree_stanzas:
                if stanza not in tree_stanzas:  # pragma: no cover
                    error_exit("{!r} stanza missing in yaml file"
                               .format(stanza))
        return self._yaml['tree']

    def write(self):  # pragma: no cover
        fn = self.yaml_file_name()
        tree = self.tree()
        with open(fn, 'w') as outfile:
            outfile.write(
                pyaml.dump(tree, vspacing=[1, 0])
            )

    def load(self, yaml_file=None):
        if yaml_file is None:
            yaml_file = self.yaml_file_name()
        log.debug("yaml_file is {!r}".format(yaml_file))
        f = open(yaml_file)
        self._yaml['tree'] = yaml.safe_load(f)
        f.close()
        log.info("Loaded yaml from {}".format(yaml_file))

    def validate_role_definitions(self):  # pragma: no cover
        tree = self.tree()
        stanza = tree['role-definitions']
        if type(stanza) is not dict:
            error_exit("role-definitions stanza is not a mapping")
        roles = []
        for role in stanza:
            log.debug("Considering role definition {!r}".format(role))
            roles.append(role)
            role_def = stanza[role]
            if role_def is None:
                continue
            if type(role_def) is not dict:
                error_exit("Role definition {!r} is not a mapping"
                           .format(role))
            for key in role_def:
                log.debug("Considering whether key {!r} is in {!r}"
                          .format(key, role_definition_keys))
                if key not in role_definition_keys:
                    error_exit(
                        "Role definition {!r} contains illegal attribute {!r}"
                        .format(role, key)
                    )
        log.info("Detected roles {!r}".format(roles))
        return roles

    def role_exists(self, role):
        tree = self.tree()
        stanza = tree['role-definitions']
        return True if role in stanza else False

    def validate_cluster_definition(self):  # pragma: no cover
        tree = self.tree()
        cluster_def = tree['cluster-definition']
        if cluster_def is None:
            error_exit("cluster-definition stanza is empty")
        if type(cluster_def) is not list:
            error_exit("cluster-definition is not a sequence")
        if len(cluster_def) < 1:
            error_exit("cluster-definition stanza is empty")
        log.info("Detected cluster-definition stanza")
        roles = []
        for instance_def in cluster_def:
            log.debug("Considering instance definition {!r}"
                      .format(instance_def))
            if type(instance_def) is not dict:
                error_exit("Instance definition is not a mapping")
            if len(instance_def.items()) < 0:
                error_exit("Instance definition is empty")
            if len(instance_def.items()) > 1:
                error_exit("Instance definition contains more than one "
                           "attribute")
            log.debug("Instance definition {!r}".format(instance_def.items()))
            key = instance_def.items()[0][0]
            if key != 'role':
                error_exit("Instance definition key is not 'role'")
            val = instance_def[key]
            if val is None:
                error_exit("Detected empty 'role' attribute in cluster "
                           "definition")
            if type(val) is not str:
                error_exit("Detected non-string 'role' attribute in cluster "
                           "definition")
            if val in roles:
                error_exit("Detected duplicate role {!r} in cluster definition"
                           .format(val))
            log.info("Detected role {!r} in cluster definition".format(val))
            if val.lower() == "defaults":
                error_exit("Detected bogus role {!r} in cluster definition"
                           .format(val))
            roles.append(val)
            if not self.role_exists(val):
                error_exit("Role {!r} is undefined".format(val))
        return True
<commit_msg>myyaml.py: make validate_role_definitions() validate type<commit_after>#
# Copyright (c) 2016, SUSE LLC
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of ceph-auto-aws nor the names of its contributors may be
# used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
import logging
import pyaml
import yaml

from handson.error import error_exit

log = logging.getLogger(__name__)

tree_stanzas = [
    'cluster-definition',
    'delegates',
    'keyname',
    'region',
    'role-definitions',
    'subnets',
    'types',
    'vpc',
]

role_definition_keys = [
    'ami-id',
    'instance',
    'replace-from-environment',
    'type',
    'user-data',
    'volume',
]

class MyYaml(object):

    def __init__(self, yamlfile):
        self._yaml = {}
        self.yaml_file_name(yamlfile)

    def yaml_file_name(self, fn=None):
        if 'yaml_file_name' not in self._yaml:
            self._yaml['yaml_file_name'] = fn
        return self._yaml['yaml_file_name']

    def tree(self):
        # log.debug("{!r}".format(self._yaml))
        if 'tree' not in self._yaml:
            self.load()
            tree = self._yaml['tree']
            if type(tree) is not dict:  # pragma: no cover
                error_exit("yaml file is totally munged")
            for stanza in tree_stanzas:
                if stanza not in tree_stanzas:  # pragma: no cover
                    error_exit("{!r} stanza missing in yaml file"
                               .format(stanza))
        return self._yaml['tree']

    def write(self):  # pragma: no cover
        fn = self.yaml_file_name()
        tree = self.tree()
        with open(fn, 'w') as outfile:
            outfile.write(
                pyaml.dump(tree, vspacing=[1, 0])
            )

    def load(self, yaml_file=None):
        if yaml_file is None:
            yaml_file = self.yaml_file_name()
        log.debug("yaml_file is {!r}".format(yaml_file))
        f = open(yaml_file)
        self._yaml['tree'] = yaml.safe_load(f)
        f.close()
        log.info("Loaded yaml from {}".format(yaml_file))

    def validate_role_definitions(self):  # pragma: no cover
        tree = self.tree()
        types = tree['types']
        stanza = tree['role-definitions']
        if type(stanza) is not dict:
            error_exit("role-definitions stanza is not a mapping")
        roles = []
        for role in stanza:
            log.debug("Detected definition stanza of role {!r}".format(role))
            roles.append(role)
            role_def = stanza[role]
            if role_def is None:
                continue
            if type(role_def) is not dict:
                error_exit("Role definition {!r} is not a mapping"
                           .format(role))
            for key in role_def:
                log.debug("Considering role definition {!r}".format(role_def))
                log.debug("Considering whether key {!r} is in {!r}"
                          .format(key, role_definition_keys))
                if key not in role_definition_keys:
                    error_exit(
                        "Role definition {!r} contains illegal attribute {!r}"
                        .format(role, key)
                    )
                val = role_def[key]
                if key == 'type' and val not in types:
                    error_exit(
                        "Illegal type {!r} detected in role definition {!r}"
                        .format(val, role)
                    )
                keys.append(key)
        log.info("Detected roles {!r}".format(roles))
        return roles

    def role_exists(self, role):
        tree = self.tree()
        stanza = tree['role-definitions']
        return True if role in stanza else False

    def validate_cluster_definition(self):  # pragma: no cover
        tree = self.tree()
        cluster_def = tree['cluster-definition']
        if cluster_def is None:
            error_exit("cluster-definition stanza is empty")
        if type(cluster_def) is not list:
            error_exit("cluster-definition is not a sequence")
        if len(cluster_def) < 1:
            error_exit("cluster-definition stanza is empty")
        log.info("Detected cluster-definition stanza")
        roles = []
        for instance_def in cluster_def:
            log.debug("Considering instance definition {!r}"
                      .format(instance_def))
            if type(instance_def) is not dict:
                error_exit("Instance definition is not a mapping")
            if len(instance_def.items()) < 0:
                error_exit("Instance definition is empty")
            if len(instance_def.items()) > 1:
                error_exit("Instance definition contains more than one "
                           "attribute")
            log.debug("Instance definition {!r}".format(instance_def.items()))
            key = instance_def.items()[0][0]
            if key != 'role':
                error_exit("Instance definition key is not 'role'")
            val = instance_def[key]
            if val is None:
                error_exit("Detected empty 'role' attribute in cluster "
                           "definition")
            if type(val) is not str:
                error_exit("Detected non-string 'role' attribute in cluster "
                           "definition")
            if val in roles:
                error_exit("Detected duplicate role {!r} in cluster definition"
                           .format(val))
            log.info("Detected role {!r} in cluster definition".format(val))
            if val.lower() == "defaults":
                error_exit("Detected bogus role {!r} in cluster definition"
                           .format(val))
            roles.append(val)
            if not self.role_exists(val):
                error_exit("Role {!r} is undefined".format(val))
        return True
<|endoftext|>


<commit_before>'''
accept_risks
============

NOTE: not currently tested code.

The following methods allow for interaction into the Tenable.sc
`Accept Risk <https://docs.tenable.com/sccv/api/Accept-Risk-Rule.html>`_ API.

Methods available on ``sc.accept_risks``:

.. rst-class:: hide-signature
.. autoclass:: AcceptRiskAPI

    .. automethod:: apply
    .. automethod:: create
    .. automethod:: delete
    .. automethod:: details
    .. automethod:: list
    .. automethod:: update
'''
from .base import SCEndpoint

class AcceptRiskAPI(SCEndpoint):
    def _constructor(self, **kw):
        '''
        document creator for acceptRisk creation and update calls.
        '''
        if 'repos' in kw:
            # as repositories are passed in the API as a series of sub-documents
            # with the ID attribute set, we will convert the simply list that
            # was passed to us into a series of documents as the API expects.
            kw['repositories'] = [{'id': self._check('repo:id', r, int)}
                for r in self._check('repos', kw['repos'], list)]
            del(kw['repos'])

        if 'plugin_id' in kw:
            # the plugin parameter
            kw['plugin'] = {'id': self._check('plugin_id', kw['plugin_id'], int)}
            del(kw['plugin_id'])

        if 'port' in kw:
            # as the port will only be passed if the default of "any" isn't
            # desired, we should check to make sure that the value passed is an
            # integer, and then convert it into a string.
            kw['protocol'] = str(self._check('port', kw['port'], int))

        if 'protocol' in kw:
            # as the protocol will only be passed if the default of "any" isn't
            # desired, we should check to make sure that the value passed is an
            # integer, and then convert it into a string.
            kw['protocol'] = str(self._check('protocol', kw['protocol'], int))

        if 'comments' in kw:
            # if a comment is attached to the rule, then lets just make sure
            # that we actually have a string here before moving on.
            self._check('comments', kw['comments'], str)

        if 'expires' in kw:
            # how many days until the accept risk rule expires?  We should
            # simply checkt o see if the value is an integer.
            self._check('expires', kw['expires'], int)

        if 'ips' in kw:
            # if the ips list is passed, then
            kw['hostType'] = 'ip'
            kw['hostValue'] = ','.join(self._check('ips', kw['ips'], list))
            del(kw['ips'])

        if 'uuids' in kw:
            kw['hostType'] = 'uuid'
            kw['hostValue'] = ','.join(self._check('uuids', kw['uuids'], list))
            del(kw['uuids'])

        if 'asset_list' in kw:
            kw['hostType'] = 'asset'
            kw['hostValue'] = {'id': self._check('asset_list', kw['asset_list'], int)}
            del(kw['asset_list'])

        return kw

    def list(self, fields=None):
        '''
        Retreives the list of accepted risk rules.

        + `SC Accept Risk List <https://docs.tenable.com/sccv/api/Accept-Risk-Rule.html#AcceptRiskRuleRESTReference-/acceptRiskRule>`_

        Args:
            fields (list, optional):
                A list of attributes to return for each accepted risk rule.

        Returns:
            list: A list of accepted risk rules.

        Examples:
            >>> for rule in sc.accept_risks.list():
            ...     pprint(rule)
        '''
        params = dict()
        if fields:
            params['fields'] = ','.join([self._check('field', f, str)
                for f in fields])

        return self._api.get('acceptRisk', params=params).json()['response']

    def details(self, id, fields=None):
        '''
        Retreives the details of an accepted risk rule.

        + `SC Accept Risk Details <https://docs.tenable.com/sccv/api/Accept-Risk-Rule.html#AcceptRiskRuleRESTReference-/acceptRiskRule/{id}>`_

        Args:
            id (int): The identifier for the accept risk rule.
            fields (list, optional):
                A list of attributes to return for each accepted risk rule.

        Returns:
            dict: The accept risk rule details.

        Examples:
            >>> rule = sc.accept_risks.details(1)
            >>> pprint(rule)
        '''
        params = dict()
        if fields:
            params['fields'] = ','.join([self._check('field', f, str)
                for f in fields])

        return self._api.get('acceptRisk/{}'.format(self._check('id', id, int)),
            params=params).json()['response']

    def delete(self, id):
        '''
        Removes the accepted risk rule from Tenable.sc

        + `SC Accept Risk Delete <https://docs.tenable.com/sccv/api/Accept-Risk-Rule.html#acceptRiskRule_id_DELETE>`_

        Args:
            id (int): The identifier for the accept risk rule.

        Returns:
            str: Empty string reponse from the API.

        Examples:
            >>> sc.accept_risks.delete(1)
        '''
        return self._api.delete('acceptRisk/{}'.format(
            self._check('id', id, int))).json()['response']

    def apply(self, id, repo=None):
        '''
        Applies the accept risk rule for either all repositories, or the
        repository specified.

        + `SC Accept Risk Apply <https://docs.tenable.com/sccv/api/Accept-Risk-Rule.html#AcceptRiskRuleRESTReference-/acceptRiskRule/apply>`_

        Args:
            id (int): The identifier for the accept risk rule.
            repo (int, optional):
                A specific repository to apply the rule to.  The default if not
                specified is all repositories (``0``).

        Returns:
            str: Empty string reponse from the API.

        Examples:
            >>> sc.accept_risks.apply(1)
        '''
        payload = dict()
        if repo:
            payload['repository'] = {'id': self._check('repo', repo, int)}

        return self._api.post('acceptRisk/{}/apply'.format(
            self._check('id', id, int)), json=payload).json()['response']

    def create(self, plugin_id, repos, **kw):
        '''
        Creates a new accept risk rule.  Either ips, uuids, or asset_list must
        be specified.

        + `SC Accept Risk Create <https://docs.tenable.com/sccv/api/Accept-Risk-Rule.html#acceptRiskRule_POST>`_

        Args:
            plugin_id (int): The plugin to apply the accept risk rule to.
            repos (list):
                The list of repositories to apply this accept risk rule to.
            asset_list (int, optional):
                The asset list id to apply the accept risk rule to.  Please note
                that ``asset_list``, ``ips``, and ``uuids`` are mutually
                exclusive.
            comments (str, optional):
                The comment associated to the accept risk rule.
            expires (int, optional):
                When should the rule expire?  if no expiration is set, the rule
                will never expire.
            ips (list, optional):
                A list of IPs to apply the accept risk rule to.  Please note
                that ``asset_list``, ``ips``, and ``uuids`` are mutually
                exclusive.
            port (int, optional):
                The port to restrict this accept risk rule to.  The default is
                unrestricted.
            protocol (int, optional):
                The protocol to restrict the accept risk rule to.  The default
                is unrestricted.
            uuids (list, optional):
                The agent uuids to apply the accept risk rule to.  Please note
                that ``asset_list``, ``ips``, and ``uuids`` are mutually
                exclusive.

        Returns:
            dict: The newly created accept risk rule definition.

        Examples:
            Create a rule to accept 97737 on 2 IPs for 90 days.

            >>> rule = sc.accept_risks.create(97737, [1],
            ...     ips=['192.168.0.101', '192.168.0.102'], expires=90)
        '''
        kw['plugin_id'] = plugin_id
        kw['repos'] = repos
        payload = self._constructor(**kw)

        return self._api.post('acceptRisk', json=payload).json()['response']

    def update(self, id, **kw):
        '''
        Creates a new accept risk rule.  Either ips, uuids, or asset_list must
        be specified.

        + `SC Accept Risk Create <https://docs.tenable.com/sccv/api/Accept-Risk-Rule.html#acceptRiskRule_POST>`_

        Args:
            id (int):
                The identifier for the accept risk rule.
            asset_list (int, optional):
                The asset list id to apply the accept risk rule to.  Please note
                that ``asset_list``, ``ips``, and ``uuids`` are mutually
                exclusive.
            comments (str, optional):
                The comment associated to the accept risk rule.
            expires (int, optional):
                When should the rule expire?  if no expiration is set, the rule
                will never expire.
            ips (list, optional):
                A list of IPs to apply the accept risk rule to.  Please note
                that ``asset_list``, ``ips``, and ``uuids`` are mutually
                exclusive.
            plugin_id (int, optional):
                The plugin to apply the accept risk rule to.
            port (int, optional):
                The port to restrict this accept risk rule to.  The default is
                unrestricted.
            protocol (int, optional):
                The protocol to restrict the accept risk rule to.  The default
                is unrestricted.
            repos (list):
                The list of repositories to apply this accept risk rule to.
            uuids (list, optional):
                The agent uuids to apply the accept risk rule to.  Please note
                that ``asset_list``, ``ips``, and ``uuids`` are mutually
                exclusive.

        Returns:
            dict: The newly created accept risk rule definition.

        Examples:
            Update the rule to accept 97737 on 2 IPs for 90 days.

            >>> rule = sc.accept_risks.update(1,
            ...     ips=['192.168.0.101', '192.168.0.102'], expires=90)
        '''
        payload = self._constructor(**kw)

        return self._api.patch('acceptRisk/{}'.format(
            self._check('id', id, int)), json=payload).json()['response']
<commit_msg>‘acceptRisk’ should be ‘acceptRiskRule’<commit_after>'''
accept_risks
============

NOTE: not currently tested code.

The following methods allow for interaction into the Tenable.sc
`Accept Risk <https://docs.tenable.com/sccv/api/Accept-Risk-Rule.html>`_ API.

Methods available on ``sc.accept_risks``:

.. rst-class:: hide-signature
.. autoclass:: AcceptRiskAPI

    .. automethod:: apply
    .. automethod:: create
    .. automethod:: delete
    .. automethod:: details
    .. automethod:: list
    .. automethod:: update
'''
from .base import SCEndpoint

class AcceptRiskAPI(SCEndpoint):
    def _constructor(self, **kw):
        '''
        document creator for acceptRisk creation and update calls.
        '''
        if 'repos' in kw:
            # as repositories are passed in the API as a series of sub-documents
            # with the ID attribute set, we will convert the simply list that
            # was passed to us into a series of documents as the API expects.
            kw['repositories'] = [{'id': self._check('repo:id', r, int)}
                for r in self._check('repos', kw['repos'], list)]
            del(kw['repos'])

        if 'plugin_id' in kw:
            # the plugin parameter
            kw['plugin'] = {'id': self._check('plugin_id', kw['plugin_id'], int)}
            del(kw['plugin_id'])

        if 'port' in kw:
            # as the port will only be passed if the default of "any" isn't
            # desired, we should check to make sure that the value passed is an
            # integer, and then convert it into a string.
            kw['protocol'] = str(self._check('port', kw['port'], int))

        if 'protocol' in kw:
            # as the protocol will only be passed if the default of "any" isn't
            # desired, we should check to make sure that the value passed is an
            # integer, and then convert it into a string.
            kw['protocol'] = str(self._check('protocol', kw['protocol'], int))

        if 'comments' in kw:
            # if a comment is attached to the rule, then lets just make sure
            # that we actually have a string here before moving on.
            self._check('comments', kw['comments'], str)

        if 'expires' in kw:
            # how many days until the accept risk rule expires?  We should
            # simply checkt o see if the value is an integer.
            self._check('expires', kw['expires'], int)

        if 'ips' in kw:
            # if the ips list is passed, then
            kw['hostType'] = 'ip'
            kw['hostValue'] = ','.join(self._check('ips', kw['ips'], list))
            del(kw['ips'])

        if 'uuids' in kw:
            kw['hostType'] = 'uuid'
            kw['hostValue'] = ','.join(self._check('uuids', kw['uuids'], list))
            del(kw['uuids'])

        if 'asset_list' in kw:
            kw['hostType'] = 'asset'
            kw['hostValue'] = {'id': self._check('asset_list', kw['asset_list'], int)}
            del(kw['asset_list'])

        return kw

    def list(self, fields=None):
        '''
        Retreives the list of accepted risk rules.

        + `SC Accept Risk List <https://docs.tenable.com/sccv/api/Accept-Risk-Rule.html#AcceptRiskRuleRESTReference-/acceptRiskRule>`_

        Args:
            fields (list, optional):
                A list of attributes to return for each accepted risk rule.

        Returns:
            list: A list of accepted risk rules.

        Examples:
            >>> for rule in sc.accept_risks.list():
            ...     pprint(rule)
        '''
        params = dict()
        if fields:
            params['fields'] = ','.join([self._check('field', f, str)
                for f in fields])

        return self._api.get('acceptRiskRule', params=params).json()['response']

    def details(self, id, fields=None):
        '''
        Retreives the details of an accepted risk rule.

        + `SC Accept Risk Details <https://docs.tenable.com/sccv/api/Accept-Risk-Rule.html#AcceptRiskRuleRESTReference-/acceptRiskRule/{id}>`_

        Args:
            id (int): The identifier for the accept risk rule.
            fields (list, optional):
                A list of attributes to return for each accepted risk rule.

        Returns:
            dict: The accept risk rule details.

        Examples:
            >>> rule = sc.accept_risks.details(1)
            >>> pprint(rule)
        '''
        params = dict()
        if fields:
            params['fields'] = ','.join([self._check('field', f, str)
                for f in fields])

        return self._api.get('acceptRiskRule/{}'.format(self._check('id', id, int)),
            params=params).json()['response']

    def delete(self, id):
        '''
        Removes the accepted risk rule from Tenable.sc

        + `SC Accept Risk Delete <https://docs.tenable.com/sccv/api/Accept-Risk-Rule.html#acceptRiskRule_id_DELETE>`_

        Args:
            id (int): The identifier for the accept risk rule.

        Returns:
            str: Empty string reponse from the API.

        Examples:
            >>> sc.accept_risks.delete(1)
        '''
        return self._api.delete('acceptRiskRule/{}'.format(
            self._check('id', id, int))).json()['response']

    def apply(self, id, repo=None):
        '''
        Applies the accept risk rule for either all repositories, or the
        repository specified.

        + `SC Accept Risk Apply <https://docs.tenable.com/sccv/api/Accept-Risk-Rule.html#AcceptRiskRuleRESTReference-/acceptRiskRule/apply>`_

        Args:
            id (int): The identifier for the accept risk rule.
            repo (int, optional):
                A specific repository to apply the rule to.  The default if not
                specified is all repositories (``0``).

        Returns:
            str: Empty string reponse from the API.

        Examples:
            >>> sc.accept_risks.apply(1)
        '''
        payload = dict()
        if repo:
            payload['repository'] = {'id': self._check('repo', repo, int)}

        return self._api.post('acceptRiskRule/{}/apply'.format(
            self._check('id', id, int)), json=payload).json()['response']

    def create(self, plugin_id, repos, **kw):
        '''
        Creates a new accept risk rule.  Either ips, uuids, or asset_list must
        be specified.

        + `SC Accept Risk Create <https://docs.tenable.com/sccv/api/Accept-Risk-Rule.html#acceptRiskRule_POST>`_

        Args:
            plugin_id (int): The plugin to apply the accept risk rule to.
            repos (list):
                The list of repositories to apply this accept risk rule to.
            asset_list (int, optional):
                The asset list id to apply the accept risk rule to.  Please note
                that ``asset_list``, ``ips``, and ``uuids`` are mutually
                exclusive.
            comments (str, optional):
                The comment associated to the accept risk rule.
            expires (int, optional):
                When should the rule expire?  if no expiration is set, the rule
                will never expire.
            ips (list, optional):
                A list of IPs to apply the accept risk rule to.  Please note
                that ``asset_list``, ``ips``, and ``uuids`` are mutually
                exclusive.
            port (int, optional):
                The port to restrict this accept risk rule to.  The default is
                unrestricted.
            protocol (int, optional):
                The protocol to restrict the accept risk rule to.  The default
                is unrestricted.
            uuids (list, optional):
                The agent uuids to apply the accept risk rule to.  Please note
                that ``asset_list``, ``ips``, and ``uuids`` are mutually
                exclusive.

        Returns:
            dict: The newly created accept risk rule definition.

        Examples:
            Create a rule to accept 97737 on 2 IPs for 90 days.

            >>> rule = sc.accept_risks.create(97737, [1],
            ...     ips=['192.168.0.101', '192.168.0.102'], expires=90)
        '''
        kw['plugin_id'] = plugin_id
        kw['repos'] = repos
        payload = self._constructor(**kw)

        return self._api.post('acceptRiskRule', json=payload).json()['response']

    def update(self, id, **kw):
        '''
        Creates a new accept risk rule.  Either ips, uuids, or asset_list must
        be specified.

        + `SC Accept Risk Create <https://docs.tenable.com/sccv/api/Accept-Risk-Rule.html#acceptRiskRule_POST>`_

        Args:
            id (int):
                The identifier for the accept risk rule.
            asset_list (int, optional):
                The asset list id to apply the accept risk rule to.  Please note
                that ``asset_list``, ``ips``, and ``uuids`` are mutually
                exclusive.
            comments (str, optional):
                The comment associated to the accept risk rule.
            expires (int, optional):
                When should the rule expire?  if no expiration is set, the rule
                will never expire.
            ips (list, optional):
                A list of IPs to apply the accept risk rule to.  Please note
                that ``asset_list``, ``ips``, and ``uuids`` are mutually
                exclusive.
            plugin_id (int, optional):
                The plugin to apply the accept risk rule to.
            port (int, optional):
                The port to restrict this accept risk rule to.  The default is
                unrestricted.
            protocol (int, optional):
                The protocol to restrict the accept risk rule to.  The default
                is unrestricted.
            repos (list):
                The list of repositories to apply this accept risk rule to.
            uuids (list, optional):
                The agent uuids to apply the accept risk rule to.  Please note
                that ``asset_list``, ``ips``, and ``uuids`` are mutually
                exclusive.

        Returns:
            dict: The newly created accept risk rule definition.

        Examples:
            Update the rule to accept 97737 on 2 IPs for 90 days.

            >>> rule = sc.accept_risks.update(1,
            ...     ips=['192.168.0.101', '192.168.0.102'], expires=90)
        '''
        payload = self._constructor(**kw)

        return self._api.patch('acceptRiskRule/{}'.format(
            self._check('id', id, int)), json=payload).json()['response']
<|endoftext|>