<commit_before>import logging
l = logging.getLogger('angr.path_heirarchy')

import weakref

class PathHeirarchy(object):
    def __init__(self):
        self._parents = { }
        self._successors = { }
        self._good = set()
        self._path_mapping = weakref.WeakValueDictionary()

    def _lineage(self, se):
        lineage = [ ]

        cur = se
        while cur in self._parents:
            cur = self._parents[cur]
            lineage.append(cur)

        lineage.reverse()
        return lineage

    def _all_successors(self, se):
        todo = [ se ]

        while len(todo) != 0:
            cur = todo.pop()
            if cur in self._successors:
                todo.extend(self._successors[cur])
            yield cur

    def _find_root_unreachable(self, se):
        lineage = self._lineage(se)
        if len(lineage) == 0 or lineage[-1].reachable:
            return se

        good = max([0] + [ i for i,s in enumerate(lineage) if s in self._good ])
        bad = len(lineage) - 1

        while True:
            l.debug("... looking between %d and %d in %d paths", good, bad, len(lineage))
            cur = (bad+good)/2

            if cur == good or cur == bad:
                if lineage[bad].satisfiable():
                    self._good.add(lineage[bad])
                    bad += 1

                root = lineage[bad]
                l.debug("... returning %d (%s)", bad, root)
                return root
            elif lineage[cur].satisfiable():
                l.debug("... %d is reachable", cur)
                self._good.add(lineage[cur])
                good = cur
            else:
                l.debug("... %d is unreachable", bad)
                bad = cur

    def _prune(self, se):
        for c in self._all_successors(se):
            l.debug("... pruning %s", c)

            try:
                p = self._path_mapping[c]
                if not p._error:
                    p.error = PathUnreachableError('ancestral path %s is unreachable' % p)
                    p._reachable = False
            except KeyError:
                pass

            self._remove(c)
        self._remove(se)

    def _remove(self, se):
        if se in self._parents:
            del self._parents[se]
        if se in self._successors:
            del self._successors[se]

    def unreachable(self, p):
        se = p.state.se

        l.debug("Pruning tree given unreachable %s", se)
        root = self._find_root_unreachable(se)
        l.debug("... root is %s", root)
        self._prune(root)

    def add_successors(self, p, successors):
        l.debug("Adding %d successors for %s", len(successors), p)
        if p.state.se not in self._successors:
            self._successors[p.state.se] = [ ]

        self._successors[p.state.se].extend(successors)
        for s in successors:
            self._parents[s] = p.state.se

from .errors import PathUnreachableError
<commit_msg>fixed *lots* of issue with hierarchies<commit_after>import logging
l = logging.getLogger('angr.path_heirarchy')

import weakref

class PathHeirarchy(object):
    def __init__(self):
        self._parents = { }
        self._successors = { }
        self._good = set()
        self._path_mapping = weakref.WeakValueDictionary()
        #self._path_mapping = { }

    def _lineage(self, se):
        lineage = [ ]

        cur = se
        while cur in self._parents:
            cur = self._parents[cur]
            lineage.append(cur)

        lineage.reverse()

        return lineage

    def _all_successors(self, se):
        todo = [ se ]
        successors = [ ]

        while len(todo) != 0:
            cur = todo.pop()
            if cur in self._successors:
                todo += self._successors[cur]
            successors.append(cur)

        return successors

    def _is_reachable(self, se):
        if se in self._good:
            return True
        else:
            s = se._solver.satisfiable()
            if s:
                self._good.add(se)
            return s

    def _find_root_unreachable(self, se):
        lineage = self._lineage(se)
        if len(lineage) == 0 or self._is_reachable(lineage[-1]):
            return se

        good = max([0] + [ i for i,s in enumerate(lineage) if s in self._good ])
        bad = len(lineage) - 1

        while True:
            l.debug("... looking between %d and %d in %d paths", good, bad, len(lineage))
            cur = (bad+good)/2

            if cur == good or cur == bad:
                if self._is_reachable(lineage[bad]):
                    bad += 1

                root = lineage[bad]
                l.debug("... returning %d (%s)", bad, root)
                return root
            elif self._is_reachable(lineage[cur]):
                l.debug("... %d is reachable", cur)
                good = cur
            else:
                l.debug("... %d is unreachable", bad)
                bad = cur

    def _prune(self, se):
        to_prune = self._all_successors(se)
        to_prune.append(se)

        for c in to_prune:
            l.debug("... pruning %s", c)

            try:
                p = self._path_mapping[c]
                l.debug("... still there: %s", p)
                if not p._error:
                    p.error = PathUnreachableError('ancestral path %s is unreachable' % p)
                    p._reachable = False
            except KeyError:
                l.debug("... gc'ed: path of %s", c)

        for c in to_prune:
            self._remove(c)

        return to_prune

    def _remove(self, se):
        if se in self._parents:
            del self._parents[se]
        if se in self._successors:
            del self._successors[se]
        self._good.discard(se)

    def unreachable(self, p):
        se = p.state.se

        l.debug("Pruning tree given unreachable %s", se)
        root = self._find_root_unreachable(se)
        l.debug("... root is %s", root)
        self._prune(root)

        #paths = [ ]
        #for se in pruned:
        #   try:
        #       paths.append(self._path_mapping[se])
        #   except KeyError:
        #       pass
        #return paths

    def add_successors(self, p, successors):
        l.debug("Adding %d successors for %s", len(successors), p)

        if p.state.se not in self._successors:
            self._successors[p.state.se] = [ ]
        self._successors[p.state.se] += [ s.state.se for s in successors ]
        self._path_mapping[p.state.se] = p

        for s in successors:
            self._parents[s.state.se] = p.state.se
            self._path_mapping[s.state.se] = s

from .errors import PathUnreachableError
<|endoftext|>


<commit_before>#
#  Copyright (C) 2015-2020 by Last Run Contributors.
#
#  This file is part of Arena of Titans.
#
#  Arena of Titans is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Affero General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  Arena of Titans is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Affero General Public License for more details.
#
#  You should have received a copy of the GNU Affero General Public License
#  along with Arena of Titans. If not, see <http://www.gnu.org/licenses/>.
#

import dataclasses
import math
from enum import Enum

from aot.game import Player
from aot.game.board import Board, Square
from aot.game.cards import Card
from aot.game.trumps import Power
from aot.game.trumps.effects import TrumpEffect

from ..config import config
from ..utils import get_time
from .utils import RequestTypes

def get_global_game_message(game):
    return {
        "rt": RequestTypes.GAME_UPDATED,
        "request": get_global_game_state(game),
    }

def get_global_game_state(game):
    return {
        "id": game.game_id,
        "actions": game.actions,
        "board": game.board,
        "is_over": game.is_over,
        "current_player_index": game.active_player.index,
        "nb_turns": game.nb_turns,
        "players": {player.index: _get_public_player_state(player) for player in game.players},
        "winners": game.winners,
    }

def _get_public_player_state(player):
    return {
        "active_trumps": player.trump_effects,
        "square": player.current_square,
        "name": player.name,
        "index": player.index,
        "hero": player.hero,
        "is_visible": player.is_visible,
        "can_pawn_be_selected": player.can_pawn_be_selected,
    }

def get_private_player_messages_by_ids(game):
    messages = {}

    for player in game.players:
        if player is not None:
            messages[player.id] = [get_private_player_message(game, player)]

    return messages

def get_private_player_message(game, player):
    return {
        "rt": RequestTypes.PLAYER_UPDATED,
        "request": get_private_player_state(game, player),
    }

def get_private_player_state(game, player):
    # Since between the request arrives (game.active_player.turn_start_time) and the time we
    # get here some time has passed. Which means, the elapsed time sent to the frontend could
    # be greater than 0 at the beginning of a turn.
    elapsed_time = get_time() - game.active_player.turn_start_time
    if elapsed_time < config["api"]["min_elapsed_time_to_consider"]:
        elapsed_time = 0

    return {
        "name": player.name,
        "index": player.index,
        "id": player.id,
        "available_trumps": player.available_trumps,
        "hero": player.hero,
        "your_turn": player.id == game.active_player.id,
        "on_last_line": player.on_last_line,
        "has_won": player.has_won,
        "rank": player.rank,
        "hand": [
            {"name": card.name, "color": card.color, "description": card.description}
            for card in player.hand
        ],
        "active_trumps": player.trump_effects,
        "trump_target_indexes": [
            player.index for player in game.players if player and player.can_be_targeted_by_trumps
        ],
        "has_remaining_moves_to_play": player.has_remaining_moves_to_play,
        "trumps_statuses": player.trumps_statuses,
        "can_power_be_played": player.can_power_be_played,
        "gauge_value": player.gauge.value,
        "elapsed_time": elapsed_time,
        "power": player.power,
        "special_action": player.name_next_special_action,
    }

def to_json(python_object):  # noqa: C901 too complex
    if isinstance(python_object, Enum):
        return python_object.value
    elif isinstance(python_object, Square):
        return {
            "x": python_object.x,
            "y": python_object.y,
            "color": python_object.color,
        }
    elif isinstance(python_object, Board):
        return {"updated_squares": python_object.updated_squares}
    elif isinstance(python_object, TrumpEffect):
        data = {
            "duration": python_object.duration if not math.isinf(python_object.duration) else None,
            "name": python_object.name,
            "color": python_object.color,
            "effect_type": python_object.effect_type,
        }
        return data
    elif isinstance(python_object, (set, frozenset)):
        return [to_json(element) for element in python_object]
    elif isinstance(python_object, Player):
        return {
            "name": python_object.name,
            "index": python_object.index,
        }
    elif isinstance(python_object, Card):
        return {
            "name": python_object.name,
            "color": python_object.color,
        }
    elif dataclasses.is_dataclass(python_object) and not isinstance(python_object, type):
        # Our dataclasses may hold a reference to a class which we can't serialize into JSON.
        trump_like = {
            key: _remove_class_references(value)
            for key, value in dataclasses.asdict(python_object).items()
            if not isinstance(value, type)
        }
        trump_like = _inline_trump_args(trump_like)
        if isinstance(python_object, Power):
            trump_like["is_power"] = True
            trump_like["passive"] = python_object.passive

        return trump_like

    # Normally, this is unreachable
    raise TypeError(str(python_object) + " is not JSON serializable")  # pragma: no cover

def _remove_class_references(data):
    if not isinstance(data, dict):
        return data

    return {
        key: _remove_class_references(value)
        for key, value in data.items()
        if not isinstance(value, type)
    }

def _inline_trump_args(data):
    if not isinstance(data, dict):
        return data

    if "trump_args" in data:
        data = {
            **data,
            **data["trump_args"],
        }
        del data["trump_args"]

    return {key: _inline_trump_args(value) for key, value in data.items()}
<commit_msg>feat(serializer): limit the number of returned actions<commit_after>#
#  Copyright (C) 2015-2020 by Last Run Contributors.
#
#  This file is part of Arena of Titans.
#
#  Arena of Titans is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Affero General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  Arena of Titans is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Affero General Public License for more details.
#
#  You should have received a copy of the GNU Affero General Public License
#  along with Arena of Titans. If not, see <http://www.gnu.org/licenses/>.
#

import dataclasses
import math
from enum import Enum

from aot.game import Player
from aot.game.board import Board, Square
from aot.game.cards import Card
from aot.game.trumps import Power
from aot.game.trumps.effects import TrumpEffect

from ..config import config
from ..utils import get_time
from .utils import RequestTypes

def get_global_game_message(game):
    return {
        "rt": RequestTypes.GAME_UPDATED,
        "request": get_global_game_state(game),
    }

def get_global_game_state(game):
    return {
        "id": game.game_id,
        # Limit the number of returned actions to prevent slowdown in the frontend.
        "actions": game.actions[-30:],
        "board": game.board,
        "is_over": game.is_over,
        "current_player_index": game.active_player.index,
        "nb_turns": game.nb_turns,
        "players": {player.index: _get_public_player_state(player) for player in game.players},
        "winners": game.winners,
    }

def _get_public_player_state(player):
    return {
        "active_trumps": player.trump_effects,
        "square": player.current_square,
        "name": player.name,
        "index": player.index,
        "hero": player.hero,
        "is_visible": player.is_visible,
        "can_pawn_be_selected": player.can_pawn_be_selected,
    }

def get_private_player_messages_by_ids(game):
    messages = {}

    for player in game.players:
        if player is not None:
            messages[player.id] = [get_private_player_message(game, player)]

    return messages

def get_private_player_message(game, player):
    return {
        "rt": RequestTypes.PLAYER_UPDATED,
        "request": get_private_player_state(game, player),
    }

def get_private_player_state(game, player):
    # Since between the request arrives (game.active_player.turn_start_time) and the time we
    # get here some time has passed. Which means, the elapsed time sent to the frontend could
    # be greater than 0 at the beginning of a turn.
    elapsed_time = get_time() - game.active_player.turn_start_time
    if elapsed_time < config["api"]["min_elapsed_time_to_consider"]:
        elapsed_time = 0

    return {
        "name": player.name,
        "index": player.index,
        "id": player.id,
        "available_trumps": player.available_trumps,
        "hero": player.hero,
        "your_turn": player.id == game.active_player.id,
        "on_last_line": player.on_last_line,
        "has_won": player.has_won,
        "rank": player.rank,
        "hand": [
            {"name": card.name, "color": card.color, "description": card.description}
            for card in player.hand
        ],
        "active_trumps": player.trump_effects,
        "trump_target_indexes": [
            player.index for player in game.players if player and player.can_be_targeted_by_trumps
        ],
        "has_remaining_moves_to_play": player.has_remaining_moves_to_play,
        "trumps_statuses": player.trumps_statuses,
        "can_power_be_played": player.can_power_be_played,
        "gauge_value": player.gauge.value,
        "elapsed_time": elapsed_time,
        "power": player.power,
        "special_action": player.name_next_special_action,
    }

def to_json(python_object):  # noqa: C901 too complex
    if isinstance(python_object, Enum):
        return python_object.value
    elif isinstance(python_object, Square):
        return {
            "x": python_object.x,
            "y": python_object.y,
            "color": python_object.color,
        }
    elif isinstance(python_object, Board):
        return {"updated_squares": python_object.updated_squares}
    elif isinstance(python_object, TrumpEffect):
        data = {
            "duration": python_object.duration if not math.isinf(python_object.duration) else None,
            "name": python_object.name,
            "color": python_object.color,
            "effect_type": python_object.effect_type,
        }
        return data
    elif isinstance(python_object, (set, frozenset)):
        return [to_json(element) for element in python_object]
    elif isinstance(python_object, Player):
        return {
            "name": python_object.name,
            "index": python_object.index,
        }
    elif isinstance(python_object, Card):
        return {
            "name": python_object.name,
            "color": python_object.color,
        }
    elif dataclasses.is_dataclass(python_object) and not isinstance(python_object, type):
        # Our dataclasses may hold a reference to a class which we can't serialize into JSON.
        trump_like = {
            key: _remove_class_references(value)
            for key, value in dataclasses.asdict(python_object).items()
            if not isinstance(value, type)
        }
        trump_like = _inline_trump_args(trump_like)
        if isinstance(python_object, Power):
            trump_like["is_power"] = True
            trump_like["passive"] = python_object.passive

        return trump_like

    # Normally, this is unreachable
    raise TypeError(str(python_object) + " is not JSON serializable")  # pragma: no cover

def _remove_class_references(data):
    if not isinstance(data, dict):
        return data

    return {
        key: _remove_class_references(value)
        for key, value in data.items()
        if not isinstance(value, type)
    }

def _inline_trump_args(data):
    if not isinstance(data, dict):
        return data

    if "trump_args" in data:
        data = {
            **data,
            **data["trump_args"],
        }
        del data["trump_args"]

    return {key: _inline_trump_args(value) for key, value in data.items()}
<|endoftext|>


<commit_before>"""
stringjumble.py
Author: Nathalie
Credit: <sources>

Assignment:

The purpose of this challenge is to gain proficiency with
manipulating lists.

Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:

* With all letters in reverse.
* With words in reverse order, but letters within each word in
  the correct order.
* With all words in correct order, but letters reversed within
  the words.

Output of your program should look like this:

Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy
You entered "There are a few techniques or tricks that you may find handy". Now jumble it:
ydnah dnif yam uoy taht skcirt ro seuqinhcet wef a era erehT
handy find may you that tricks or techniques few a are There
erehT era a wef seuqinhcet ro skcirt taht uoy yam dnif ydnah
"""
string= list(input(["(Please enter a string of text): "]))
print (string)
def shuffle(string):
    if len(string) == 1:
        return string
    else:
        half = int(len(string) / 2)
        # First half in reverse
        first = string[:half][::-1]
        # Last half in reverse
        last =string[half:len(string)][::-1]

        # First + Last in reverse
        return str(first+last)[::-1]
<commit_msg>Updated from Brython Server: 4/14/2017 2:52:22 PM<commit_after>"""
stringjumble.py
Author: Nathalie
Credit: <sources>

Assignment:

The purpose of this challenge is to gain proficiency with
manipulating lists.

Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:

* With all letters in reverse.
* With words in reverse order, but letters within each word in
  the correct order.
* With all words in correct order, but letters reversed within
  the words.

Output of your program should look like this:

Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy
You entered "There are a few techniques or tricks that you may find handy". Now jumble it:
ydnah dnif yam uoy taht skcirt ro seuqinhcet wef a era erehT
handy find may you that tricks or techniques few a are There
erehT era a wef seuqinhcet ro skcirt taht uoy yam dnif ydnah
"""
string= list(input(["(Please enter a string of text): "]))
print (string)
string = x
def shuffle(string):
    if len(string) == 1:
        return string
    else:
        half = int(len(string) / 2)
        # First half in reverse
        first = string[:half][::-1]
        # Last half in reverse
        last =string[half:len(string)][::-1]

        # First + Last in reverse
        return str(first+last)[::-1]
<|endoftext|>


<commit_before>"""
stringjumble.py
Author: <your name>
Credit: <sources>

Assignment:

The purpose of this challenge is to gain proficiency with
manipulating lists.

Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:

* With all letters in reverse.
* With words in reverse order, but letters within each word in
  the correct order.
* With all words in correct order, but letters reversed within
  the words.

Output of your program should look like this:

Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy
You entered "There are a few techniques or tricks that you may find handy". Now jumble it:
ydnah dnif yam uoy taht skcirt ro seuqinhcet wef a era erehT
handy find may you that tricks or techniques few a are There
erehT era a wef seuqinhcet ro skcirt taht uoy yam dnif ydnah
"""
word=input("Please enter a string of text (the bigger the better): ")
print("You entered "+"'"+word+"'"+" Now jumble it: ")<commit_msg>Updated from Brython Server: 10/4/2016 1:53:26 PM<commit_after>"""
stringjumble.py
Author: <your name>
Credit: <sources>

Assignment:

The purpose of this challenge is to gain proficiency with
manipulating lists.

Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:

* With all letters in reverse.
* With words in reverse order, but letters within each word in
  the correct order.
* With all words in correct order, but letters reversed within
  the words.

Output of your program should look like this:

Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy
You entered "There are a few techniques or tricks that you may find handy". Now jumble it:
ydnah dnif yam uoy taht skcirt ro seuqinhcet wef a era erehT
handy find may you that tricks or techniques few a are There
erehT era a wef seuqinhcet ro skcirt taht uoy yam dnif ydnah
"""
#word=input("Please enter a string of text (the bigger the better): ")
word="There are a few techniques or tricks that you may find handy"
print("You entered "+"'"+word+"'"+" Now jumble it: ")
word=word[::-1]
print(word)<|endoftext|>


<commit_before>"""
stringjumble.py
Author: Mary Feyrer
Credit: Tess Snyder, Daniel Wilson

Assignment:

The purpose of this challenge is to gain proficiency with
manipulating lists.

Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:

* With all letters in reverse.
* With words in reverse order, but letters within each word in
  the correct order.
* With all words in correct order, but letters reversed within
  the words.

Output of your program should look like this:

Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy
You entered "There are a few techniques or tricks that you may find handy". Now jumble it:
ydnah dnif yam uoy taht skcirt ro seuqinhcet wef a era erehT
handy find may you that tricks or techniques few a are There
erehT era a wef seuqinhcet ro skcirt taht uoy yam dnif ydnah
"""

text = input("Please enter a string of text (the bigger the better): ")
n = len(text)
list=list(text)

for x in range(-1,-n-1, -1):
    print(text[x], end="")

words=text.split(' ')
print(words)

<commit_msg>Updated from Brython Server: 2/22/2016 2:16:43 PM<commit_after>"""
stringjumble.py
Author: Mary Feyrer
Credit: Tess Snyder, Daniel Wilson

Assignment:

The purpose of this challenge is to gain proficiency with
manipulating lists.

Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:

* With all letters in reverse.
* With words in reverse order, but letters within each word in
  the correct order.
* With all words in correct order, but letters reversed within
  the words.

Output of your program should look like this:

Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy
You entered "There are a few techniques or tricks that you may find handy". Now jumble it:
ydnah dnif yam uoy taht skcirt ro seuqinhcet wef a era erehT
handy find may you that tricks or techniques few a are There
erehT era a wef seuqinhcet ro skcirt taht uoy yam dnif ydnah
"""

text = input("Please enter a string of text (the bigger the better): ")
n = len(text)
list=list(text)

for x in range(-1,-n-1, -1):
    print(text[x], end="")

words=text.split(' ')
list2=list(reversed(words))
for x in list2:
    print(x, end=" ")

for x in

<|endoftext|>


<commit_before>"""
stringjumble.py
Author: Mary Feyrer
Credit: Tess Snyder, Daniel Wilson

Assignment:

The purpose of this challenge is to gain proficiency with
manipulating lists.

Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:

* With all letters in reverse.
* With words in reverse order, but letters within each word in
  the correct order.
* With all words in correct order, but letters reversed within
  the words.

Output of your program should look like this:

Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy
You entered "There are a few techniques or tricks that you may find handy". Now jumble it:
ydnah dnif yam uoy taht skcirt ro seuqinhcet wef a era erehT
handy find may you that tricks or techniques few a are There
erehT era a wef seuqinhcet ro skcirt taht uoy yam dnif ydnah
"""

text = input("Please enter a string of text (the bigger the better): ")
n = len(text)

print("\n")

for x in range(-1,-n-1, -1):
    print(text[x], end="")

words=text.split(' ')
list2=reversed(words)
for x in list2:
    print(x, end=" ")

<commit_msg>Updated from Brython Server: 2/22/2016 2:20:21 PM<commit_after>"""
stringjumble.py
Author: Mary Feyrer
Credit: Tess Snyder, Daniel Wilson

Assignment:

The purpose of this challenge is to gain proficiency with
manipulating lists.

Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:

* With all letters in reverse.
* With words in reverse order, but letters within each word in
  the correct order.
* With all words in correct order, but letters reversed within
  the words.

Output of your program should look like this:

Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy
You entered "There are a few techniques or tricks that you may find handy". Now jumble it:
ydnah dnif yam uoy taht skcirt ro seuqinhcet wef a era erehT
handy find may you that tricks or techniques few a are There
erehT era a wef seuqinhcet ro skcirt taht uoy yam dnif ydnah
"""

text = input("Please enter a string of text (the bigger the better): ")
n = len(text)

print("\n")

for x in range(-1,-n-1, -1):
    print(text[x], end="")

print("\n")

words=text.split(' ')
list2=reversed(words)
for x in list2:
    print(x, end=" ")

<|endoftext|>


<commit_before>"""
stringjumble.py
Author: Avery Wallis
Credit: Ethan, Daniel

Assignment:

The purpose of this challenge is to gain proficiency with
manipulating lists.

Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:

* With all letters in reverse.
* With words in reverse order, but letters within each word in
  the correct order.
* With all words in correct order, but letters reversed within
  the words.

Output of your program should look like this:

Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy
You entered "There are a few techniques or tricks that you may find handy". Now jumble it:
ydnah dnif yam uoy taht skcirt ro seuqinhcet wef a era erehT
handy find may you that tricks or techniques few a are There
erehT era a wef seuqinhcet ro skcirt taht uoy yam dnif ydnah
"""
string= str(input("Please enter a string of text (the bigger the better): "))
l=(int(len(string)))
print('You entered "'+ string + '". Now jumble it:')
the=list(string)
spil = the.split(' ')

for x in range(1,l+1):
    print(string[-x],end="")
print()

f=list(reverse(spil))
for word in f:
    print(word,end="")
print()

for x in range(l,1,-1):
    if string[-x]==" ":
        for y in range(l,x,-1):
            a=str(y)

        print(str(y))
"""
for x in range(l,1,-1):
    if string[-x]==" ":
        for y in range(l,x-1,1):
            print(string[-y+(l-x)],end="")
"""
<commit_msg>Updated from Brython Server: 2/12/2016 2:38:25 PM<commit_after>"""
stringjumble.py
Author: Avery Wallis
Credit: Ethan, Daniel

Assignment:

The purpose of this challenge is to gain proficiency with
manipulating lists.

Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:

* With all letters in reverse.
* With words in reverse order, but letters within each word in
  the correct order.
* With all words in correct order, but letters reversed within
  the words.

Output of your program should look like this:

Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy
You entered "There are a few techniques or tricks that you may find handy". Now jumble it:
ydnah dnif yam uoy taht skcirt ro seuqinhcet wef a era erehT
handy find may you that tricks or techniques few a are There
erehT era a wef seuqinhcet ro skcirt taht uoy yam dnif ydnah
"""
string= str(input("Please enter a string of text (the bigger the better): "))
l=(int(len(string)))
print('You entered "'+ string + '". Now jumble it:')
the=list(string)
spil = string.split(' ')

for x in range(1,l+1):
    print(string[-x],end="")
print()

f=list(reverse(spil))
for word in f:
    print(word,end="")
print()

for x in range(l,1,-1):
    if string[-x]==" ":
        for y in range(l,x,-1):
            a=str(y)

        print(str(y))
"""
for x in range(l,1,-1):
    if string[-x]==" ":
        for y in range(l,x-1,1):
            print(string[-y+(l-x)],end="")
"""
<|endoftext|>


<commit_before>"""
stringjumble.py
Author: Daniel Wilson
Credit:

Assignment:

The purpose of this challenge is to gain proficiency with
manipulating lists.

Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:

* With all letters in reverse.
* With words in reverse order, but letters within each word in
  the correct order.
* With all words in correct order, but letters reversed within
  the words.

Output of your program should look like this:

Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy
You entered "There are a few techniques or tricks that you may find handy". Now jumble it:
ydnah dnif yam uoy taht skcirt ro seuqinhcet wef a era erehT
handy find may you that tricks or techniques few a are There
erehT era a wef seuqinhcet ro skcirt taht uoy yam dnif ydnah
"""
string = str(input("Please enter a string of text (the bigger the better): "))
b = (int(len(string)))
print("You entered '" + string + "'. Now jumble it:")
l = list(string)
sost = string.split(' ')

for y in range(1, b+1) :
    print(string[-y],end="")
print()

word = list(reversed(sost))
for word in l :
    print(word[::-1], end="")
print("")

for words in sost:
    g=0
    while g < len(words) :
        r = "".join(str(words[len(words)-g-1]).split())
        print("{0}".format(r), end="")
        g=g+1
print("", end=" ")
<commit_msg>Updated from Brython Server: 2/11/2016 2:06:33 PM<commit_after>"""
stringjumble.py
Author: Daniel Wilson
Credit:

Assignment:

The purpose of this challenge is to gain proficiency with
manipulating lists.

Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:

* With all letters in reverse.
* With words in reverse order, but letters within each word in
  the correct order.
* With all words in correct order, but letters reversed within
  the words.

Output of your program should look like this:

Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy
You entered "There are a few techniques or tricks that you may find handy". Now jumble it:
ydnah dnif yam uoy taht skcirt ro seuqinhcet wef a era erehT
handy find may you that tricks or techniques few a are There
erehT era a wef seuqinhcet ro skcirt taht uoy yam dnif ydnah
"""
string = str(input("Please enter a string of text (the bigger the better): "))
b = (int(len(string)))
print("You entered '" + string + "'. Now jumble it:")
l = list(string)
sost = string.split(' ')

for y in range(1, b+1) :
    print(string[-y],end="")
print()

word = list(reversed(sost))
for word in l :
    print(word[::-1], end="")
print("")

for words in sost:
    g=0
    while g < len(words) :
        r = "".join(str(words[len(words)-g-1]).split())
        print("{0}".format(r), end="")
        g=g+1
print(" ", end=" ")
<|endoftext|>


<commit_before>import pytest
from aiohttp.test_utils import make_mocked_coro

import virtool.db.references

async def test_get_release(mocker, spawn_client, id_exists, resp_is):
    client = await spawn_client(authorize=True)

    m_fetch_and_update_release = mocker.patch(
        "virtool.db.references.fetch_and_update_release",
        make_mocked_coro({
            "_id": "release"
        })
    )

    resp = await client.get("/api/refs/foo/release")

    id_exists.assert_called_with(
        client.db.references,
        "foo"
    )

    if not id_exists:
        assert await resp_is.not_found(resp)
        return

    assert resp.status == 200

    assert await resp.json() == {
        "_id": "release"
    }

    m_fetch_and_update_release.assert_called_with(
        client.app,
        "foo"
    )

@pytest.mark.parametrize("empty", [True, False])
async def test_list_updates(empty, mocker, spawn_client, id_exists, resp_is):
    client = await spawn_client(authorize=True)

    m_get_one_field = mocker.patch(
        "virtool.db.utils.get_one_field",
        make_mocked_coro(None if empty else [
            "a",
            "b",
            "c"
        ])
    )

    resp = await client.get("/api/refs/foo/updates")

    id_exists.assert_called_with(
        client.db.references,
        "foo"
    )

    if not id_exists:
        assert await resp_is.not_found(resp)
        return

    assert resp.status == 200
    assert await resp.json() == [] if None else [
        "c",
        "b",
        "a"
    ]

    m_get_one_field.assert_called_with(
        client.db.references,
        "updates",
        "foo"
    )

@pytest.mark.parametrize("error", [None, "400"])
async def test_update(error, mocker, spawn_client, check_ref_right, id_exists, resp_is):
    client = await spawn_client(authorize=True)

    if error != "400":
        await client.db.references.insert_one({
            "_id": "foo",
            "release": {
                "id": "bar"
            }
        })

    m_finish_update = mocker.patch("virtool.db.references.finish_update", make_mocked_coro())

    m_register = mocker.patch(
        "virtool.db.processes.register",
        make_mocked_coro({
            "id": "process"
        })
    )

    m_update = mocker.patch(
        "virtool.db.references.update",
        make_mocked_coro((
            {
                "id": "bar"
            },
            {
                "id": "update",
                "created_at": "time"
            }
        ))
    )

    resp = await client.post("/api/refs/foo/updates")

    id_exists.assert_called_with(
        client.db.references,
        "foo"
    )

    if not id_exists:
        assert await resp_is.not_found(resp)
        return

    if not check_ref_right:
        assert await resp_is.insufficient_rights(resp)
        return

    if error == "400":
        assert await resp_is.bad_request(resp, "Target release does not exist")
        return

    m_register.assert_called_with(
        client.db,
        "update_remote_reference"
    )

    m_update.assert_called_with(
        client.app,
        "process",
        "foo",
        {
            "id": "bar"
        },
        "test"
    )

    m_finish_update.assert_called_with(
        client.app,
        "foo",
        "time",
        "process",
        {
            "id": "bar"
        },
        "test"
    )

    assert resp.status == 201

    assert await resp.json() == {
        "id": "update",
        "created_at": "time"
    }

async def test_find_indexes(mocker, spawn_client, id_exists, md_proxy, resp_is):
    client = await spawn_client(authorize=True)

    body = {
        "documents": ["a", "b", "c"]
    }

    m_find = mocker.patch("virtool.db.indexes.find", make_mocked_coro(body))

    resp = await client.get("/api/refs/foo/indexes")

    if not id_exists:
        assert await resp_is.not_found(resp)
        return

    assert resp.status == 200

    assert await resp.json() == body

    m_find.assert_called_with(
        client.db,
        md_proxy(),
        ref_id="foo"
    )

async def test_create(mocker, spawn_client, test_random_alphanumeric, static_time):
    client = await spawn_client(authorize=True, permissions=["create_ref"])

    default_source_type = [
        "strain",
        "isolate"
    ]

    client.app["settings"] = {
        "default_source_types": default_source_type
    }

    data = {
        "name": "Test Viruses",
        "description": "A bunch of viruses used for testing",
        "data_type": "genome",
        "organism": "virus"
    }

    m_get_otu_count = mocker.patch("virtool.db.references.get_otu_count", make_mocked_coro(22))
    m_get_unbuilt_count = mocker.patch("virtool.db.references.get_unbuilt_count", make_mocked_coro(5))

    resp = await client.post("/api/refs", data)

    assert resp.status == 201

    assert resp.headers["Location"] == "/api/refs/" + test_random_alphanumeric.history[0]

    assert await resp.json() == dict(
        data,
        id=test_random_alphanumeric.history[0],
        created_at="2015-10-06T20:00:00Z",
        user={
            "id": "test"
        },
        users=[{
            "build": True,
            "id": "test",
            "modify": True,
            "modify_otu": True,
            "remove": True
        }],
        groups=[],
        contributors=[],
        internal_control=None,
        restrict_source_types=False,
        otu_count=22,
        unbuilt_change_count=5,
        source_types=default_source_type,
        latest_build=None
    )

    m_get_otu_count.assert_called_with(
        client.db,
        test_random_alphanumeric.history[0]
    )

    m_get_unbuilt_count.assert_called_with(
        client.db,
        test_random_alphanumeric.history[0]
    )

@pytest.mark.parametrize("control_exists", [True, False])
@pytest.mark.parametrize("control_id", [None, "", "baz"])
async def test_edit(control_exists, control_id, mocker, spawn_client, check_ref_right, id_exists, resp_is):
    client = await spawn_client(authorize=True)

    m_find_one_and_update = mocker.patch.object(
        client.db.references,
        "find_one_and_update",
        make_mocked_coro({
            "_id": "foo",
            "name": "Test Reference"
        })
    )

    m_get_computed = mocker.patch(
        "virtool.db.references.get_computed",
        make_mocked_coro({
            "computed": True
        })
    )

    m_get_internal_control = mocker.patch(
        "virtool.db.references.get_internal_control",
        make_mocked_coro({"id": "baz"} if control_exists else None)
    )

    data = {
        "name": "Tester",
        "description": "This is a test reference."
    }

    if control_id is not None:
        data["internal_control"] = control_id

    resp = await client.patch("/api/refs/foo", data)

    id_exists.assert_called_with(
        client.db.references,
        "foo"
    )

    if not id_exists:
        assert await resp_is.not_found(resp)
        return

    check_ref_right.assert_called_with(
        mocker.ANY,
        "foo",
        "modify"
    )

    assert check_ref_right.called_with_req()

    if not check_ref_right:
        assert await resp_is.insufficient_rights(resp)
        return

    expected_internal_control = None

    if control_id and control_exists:
        expected_internal_control = {
            "id": "baz"
        }

    update = {
        "description": "This is a test reference.",
        "name": "Tester"
    }

    if control_id is not None:
        update["internal_control"] = expected_internal_control

    m_find_one_and_update.assert_called_with(
        {
            "_id": "foo"
        },
        {
            "$set": update
        },
        projection=virtool.db.references.PROJECTION
    )

    m_get_computed.assert_called_with(
        client.db,
        "foo",
        control_id
    )

    if control_id:
        m_get_internal_control.assert_called_with(
            client.db,
            "baz",
            "foo"
        )

@pytest.mark.parametrize("error", [None, "400_dne", "400_exists", "404"])
@pytest.mark.parametrize("field", ["group", "user"])
async def test_add_group_or_user(error, field, spawn_client, check_ref_right, resp_is, static_time):
    """
    Test that the group or user is added to the reference when no error condition exists.

    Test for the following error conditions:
    - 404: ref does not exist
    - 400_exists: group or user already exists in ref
    - 400_dne: group or user does not exist

    """
    client = await spawn_client(authorize=True)

    document = {
        "_id": "foo",
        "groups": [],
        "users": []
    }

    # Add group and user subdocuments to make sure a 400 is returned complaining about the user or group already
    # existing in the ref.
    if error == "400_exists":
        document["groups"].append({
            "id": "tech"
        })

        document["users"].append({
            "id": "fred"
        })

    # Add group and user document to their collections unless we want to trigger a 400 complaining about the user or
    # group already not existing.
    if error != "400_dne":
        await client.db.groups.insert_one({
            "_id": "tech"
        })

        await client.db.users.insert_one({
            "_id": "fred",
            "identicon": "foo_identicon"
        })

    # Don't insert the ref document if we want to trigger a 404.
    if error != "404":
        await client.db.references.insert_one(document)

    url = "/api/refs/foo/{}s".format(field)

    resp = await client.post(url, {
        field + "_id": "tech" if field == "group" else "fred",
        "modify": True
    })

    if error == "404":
        assert await resp_is.not_found(resp)
        return

    if not check_ref_right:
        assert await resp_is.insufficient_rights(resp)
        return

    if error == "400_dne":
        assert await resp_is.bad_request(resp, "{} does not exist".format(field.capitalize()))
        return

    if error == "400_exists":
        assert await resp_is.bad_request(resp, "{} already exists".format(field.capitalize()))
        return

    assert resp.status == 201

    expected = {
        "id": "tech" if field == "group" else "fred",
        "created_at": static_time.iso,
        "build": False,
        "modify": True,
        "modify_otu": False,
        "remove": False
    }

    if field == "user":
        expected["identicon"] = "foo_identicon"

    assert await resp.json() == expected

@pytest.mark.parametrize("error", [None, "404_field", "404_ref"])
@pytest.mark.parametrize("field", ["group", "user"])
async def test_edit_group_or_user(error, field, spawn_client, check_ref_right, resp_is):
    client = await spawn_client(authorize=True)

    document = {
        "_id": "foo",
        "groups": [],
        "users": []
    }

    if error != "404_field":
        document["groups"].append({
            "id": "tech",
            "build": False,
            "modify": False,
            "modify_otu": False,
            "remove": False
        })

        document["users"].append({
            "id": "fred",
            "build": False,
            "modify": False,
            "modify_otu": False,
            "remove": False
        })

    if error != "404_ref":
        await client.db.references.insert_one(document)

    await client.db.users.insert_one({
        "_id": "fred",
        "identicon": "foo_identicon"
    })

    subdocument_id = "tech" if field == "group" else "fred"

    url = "/api/refs/foo/{}s/{}".format(field, subdocument_id)

    resp = await client.patch(url, {
        "remove": True
    })

    if error:
        assert await resp_is.not_found(resp)
        return

    if not check_ref_right:
        assert await resp_is.insufficient_rights(resp)
        return

    assert resp.status == 200

    expected = {
        "id": subdocument_id,
        "build": False,
        "modify": False,
        "modify_otu": False,
        "remove": True
    }

    if field == "user":
        expected["identicon"] = "foo_identicon"

    assert await resp.json() == expected

    assert await client.db.references.find_one() == {
        "_id": "foo",
        "groups": [{
            "id": "tech",
            "build": False,
            "modify": False,
            "modify_otu": False,
            "remove": field == "group"
        }],
        "users": [{
            "id": "fred",
            "build": False,
            "modify": False,
            "modify_otu": False,
            "remove": field == "user"
        }]
    }

@pytest.mark.parametrize("error", [None, "404_field", "404_ref"])
@pytest.mark.parametrize("field", ["group", "user"])
async def test_delete_group_or_user(error, field, spawn_client, check_ref_right, resp_is):
    client = await spawn_client(authorize=True)

    document = {
        "_id": "foo",
        "groups": [],
        "users": []
    }

    if error != "404_field":
        document["groups"].append({
            "id": "tech",
            "build": False,
            "modify": False,
            "modify_otu": False,
            "remove": False
        })

        document["users"].append({
            "id": "fred",
            "build": False,
            "modify": False,
            "modify_otu": False,
            "remove": False
        })

    if error != "404_ref":
        await client.db.references.insert_one(document)

    subdocument_id = "tech" if field == "group" else "fred"

    url = "/api/refs/foo/{}s/{}".format(field, subdocument_id)

    resp = await client.delete(url)

    if error:
        assert await resp_is.not_found(resp)
        return

    if not check_ref_right:
        assert await resp_is.insufficient_rights(resp)
        return

    assert resp.status == 204

    if field == "group":
        expected = {
            **document,
            "groups": []
        }
    else:
        expected = {
            **document,
            "users": []
        }

    assert await client.db.references.find_one() == expected
<commit_msg>Fix failing tests<commit_after>import pytest
from aiohttp.test_utils import make_mocked_coro

import virtool.db.references

async def test_get_release(mocker, spawn_client, id_exists, resp_is):
    client = await spawn_client(authorize=True)

    m_fetch_and_update_release = mocker.patch(
        "virtool.db.references.fetch_and_update_release",
        make_mocked_coro({
            "_id": "release"
        })
    )

    resp = await client.get("/api/refs/foo/release")

    id_exists.assert_called_with(
        client.db.references,
        "foo"
    )

    if not id_exists:
        assert await resp_is.not_found(resp)
        return

    assert resp.status == 200

    assert await resp.json() == {
        "_id": "release"
    }

    m_fetch_and_update_release.assert_called_with(
        client.app,
        "foo"
    )

@pytest.mark.parametrize("empty", [True, False])
async def test_list_updates(empty, mocker, spawn_client, id_exists, resp_is):
    client = await spawn_client(authorize=True)

    m_get_one_field = mocker.patch(
        "virtool.db.utils.get_one_field",
        make_mocked_coro(None if empty else [
            "a",
            "b",
            "c"
        ])
    )

    resp = await client.get("/api/refs/foo/updates")

    id_exists.assert_called_with(
        client.db.references,
        "foo"
    )

    if not id_exists:
        assert await resp_is.not_found(resp)
        return

    assert resp.status == 200
    assert await resp.json() == [] if None else [
        "c",
        "b",
        "a"
    ]

    m_get_one_field.assert_called_with(
        client.db.references,
        "updates",
        "foo"
    )

@pytest.mark.parametrize("error", [None, "400"])
async def test_update(error, mocker, spawn_client, check_ref_right, id_exists, resp_is):
    client = await spawn_client(authorize=True)

    if error != "400":
        await client.db.references.insert_one({
            "_id": "foo",
            "release": {
                "id": "bar"
            }
        })

    m_finish_update = mocker.patch("virtool.db.references.finish_update", make_mocked_coro())

    m_register = mocker.patch(
        "virtool.db.processes.register",
        make_mocked_coro({
            "id": "process"
        })
    )

    m_update = mocker.patch(
        "virtool.db.references.update",
        make_mocked_coro((
            {
                "id": "bar"
            },
            {
                "id": "update",
                "created_at": "time"
            }
        ))
    )

    resp = await client.post("/api/refs/foo/updates")

    id_exists.assert_called_with(
        client.db.references,
        "foo"
    )

    if not id_exists:
        assert await resp_is.not_found(resp)
        return

    if not check_ref_right:
        assert await resp_is.insufficient_rights(resp)
        return

    if error == "400":
        assert await resp_is.bad_request(resp, "Target release does not exist")
        return

    m_register.assert_called_with(
        client.db,
        "update_remote_reference"
    )

    m_update.assert_called_with(
        client.app,
        "process",
        "foo",
        {
            "id": "bar"
        },
        "test"
    )

    m_finish_update.assert_called_with(
        client.app,
        "foo",
        "time",
        "process",
        {
            "id": "bar"
        },
        "test"
    )

    assert resp.status == 201

    assert await resp.json() == {
        "id": "update",
        "created_at": "time"
    }

async def test_find_indexes(mocker, spawn_client, id_exists, md_proxy, resp_is):
    client = await spawn_client(authorize=True)

    body = {
        "documents": ["a", "b", "c"]
    }

    m_find = mocker.patch("virtool.db.indexes.find", make_mocked_coro(body))

    resp = await client.get("/api/refs/foo/indexes")

    if not id_exists:
        assert await resp_is.not_found(resp)
        return

    assert resp.status == 200

    assert await resp.json() == body

    m_find.assert_called_with(
        client.db,
        md_proxy(),
        ref_id="foo"
    )

async def test_create(mocker, spawn_client, test_random_alphanumeric, static_time):
    client = await spawn_client(authorize=True, permissions=["create_ref"])

    default_source_type = [
        "strain",
        "isolate"
    ]

    client.app["settings"] = {
        "default_source_types": default_source_type
    }

    data = {
        "name": "Test Viruses",
        "description": "A bunch of viruses used for testing",
        "data_type": "genome",
        "organism": "virus"
    }

    m_get_otu_count = mocker.patch("virtool.db.references.get_otu_count", make_mocked_coro(22))
    m_get_unbuilt_count = mocker.patch("virtool.db.references.get_unbuilt_count", make_mocked_coro(5))

    resp = await client.post("/api/refs", data)

    assert resp.status == 201

    assert resp.headers["Location"] == "/api/refs/" + test_random_alphanumeric.history[0]

    assert await resp.json() == dict(
        data,
        id=test_random_alphanumeric.history[0],
        created_at="2015-10-06T20:00:00Z",
        user={
            "id": "test"
        },
        users=[{
            "build": True,
            "id": "test",
            "modify": True,
            "modify_otu": True,
            "remove": True
        }],
        groups=[],
        contributors=[],
        internal_control=None,
        restrict_source_types=False,
        otu_count=22,
        unbuilt_change_count=5,
        source_types=default_source_type,
        latest_build=None
    )

    m_get_otu_count.assert_called_with(
        client.db,
        test_random_alphanumeric.history[0]
    )

    m_get_unbuilt_count.assert_called_with(
        client.db,
        test_random_alphanumeric.history[0]
    )

@pytest.mark.parametrize("control_exists", [True, False])
@pytest.mark.parametrize("control_id", [None, "", "baz"])
async def test_edit(control_exists, control_id, mocker, spawn_client, check_ref_right, id_exists, resp_is):
    client = await spawn_client(authorize=True)

    m_find_one_and_update = mocker.patch.object(
        client.db.references,
        "find_one_and_update",
        make_mocked_coro({
            "_id": "foo",
            "name": "Test Reference"
        })
    )

    m_get_computed = mocker.patch(
        "virtool.db.references.get_computed",
        make_mocked_coro({
            "computed": True
        })
    )

    m_get_internal_control = mocker.patch(
        "virtool.db.references.get_internal_control",
        make_mocked_coro({"id": "baz"} if control_exists else None)
    )

    data = {
        "name": "Tester",
        "description": "This is a test reference."
    }

    if control_id is not None:
        data["internal_control"] = control_id

    resp = await client.patch("/api/refs/foo", data)

    id_exists.assert_called_with(
        client.db.references,
        "foo"
    )

    if not id_exists:
        assert await resp_is.not_found(resp)
        return

    check_ref_right.assert_called_with(
        mocker.ANY,
        "foo",
        "modify"
    )

    assert check_ref_right.called_with_req()

    if not check_ref_right:
        assert await resp_is.insufficient_rights(resp)
        return

    expected_internal_control = None

    if control_id and control_exists:
        expected_internal_control = {
            "id": "baz"
        }

    update = {
        "description": "This is a test reference.",
        "name": "Tester"
    }

    if control_id is not None:
        update["internal_control"] = expected_internal_control

    m_find_one_and_update.assert_called_with(
        {
            "_id": "foo"
        },
        {
            "$set": update
        }
    )

    m_get_computed.assert_called_with(
        client.db,
        "foo",
        control_id
    )

    if control_id:
        m_get_internal_control.assert_called_with(
            client.db,
            "baz",
            "foo"
        )

@pytest.mark.parametrize("error", [None, "400_dne", "400_exists", "404"])
@pytest.mark.parametrize("field", ["group", "user"])
async def test_add_group_or_user(error, field, spawn_client, check_ref_right, resp_is, static_time):
    """
    Test that the group or user is added to the reference when no error condition exists.

    Test for the following error conditions:
    - 404: ref does not exist
    - 400_exists: group or user already exists in ref
    - 400_dne: group or user does not exist

    """
    client = await spawn_client(authorize=True)

    document = {
        "_id": "foo",
        "groups": [],
        "users": []
    }

    # Add group and user subdocuments to make sure a 400 is returned complaining about the user or group already
    # existing in the ref.
    if error == "400_exists":
        document["groups"].append({
            "id": "tech"
        })

        document["users"].append({
            "id": "fred"
        })

    # Add group and user document to their collections unless we want to trigger a 400 complaining about the user or
    # group already not existing.
    if error != "400_dne":
        await client.db.groups.insert_one({
            "_id": "tech"
        })

        await client.db.users.insert_one({
            "_id": "fred",
            "identicon": "foo_identicon"
        })

    # Don't insert the ref document if we want to trigger a 404.
    if error != "404":
        await client.db.references.insert_one(document)

    url = "/api/refs/foo/{}s".format(field)

    resp = await client.post(url, {
        field + "_id": "tech" if field == "group" else "fred",
        "modify": True
    })

    if error == "404":
        assert await resp_is.not_found(resp)
        return

    if not check_ref_right:
        assert await resp_is.insufficient_rights(resp)
        return

    if error == "400_dne":
        assert await resp_is.bad_request(resp, "{} does not exist".format(field.capitalize()))
        return

    if error == "400_exists":
        assert await resp_is.bad_request(resp, "{} already exists".format(field.capitalize()))
        return

    assert resp.status == 201

    expected = {
        "id": "tech" if field == "group" else "fred",
        "created_at": static_time.iso,
        "build": False,
        "modify": True,
        "modify_otu": False,
        "remove": False
    }

    if field == "user":
        expected["identicon"] = "foo_identicon"

    assert await resp.json() == expected

@pytest.mark.parametrize("error", [None, "404_field", "404_ref"])
@pytest.mark.parametrize("field", ["group", "user"])
async def test_edit_group_or_user(error, field, spawn_client, check_ref_right, resp_is):
    client = await spawn_client(authorize=True)

    document = {
        "_id": "foo",
        "groups": [],
        "users": []
    }

    if error != "404_field":
        document["groups"].append({
            "id": "tech",
            "build": False,
            "modify": False,
            "modify_otu": False,
            "remove": False
        })

        document["users"].append({
            "id": "fred",
            "build": False,
            "modify": False,
            "modify_otu": False,
            "remove": False
        })

    if error != "404_ref":
        await client.db.references.insert_one(document)

    await client.db.users.insert_one({
        "_id": "fred",
        "identicon": "foo_identicon"
    })

    subdocument_id = "tech" if field == "group" else "fred"

    url = "/api/refs/foo/{}s/{}".format(field, subdocument_id)

    resp = await client.patch(url, {
        "remove": True
    })

    if error:
        assert await resp_is.not_found(resp)
        return

    if not check_ref_right:
        assert await resp_is.insufficient_rights(resp)
        return

    assert resp.status == 200

    expected = {
        "id": subdocument_id,
        "build": False,
        "modify": False,
        "modify_otu": False,
        "remove": True
    }

    if field == "user":
        expected["identicon"] = "foo_identicon"

    assert await resp.json() == expected

    assert await client.db.references.find_one() == {
        "_id": "foo",
        "groups": [{
            "id": "tech",
            "build": False,
            "modify": False,
            "modify_otu": False,
            "remove": field == "group"
        }],
        "users": [{
            "id": "fred",
            "build": False,
            "modify": False,
            "modify_otu": False,
            "remove": field == "user"
        }]
    }

@pytest.mark.parametrize("error", [None, "404_field", "404_ref"])
@pytest.mark.parametrize("field", ["group", "user"])
async def test_delete_group_or_user(error, field, spawn_client, check_ref_right, resp_is):
    client = await spawn_client(authorize=True)

    document = {
        "_id": "foo",
        "groups": [],
        "users": []
    }

    if error != "404_field":
        document["groups"].append({
            "id": "tech",
            "build": False,
            "modify": False,
            "modify_otu": False,
            "remove": False
        })

        document["users"].append({
            "id": "fred",
            "build": False,
            "modify": False,
            "modify_otu": False,
            "remove": False
        })

    if error != "404_ref":
        await client.db.references.insert_one(document)

    subdocument_id = "tech" if field == "group" else "fred"

    url = "/api/refs/foo/{}s/{}".format(field, subdocument_id)

    resp = await client.delete(url)

    if error:
        assert await resp_is.not_found(resp)
        return

    if not check_ref_right:
        assert await resp_is.insufficient_rights(resp)
        return

    assert resp.status == 204

    if field == "group":
        expected = {
            **document,
            "groups": []
        }
    else:
        expected = {
            **document,
            "users": []
        }

    assert await client.db.references.find_one() == expected
<|endoftext|>


<commit_before>from unittest import mock
import requests_mock
import json
import foremast.app.create_app
from foremast.app import SpinnakerApp

@mock.patch('foremast.app.create_app.LINKS', new={"test1": "https://test1.com", "test2": "https://test2.com"})
def test_instance_links():
    """Checks if instance_links is being populated properly"""
    pipeline_config = {
        "instance_links": {
            "test3": "https://test3.com",
            "test4": "https://test4.com",
        }
    }
    spinnaker_app = SpinnakerApp(pipeline_config=pipeline_config)
    instance_links = spinnaker_app.retrieve_instance_links()
    assert instance_links == {"test1": "https://test1.com", "test2": "https://test2.com"}, "Instance Links are not being retrieved properly"

@mock.patch('foremast.app.create_app.API_URL', new='https://spinnaker.build.gogoair.com:7777')
@mock.patch.object(SpinnakerApp, 'retrieve_instance_links', return_value={"test1": "https://test3.com", "test2": "https://test4.com"})
def test_retrieval_of_templates(mock_instance_links):
    """Checks to see if the instance links are populating app_data.json.j2 properly"""
    pipeline_config = {
        "instance_links": {
            "health": ":8080/health",
            "tail_on": ":8133"
        },
        "chaos_monkey": {
            "mean_time": 5,
            "minimum_time": 3,
            "enabled": False,
            "exceptions": []
        }
    }
    app = "UnitTestApp"
    email = "UnitTestApp@gogoair.com"
    project = "UnitTest"
    repo = "UnitTest"
    accounts = [
        {
            "type": "aws",
            "name": "dev",
        }
    ]
    mock_api_url = 'https://spinnaker.build.gogoair.com:7777/credentials'
    spinnaker_app = SpinnakerApp(pipeline_config=pipeline_config, app=app, email=email,
                                 project=project, repo=repo)
    with requests_mock.Mocker() as mock_requests:
        mock_requests.get(mock_api_url, json=accounts)
        accounts = spinnaker_app.get_accounts()
        spinnaker_app.appinfo['accounts'] = accounts
        app_data = json.loads(spinnaker_app.retrieve_template())
    instance_links = app_data['job'][0]['application']['instanceLinks'][0]['links']
    assert_links = {}
    for instance_link in instance_links:
        assert_links[instance_link['title']] = instance_link['path']
    assert assert_links == {**pipeline_config['instance_links'], **mock_instance_links.return_value}
<commit_msg>docs: docstrings on unittests<commit_after>"""Verifies that instance_links are being retrieved properly from LINKS. Verifies that app_data.json.j2
contains the instance link information"""
from unittest import mock
import requests_mock
import json
import foremast.app.create_app
from foremast.app import SpinnakerApp

@mock.patch('foremast.app.create_app.LINKS', new={"test1": "https://test1.com", "test2": "https://test2.com"})
def test_instance_links():
    """Checks if instance_links is being populated properly"""
    pipeline_config = {
        "instance_links": {
            "test3": "https://test3.com",
            "test4": "https://test4.com",
            "test5": "https://test2.com"
        }
    }
    spinnaker_app = SpinnakerApp(pipeline_config=pipeline_config)
    instance_links = spinnaker_app.retrieve_instance_links()
    assert instance_links == {"test1": "https://test1.com"}, "Instance Links are not being retrieved properly"

    pipeline_config = { "instance_links": {} }
    spinnaker_app = SpinnakerApp(pipeline_config=pipeline_config)
    instance_links = spinnaker_app.retrieve_instance_links()
    assert instance_links == {"test1": "https://test1.com", "test2": "https://test2.com"},
                             "Instance Links are not being retrieved properly"

@mock.patch('foremast.app.create_app.API_URL', new='https://spinnaker.build.gogoair.com:7777')
@mock.patch.object(SpinnakerApp, 'retrieve_instance_links', return_value={"test1": "https://test1.com",
                   "test2": "https://test2.com"}, "test3")
def test_retrieval_of_templates(mock_instance_links):
    """Checks to see if the instance links are populating app_data.json.j2 properly.
    This also mocks the return_value of the accounts on Spinnaker"""
    pipeline_config = {
        "instance_links": {
            "health": ":8080/health",
            "tail_on": ":8133"
        },
        "chaos_monkey": {
            "mean_time": 5,
            "minimum_time": 3,
            "enabled": False,
            "exceptions": []
        }
    }

    app = "UnitTestApp"
    email = "UnitTestApp@gogoair.com"
    project = "UnitTest"
    repo = "UnitTest"

    accounts = [{
        "type": "aws",
        "name": "dev",
    }]
    mock_api_url = 'https://spinnaker.build.gogoair.com:7777/credentials'
    spinnaker_app = SpinnakerApp(pipeline_config=pipeline_config, app=app, email=email,
                                 project=project, repo=repo)

    with requests_mock.Mocker() as mock_requests:
        mock_requests.get(mock_api_url, json=accounts)
        accounts = spinnaker_app.get_accounts()
        spinnaker_app.appinfo['accounts'] = accounts
        app_data = json.loads(spinnaker_app.retrieve_template())
    instance_links = app_data['job'][0]['application']['instanceLinks'][0]['links']
    assert_links = {}
    for instance_link in instance_links:
        assert_links[instance_link['title']] = instance_link['path']
    assert assert_links == {**pipeline_config['instance_links'], **mock_instance_links.return_value},
                            "instance_links in app_data.json.j2 is not being populated properly"
<|endoftext|>


<commit_before>#!/usr/bin/env python3

from testUtils import Utils
from testUtils import BlockLogAction
import time
from Cluster import Cluster
from WalletMgr import WalletMgr
from Node import BlockType
import os
import signal
import subprocess
from TestHelper import AppArgs
from TestHelper import TestHelper

###############################################################
# block_log_util_test
#  Test verifies that the blockLogUtil is still compatible with nodeos
###############################################################

Print=Utils.Print
errorExit=Utils.errorExit

from core_symbol import CORE_SYMBOL

appArgs=AppArgs()
args = TestHelper.parse_args({"--dump-error-details","--keep-logs","-v","--leave-running","--clean-run"})
Utils.Debug=args.v
pnodes=2
cluster=Cluster(walletd=True)
dumpErrorDetails=args.dump_error_details
keepLogs=args.keep_logs
dontKill=args.leave_running
prodCount=2
killAll=args.clean_run
p2pPlugin="net"
walletPort=TestHelper.DEFAULT_WALLET_PORT
totalNodes=pnodes

walletMgr=WalletMgr(True, port=walletPort)
testSuccessful=False
killEosInstances=not dontKill
killWallet=not dontKill

WalletdName=Utils.EosWalletName
ClientName="cleos"

try:
    TestHelper.printSystemInfo("BEGIN")
    cluster.setWalletMgr(walletMgr)

    cluster.killall(allInstances=killAll)
    cluster.cleanup()
    Print("Stand up cluster")
    if cluster.launch(prodCount=prodCount, onlyBios=False, pnodes=pnodes, totalNodes=totalNodes, totalProducers=pnodes*prodCount, p2pPlugin=p2pPlugin,
                      useBiosBootFile=False) is False:
        Utils.errorExit("Failed to stand up eos cluster.")

    Print("Validating system accounts after bootstrap")
    cluster.validateAccounts(None)

    biosNode=cluster.biosNode
    node0=cluster.getNode(0)
    node1=cluster.getNode(1)

    blockNum=100
    Print("Wait till we at least get to block %d" % (blockNum))
    node0.waitForBlock(blockNum, blockType=BlockType.lib)
    info=node0.getInfo(exitOnError=True)
    headBlockNum=info["head_block_num"]
    lib=info["last_irreversible_block_num"]

    Print("Kill the node we want to verify its block log")
    node0.kill(signal.SIGTERM)

    Print("Wait for node0's head block to become irreversible")
    node1.waitForBlock(headBlockNum, blockType=BlockType.lib)
    infoAfter=node1.getInfo(exitOnError=True)
    headBlockNumAfter=infoAfter["head_block_num"]

    def checkBlockLog(blockLog, blockNumsToFind, firstBlockNum=1):
        foundBlockNums=[]
        nextBlockNum=firstBlockNum
        previous=0
        nextIndex=0
        for block in blockLog:
            blockNum=block["block_num"]
            if nextBlockNum!=blockNum:
                Utils.errorExit("BlockLog should progress to the next block number, expected block number %d but got %d" % (nextBlockNum, blockNum))
            if nextIndex<len(blockNumsToFind) and blockNum==blockNumsToFind[nextIndex]:
                foundBlockNums.append(True)
                nextIndex+=1
            nextBlockNum+=1
        while nextIndex<len(blockNumsToFind):
            foundBlockNums.append(False)
            if nextIndex<len(blockNumsToFind)-1:
                assert blockNumsToFind[nextIndex+1] > blockNumsToFind[nextIndex], "expects passed in array, blockNumsToFind to increase from smallest to largest, %d is less than or equal to %d" % (next, previous)
            nextIndex+=1

        return foundBlockNums

    Print("Retrieve the whole blocklog for node 0")
    blockLog=cluster.getBlockLog(0)
    foundBlockNums=checkBlockLog(blockLog, [headBlockNum, headBlockNumAfter])
    assert foundBlockNums[0], "Couldn't find \"%d\" in blocklog:\n\"%s\"\n" % (foundBlockNums[0], output)
    assert not foundBlockNums[1], "Should not find \"%d\" in blocklog:\n\"%s\"\n" % (foundBlockNums[1], blockLog)

    output=cluster.getBlockLog(0, blockLogAction=BlockLogAction.smoke_test)
    expectedStr="no problems found"
    assert output.find(expectedStr) != -1, "Couldn't find \"%s\" in:\n\"%s\"\n" % (expectedStr, output)

    duplicateIndexFileName="duplicate.index"
    output=cluster.getBlockLog(0, blockLogAction=BlockLogAction.make_index, outputFile=duplicateIndexFileName)
    assert output is not None, "Couldn't make new index file \"%s\"\n" % (duplicateIndexFileName)

    blockLogDir=Utils.getNodeDataDir(0, "blocks")
    blockIndexFileName=os.path.join(blockLogDir, "blocks.index")
    blockIndexFile=open(blockIndexFileName,"rb")
    duplicateIndexFileName=os.path.join(blockLogDir, duplicateIndexFileName)
    duplicateIndexFile=open(duplicateIndexFileName,"rb")
    blockIndexStr=blockIndexFile.read()
    duplicateIndexStr=duplicateIndexFile.read()
    assert blockIndexStr==duplicateIndexStr, "Generated file \%%s\" didn't match original \"%s\"" % (duplicateIndexFileName, blockIndexFileName)

    try:
        Print("Head block num %d will not be in block log (it will be in reversible DB), so --trim will throw an exception" % (headBlockNum))
        output=cluster.getBlockLog(0, blockLogAction=BlockLogAction.trim, last=headBlockNum, throwException=True)
        Utils.errorExit("BlockLogUtil --trim should have indicated error for last value set to lib (%d) " +
                        "which should not do anything since only trimming blocklog and not irreversible blocks" % (lib))
    except subprocess.CalledProcessError as ex:
        pass

    beforeEndOfBlockLog=lib-20
    Print("Block num %d will definitely be at least one block behind the most recent entry in block log, so --trim will work" % (beforeEndOfBlockLog))
    output=cluster.getBlockLog(0, blockLogAction=BlockLogAction.trim, last=beforeEndOfBlockLog, throwException=True)

    testSuccessful=True

finally:
    TestHelper.shutdown(cluster, walletMgr, testSuccessful=testSuccessful, killEosInstances=killEosInstances, killWallet=killWallet, keepLogs=keepLogs, cleanRun=killAll, dumpErrorDetails=dumpErrorDetails)

exit(0)
<commit_msg>Removed old p2pPlugin launch parameter to allow test to run.<commit_after>#!/usr/bin/env python3

from testUtils import Utils
from testUtils import BlockLogAction
import time
from Cluster import Cluster
from WalletMgr import WalletMgr
from Node import BlockType
import os
import signal
import subprocess
from TestHelper import AppArgs
from TestHelper import TestHelper

###############################################################
# block_log_util_test
#  Test verifies that the blockLogUtil is still compatible with nodeos
###############################################################

Print=Utils.Print
errorExit=Utils.errorExit

from core_symbol import CORE_SYMBOL

appArgs=AppArgs()
args = TestHelper.parse_args({"--dump-error-details","--keep-logs","-v","--leave-running","--clean-run"})
Utils.Debug=args.v
pnodes=2
cluster=Cluster(walletd=True)
dumpErrorDetails=args.dump_error_details
keepLogs=args.keep_logs
dontKill=args.leave_running
prodCount=2
killAll=args.clean_run
walletPort=TestHelper.DEFAULT_WALLET_PORT
totalNodes=pnodes

walletMgr=WalletMgr(True, port=walletPort)
testSuccessful=False
killEosInstances=not dontKill
killWallet=not dontKill

WalletdName=Utils.EosWalletName
ClientName="cleos"

try:
    TestHelper.printSystemInfo("BEGIN")
    cluster.setWalletMgr(walletMgr)

    cluster.killall(allInstances=killAll)
    cluster.cleanup()
    Print("Stand up cluster")
    if cluster.launch(prodCount=prodCount, onlyBios=False, pnodes=pnodes, totalNodes=totalNodes, totalProducers=pnodes*prodCount, useBiosBootFile=False) is False:
        Utils.errorExit("Failed to stand up eos cluster.")

    Print("Validating system accounts after bootstrap")
    cluster.validateAccounts(None)

    biosNode=cluster.biosNode
    node0=cluster.getNode(0)
    node1=cluster.getNode(1)

    blockNum=100
    Print("Wait till we at least get to block %d" % (blockNum))
    node0.waitForBlock(blockNum, blockType=BlockType.lib)
    info=node0.getInfo(exitOnError=True)
    headBlockNum=info["head_block_num"]
    lib=info["last_irreversible_block_num"]

    Print("Kill the node we want to verify its block log")
    node0.kill(signal.SIGTERM)

    Print("Wait for node0's head block to become irreversible")
    node1.waitForBlock(headBlockNum, blockType=BlockType.lib)
    infoAfter=node1.getInfo(exitOnError=True)
    headBlockNumAfter=infoAfter["head_block_num"]

    def checkBlockLog(blockLog, blockNumsToFind, firstBlockNum=1):
        foundBlockNums=[]
        nextBlockNum=firstBlockNum
        previous=0
        nextIndex=0
        for block in blockLog:
            blockNum=block["block_num"]
            if nextBlockNum!=blockNum:
                Utils.errorExit("BlockLog should progress to the next block number, expected block number %d but got %d" % (nextBlockNum, blockNum))
            if nextIndex<len(blockNumsToFind) and blockNum==blockNumsToFind[nextIndex]:
                foundBlockNums.append(True)
                nextIndex+=1
            nextBlockNum+=1
        while nextIndex<len(blockNumsToFind):
            foundBlockNums.append(False)
            if nextIndex<len(blockNumsToFind)-1:
                assert blockNumsToFind[nextIndex+1] > blockNumsToFind[nextIndex], "expects passed in array, blockNumsToFind to increase from smallest to largest, %d is less than or equal to %d" % (next, previous)
            nextIndex+=1

        return foundBlockNums

    Print("Retrieve the whole blocklog for node 0")
    blockLog=cluster.getBlockLog(0)
    foundBlockNums=checkBlockLog(blockLog, [headBlockNum, headBlockNumAfter])
    assert foundBlockNums[0], "Couldn't find \"%d\" in blocklog:\n\"%s\"\n" % (foundBlockNums[0], output)
    assert not foundBlockNums[1], "Should not find \"%d\" in blocklog:\n\"%s\"\n" % (foundBlockNums[1], blockLog)

    output=cluster.getBlockLog(0, blockLogAction=BlockLogAction.smoke_test)
    expectedStr="no problems found"
    assert output.find(expectedStr) != -1, "Couldn't find \"%s\" in:\n\"%s\"\n" % (expectedStr, output)

    duplicateIndexFileName="duplicate.index"
    output=cluster.getBlockLog(0, blockLogAction=BlockLogAction.make_index, outputFile=duplicateIndexFileName)
    assert output is not None, "Couldn't make new index file \"%s\"\n" % (duplicateIndexFileName)

    blockLogDir=Utils.getNodeDataDir(0, "blocks")
    blockIndexFileName=os.path.join(blockLogDir, "blocks.index")
    blockIndexFile=open(blockIndexFileName,"rb")
    duplicateIndexFileName=os.path.join(blockLogDir, duplicateIndexFileName)
    duplicateIndexFile=open(duplicateIndexFileName,"rb")
    blockIndexStr=blockIndexFile.read()
    duplicateIndexStr=duplicateIndexFile.read()
    assert blockIndexStr==duplicateIndexStr, "Generated file \%%s\" didn't match original \"%s\"" % (duplicateIndexFileName, blockIndexFileName)

    try:
        Print("Head block num %d will not be in block log (it will be in reversible DB), so --trim will throw an exception" % (headBlockNum))
        output=cluster.getBlockLog(0, blockLogAction=BlockLogAction.trim, last=headBlockNum, throwException=True)
        Utils.errorExit("BlockLogUtil --trim should have indicated error for last value set to lib (%d) " +
                        "which should not do anything since only trimming blocklog and not irreversible blocks" % (lib))
    except subprocess.CalledProcessError as ex:
        pass

    beforeEndOfBlockLog=lib-20
    Print("Block num %d will definitely be at least one block behind the most recent entry in block log, so --trim will work" % (beforeEndOfBlockLog))
    output=cluster.getBlockLog(0, blockLogAction=BlockLogAction.trim, last=beforeEndOfBlockLog, throwException=True)

    testSuccessful=True

finally:
    TestHelper.shutdown(cluster, walletMgr, testSuccessful=testSuccessful, killEosInstances=killEosInstances, killWallet=killWallet, keepLogs=keepLogs, cleanRun=killAll, dumpErrorDetails=dumpErrorDetails)

exit(0)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function

import uuid

from django.conf import settings
from django.contrib.postgres.fields import JSONField
from django.db import models

from polyaxon_k8s.utils import nodes
from polyaxon_k8s import constants as k8s_constants

from libs.models import DiffModel

class Cluster(DiffModel):
    """A model that represents the cluster api version."""
    uuid = models.UUIDField(
        default=uuid.uuid4,
        editable=False,
        unique=True,
        null=False)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='clusters')
    version_api = JSONField(help_text='The cluster version api infos')

class ClusterNode(models.Model):
    """A model that represents the cluster node."""
    uuid = models.UUIDField(
        default=uuid.uuid4,
        editable=False,
        unique=True,
        null=False)
    name = models.CharField(
        max_length=256,
        blank=True,
        null=True,
        help_text='Name of the node')
    cluster = models.ForeignKey(Cluster, related_name='nodes')
    hostname = models.CharField(
        max_length=256,
        blank=True,
        null=True)
    role = models.CharField(
        max_length=6,
        choices=k8s_constants.NodeRoles.CHOICES,
        help_text='The role of the node')
    docker_version = models.CharField(
        max_length=128,
        blank=True,
        null=True)
    kubelet_version = models.CharField(
        max_length=10)
    os_image = models.CharField(max_length=128)
    kernel_version = models.CharField(max_length=128)
    schedulable_taints = models.BooleanField(default=False)
    schedulable_state = models.BooleanField(default=False)
    memory = models.BigIntegerField()
    n_cpus = models.SmallIntegerField()
    n_gpus = models.SmallIntegerField()
    status = models.CharField(
        max_length=24,
        default=k8s_constants.NodeLifeCycle.UNKNOWN,
        choices=k8s_constants.NodeLifeCycle.CHOICES)
    is_current = models.BooleanField(default=True)

    @classmethod
    def from_node_item(cls, node):
        params = {
            'name': node.metadata.name,
            'hostname': nodes.get_hostname(node),
            'role': nodes.get_role(node),
            'docker_version': nodes.get_docker_version(node),
            'kubelet_version': node.status.node_info.kubelet_version,
            'os_image': node.status.node_info.os_image,
            'kernel_version': node.status.node_info.kernel_version,
            'schedulable_taints': nodes.is_schedulable(node),
            'schedulable_state': nodes.get_schedulable_state(node),
            'mem': nodes.get_memory_size(node),
            'n_cpus': nodes.get_n_cpus(node),
            'n_gpus': nodes.get_n_gpus(node),
            'status': nodes.get_status(node)}

        return cls(**params)

class NodeGPU(DiffModel):
    """A model that represents the node's gpu."""
    uuid = models.UUIDField(
        default=uuid.uuid4,
        editable=False,
        unique=True,
        null=False)
    serial = models.CharField(max_length=256)
    name = models.CharField(max_length=256)
    device = models.CharField(max_length=256)
    memory = models.BigIntegerField()
    cluster_node = models.ForeignKey(ClusterNode, related_name='gpus')

class ClusterEvents(models.Model):
    """A model to catch all errors and warning events of the cluster."""
    cluster = models.ForeignKey(Cluster, related_name='errors')
    created_at = models.DateTimeField()
    data = JSONField()
    meta = JSONField()
    level = models.CharField(max_length=16)
<commit_msg>Use spawner constants<commit_after># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function

import uuid

from django.conf import settings
from django.contrib.postgres.fields import JSONField
from django.db import models

from libs.models import DiffModel
from spawner.utils import nodes
from spawner.utils.constants import NodeLifeCycle, NodeRoles

class Cluster(DiffModel):
    """A model that represents the cluster api version."""
    uuid = models.UUIDField(
        default=uuid.uuid4,
        editable=False,
        unique=True,
        null=False)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='clusters')
    version_api = JSONField(help_text='The cluster version api infos')

class ClusterNode(models.Model):
    """A model that represents the cluster node."""
    uuid = models.UUIDField(
        default=uuid.uuid4,
        editable=False,
        unique=True,
        null=False)
    name = models.CharField(
        max_length=256,
        blank=True,
        null=True,
        help_text='Name of the node')
    cluster = models.ForeignKey(Cluster, related_name='nodes')
    hostname = models.CharField(
        max_length=256,
        blank=True,
        null=True)
    role = models.CharField(
        max_length=6,
        choices=NodeRoles.CHOICES,
        help_text='The role of the node')
    docker_version = models.CharField(
        max_length=128,
        blank=True,
        null=True)
    kubelet_version = models.CharField(
        max_length=10)
    os_image = models.CharField(max_length=128)
    kernel_version = models.CharField(max_length=128)
    schedulable_taints = models.BooleanField(default=False)
    schedulable_state = models.BooleanField(default=False)
    memory = models.BigIntegerField()
    n_cpus = models.SmallIntegerField()
    n_gpus = models.SmallIntegerField()
    status = models.CharField(
        max_length=24,
        default=NodeLifeCycle.UNKNOWN,
        choices=NodeLifeCycle.CHOICES)
    is_current = models.BooleanField(default=True)

    @classmethod
    def from_node_item(cls, node):
        params = {
            'name': node.metadata.name,
            'hostname': nodes.get_hostname(node),
            'role': nodes.get_role(node),
            'docker_version': nodes.get_docker_version(node),
            'kubelet_version': node.status.node_info.kubelet_version,
            'os_image': node.status.node_info.os_image,
            'kernel_version': node.status.node_info.kernel_version,
            'schedulable_taints': nodes.is_schedulable(node),
            'schedulable_state': nodes.get_schedulable_state(node),
            'mem': nodes.get_memory_size(node),
            'n_cpus': nodes.get_n_cpus(node),
            'n_gpus': nodes.get_n_gpus(node),
            'status': nodes.get_status(node)}

        return cls(**params)

class NodeGPU(DiffModel):
    """A model that represents the node's gpu."""
    uuid = models.UUIDField(
        default=uuid.uuid4,
        editable=False,
        unique=True,
        null=False)
    serial = models.CharField(max_length=256)
    name = models.CharField(max_length=256)
    device = models.CharField(max_length=256)
    memory = models.BigIntegerField()
    cluster_node = models.ForeignKey(ClusterNode, related_name='gpus')

class ClusterEvents(models.Model):
    """A model to catch all errors and warning events of the cluster."""
    cluster = models.ForeignKey(Cluster, related_name='errors')
    created_at = models.DateTimeField()
    data = JSONField()
    meta = JSONField()
    level = models.CharField(max_length=16)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function

import uuid

from django.conf import settings
from django.contrib.postgres.fields import JSONField, ArrayField
from django.db import models

from polyaxon_k8s.utils import nodes

from libs.models import DiffModel

class Cluster(DiffModel):
    """A model that represents the cluster api version."""
    uuid = models.UUIDField(
        default=uuid.uuid4,
        editable=False,
        unique=True,
        null=False)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='clusters')
    version_api = JSONField(help_text='The cluster version api infos')

class ClusterNode(models.Model):
    """A model that represents the cluster node."""
    uuid = models.UUIDField(
        default=uuid.uuid4,
        editable=False,
        unique=True,
        null=False)
    name = models.CharField(
        max_length=256,
        blank=True,
        null=True,
        help_text='Name of the node')
    cluster = models.ForeignKey(Cluster, related_name='nodes')
    hostname = models.CharField(
        max_length=256,
        blank=True,
        null=True)
    role = models.CharField(
        max_length=6,
        choices=nodes.NodeRoles.CHOICES,
        help_text='The rolde of the node')
    docker_version = models.CharField(
        max_length=128,
        blank=True,
        null=True)
    kubelet_version = models.CharField(
        max_length=10)
    os_image = models.CharField(max_length=128)
    kernel_version = models.CharField(max_length=128)
    is_schedulable = models.BooleanField(default=False)
    memory = models.BigIntegerField()
    n_cpus = models.SmallIntegerField()
    n_gpus = models.SmallIntegerField()
    status = models.CharField(
        max_length=24,
        default=nodes.NodeLifeCycle.UNKNOWN,
        choices=nodes.NodeLifeCycle.CHOICES)

    @classmethod
    def from_node_item(cls, node):
        params = {
            'name': node.metadata.name,
            'hostname': nodes.get_hostname(node),
            'role': nodes.get_role(node),
            'docker_version': nodes.get_docker_version(node),
            'kubelet_version': node.status.node_info.kubelet_version,
            'os_image': node.status.node_info.os_image,
            'kernel_version': node.status.node_info.kernel_version,
            'is_schedulable': nodes.is_schedulable(node),
            'mem': nodes.get_memory_size(node),
            'n_cpus': nodes.get_n_cpus(node),
            'n_gpus': nodes.get_n_gpus(node),
            'status': nodes.get_status(node)}

        return cls(**params)

class GPU(DiffModel):
    """A model that represents the node's gpu."""
    uuid = models.UUIDField(
        default=uuid.uuid4,
        editable=False,
        unique=True,
        null=False)
    serial = models.CharField(max_length=256)
    name = models.CharField(max_length=256)
    device = models.CharField(max_length=256)
    memory = models.BigIntegerField()
    cluster_node = models.ForeignKey(ClusterNode, related_name='gpus')

class ClusterErrors(models.Model):
    """A model to catch all errors and warning events of the cluster."""
    cluster = models.ForeignKey(Cluster, related_name='errors')
    created_at = models.DateTimeField()
    data = JSONField()
    meta = JSONField()
    level = models.CharField(max_length=16)
<commit_msg>Update cluster model<commit_after># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function

import uuid

from django.conf import settings
from django.contrib.postgres.fields import JSONField, ArrayField
from django.db import models

from polyaxon_k8s.utils import nodes

from libs.models import DiffModel

class Cluster(DiffModel):
    """A model that represents the cluster api version."""
    uuid = models.UUIDField(
        default=uuid.uuid4,
        editable=False,
        unique=True,
        null=False)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='clusters')
    version_api = JSONField(help_text='The cluster version api infos')

class ClusterNode(models.Model):
    """A model that represents the cluster node."""
    uuid = models.UUIDField(
        default=uuid.uuid4,
        editable=False,
        unique=True,
        null=False)
    name = models.CharField(
        max_length=256,
        blank=True,
        null=True,
        help_text='Name of the node')
    cluster = models.ForeignKey(Cluster, related_name='nodes')
    hostname = models.CharField(
        max_length=256,
        blank=True,
        null=True)
    role = models.CharField(
        max_length=6,
        choices=nodes.NodeRoles.CHOICES,
        help_text='The role of the node')
    docker_version = models.CharField(
        max_length=128,
        blank=True,
        null=True)
    kubelet_version = models.CharField(
        max_length=10)
    os_image = models.CharField(max_length=128)
    kernel_version = models.CharField(max_length=128)
    is_schedulable = models.BooleanField(default=False)
    memory = models.BigIntegerField()
    n_cpus = models.SmallIntegerField()
    n_gpus = models.SmallIntegerField()
    status = models.CharField(
        max_length=24,
        default=nodes.NodeLifeCycle.UNKNOWN,
        choices=nodes.NodeLifeCycle.CHOICES)
    is_current = models.BooleanField(default=True)

    @classmethod
    def from_node_item(cls, node):
        params = {
            'name': node.metadata.name,
            'hostname': nodes.get_hostname(node),
            'role': nodes.get_role(node),
            'docker_version': nodes.get_docker_version(node),
            'kubelet_version': node.status.node_info.kubelet_version,
            'os_image': node.status.node_info.os_image,
            'kernel_version': node.status.node_info.kernel_version,
            'is_schedulable': nodes.is_schedulable(node),
            'mem': nodes.get_memory_size(node),
            'n_cpus': nodes.get_n_cpus(node),
            'n_gpus': nodes.get_n_gpus(node),
            'status': nodes.get_status(node)}

        return cls(**params)

class GPU(DiffModel):
    """A model that represents the node's gpu."""
    uuid = models.UUIDField(
        default=uuid.uuid4,
        editable=False,
        unique=True,
        null=False)
    serial = models.CharField(max_length=256)
    name = models.CharField(max_length=256)
    device = models.CharField(max_length=256)
    memory = models.BigIntegerField()
    cluster_node = models.ForeignKey(ClusterNode, related_name='gpus')

class ClusterErrors(models.Model):
    """A model to catch all errors and warning events of the cluster."""
    cluster = models.ForeignKey(Cluster, related_name='errors')
    created_at = models.DateTimeField()
    data = JSONField()
    meta = JSONField()
    level = models.CharField(max_length=16)
<|endoftext|>