from pathlib import Path
import json
import yaml
import requests
import sys

g_config = {"server": {}, "loaded": False}

def load_config():
    if not g_config["loaded"]:
        config_file = str(Path.home()) + "/.ghpcfe/config"
        p = Path(config_file)
        if p.is_file():
            with p.open("r", encoding="utf-8") as f:
                g_config.update(yaml.safe_load(f)["config"])
                g_config["loaded"] = True
        else:
            invoc = sys.argv[0]
            if invoc.startswith("python"):
                invoc = f"{sys.argv[0]} {sys.argv[1]}"
            print(
                "Please first initialise this application by calling "
                f"`{invoc} config`."
            )
    return g_config

def get_model_state(config, table, key=None):
    url = f"{config['server']['url']}/api/{table}/"
    if key:
        url += f"{key}/"
    headers = {"Authorization": f"Token {config['server']['accessKey']}"}
    resp = requests.get(url, headers=headers)
    if not resp.ok:
        resp.raise_for_status()
    state = resp.json()
    return json.dumps(state)

def model_create(config, table, data):
    url = f"{config['server']['url']}/api/{table}/"
    headers = {"Authorization": f"Token {config['server']['accessKey']}"}
    resp = requests.post(url, data=data, headers=headers)
    if not resp.ok:
        resp.raise_for_status()
    state = resp.json()
    return json.dumps(state)

def print_json(json_str):
    parsed = json.loads(json_str)
    print(json.dumps(parsed, indent=4))

def notimplementedyet(placeholder_function):
    """Decorator method for unimplemented feature warnings"""

    def notimpl_version(*args, **kwargs):
        print(
            f"Error: The function {placeholder_function.__name__} is not yet "
            "implemented in the cli. Please use the web frontend to perform "
            "this action."
        )

    return notimpl_version


#!/usr/bin/env python3
from charms.reactive import when
from charms.reactive import when_not
from charms.reactive import when_any
from charms.reactive import is_state
from charms.reactive import RelationBase
from charmhelpers.core import hookenv
from jujubigdata import utils
from charms.layer.apache_hadoop_namenode import get_cluster_nodes

@when_not('datanode.joined')
def report_blocked():
    hookenv.status_set('blocked', 'Waiting for relation to Slave')

@when('datanode.joined')
@when_any(
    'namenode.started',
    'leadership.set.namenode-ha',
    'namenode-cluster.joined',
    'namenode.cluster.healthy',
    'journalnode.quorum',
    'zookeeper.ready',
)
def report_status(datanode):
    num_slaves = len(datanode.nodes())
    local_hostname = hookenv.local_unit().replace('/', '-')
    chosen_nodes = get_cluster_nodes()
    cluster_roles = set(utils.ha_node_state(node, 1) for node in chosen_nodes)
    chosen = local_hostname in chosen_nodes
    started = is_state('namenode.started')
    ha = is_state('leadership.set.namenode-ha')
    clustered = is_state('namenode-cluster.joined')
    active = 'active' in cluster_roles
    standby = 'standby' in cluster_roles
    healthy = active and standby
    quorum = is_state('journalnode.quorum')
    failover = 'automatic' if is_state('zookeeper.ready') else 'manual'
    degraded = ha and not all([clustered, quorum, healthy])

    if not ha:
        if started:
            extra = 'standalone'
        else:
            extra = 'down'
    else:
        if chosen:
            role = utils.ha_node_state(local_hostname) or 'down'
        else:
            role = 'extra'
        if not degraded:
            extra = 'HA {}, with {} fail-over'.format(role, failover)
        else:
            missing = ' and '.join(filter(None, [
                'NameNode' if not clustered else None,
                'JournalNodes' if not quorum else None,
                'active' if not active else None,
                'standby' if not standby else None,
            ]))
            extra = 'HA degraded {} (missing: {}), with {} fail-over'.format(
                role, missing, failover)
    hookenv.status_set('active', 'Ready ({count} DataNode{s}, {extra})'.format(
        count=num_slaves,
        s='s' if num_slaves > 1 else '',
        extra=extra,
    ))

if __name__ == '__main__':
    if is_state('datanode.joined'):
        report_status(RelationBase.from_state('datanode.joined'))
    else:
        report_blocked()


from random import randint

for i in range(0,10):
    with open(str(i)+"-1.in","w+",encoding='UTF-8') as fd, open(str(i)+"-2.in","w+",encoding="UTF-8") as fd1:
        x1 =randint(1,100)
        x2 =randint(1,100)
        x3 =randint(1,100)
        for q in range(0,x1):
            k=[str(randint(0,100)) for j in range(0,x2)]
            print(",".join(k),file=fd)
        for q in range(0,x2):
            k=[str(randint(0,100)) for j in range(0,x3)]
            print(",".join(k),file=fd1)

import sys
from numpy import genfromtxt,matmul

for i in range(0,10):
    matrix1 = genfromtxt(str(i)+"-1.in",delimiter=',')
    matrix2 = genfromtxt(str(i)+"-2.in",delimiter=',')
    ls = matmul(matrix1,matrix2)
    if type(ls[0]) == type(matrix1):
        ls = [j for i in ls for j in i]
    ls.sort()
    with open(str(i)+".out","w+") as fd:
        for i in ls:
            print(int(i),file=fd)


import os
import logging
import discord

from discord.ext import commands

# For logging events/errors
logger = logging.getLogger('discord')
logger.setLevel(logging.INFO)  # Options in decending order: CRITICAL, ERROR, WARNING, INFO, DEBUG; default WARNING
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)

# Initialize the bot
bot = commands.Bot(command_prefix='?',
                   help_command=commands.DefaultHelpCommand(no_category='Misc', dm_help=True),
                   intents=discord.Intents.all())

# Load all extensions to start
for filename in os.listdir('./extensions'):
    if filename.endswith('.py'):
        bot.load_extension(f"extensions.{filename[:-3]}")

# Load the bot password (TOKEN) as an environment variable
TOKEN = os.getenv('BOT_TOKEN')

# Start the bot
bot.run(TOKEN)


# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details
# http://www.gnu.org/licenses/gpl-3.0.txt

from ...client import PeerFilter
from .base import ItemWidgetBase, ListWidgetBase
from .peer import TUICOLUMNS
from .utils import stringify_torrent_filter

class PeerItemWidget(ItemWidgetBase):
    palette_unfocused = 'peerlist'

    @property
    def id(self):
        return self.data['id']

    @property
    def torrent_id(self):
        return self.data['tid']

class PeerListWidget(ListWidgetBase):
    tuicolumns      = TUICOLUMNS
    ListItemClass   = PeerItemWidget
    keymap_context  = 'peer'
    palette_name    = 'peerlist'
    focusable_items = False

    def __init__(self, srvapi, keymap, tfilter=None, pfilter=None, columns=None, sort=None, title=None):
        super().__init__(srvapi, keymap, columns=columns, sort=sort, title=title)
        self._tfilter = tfilter
        self._pfilter = pfilter
        self._secondary_filter = None

        # Create peer filter generator
        if pfilter is not None:
            def filter_peers(peers):
                yield from pfilter.apply(peers)
        else:
            def filter_peers(peers):
                yield from peers
        self._maybe_filter_peers = filter_peers

        self._poller = self._srvapi.create_poller(
            self._srvapi.torrent.torrents, tfilter, keys=('peers', 'name', 'id')
        )
        self._poller.on_response(self._handle_peers)

    def _handle_peers(self, response):
        if response is None or not response.torrents:
            self.clear()
        else:
            # Auto-generate title from our filters if not set
            if self._title_name is None:
                self._title_name = stringify_torrent_filter(self._tfilter, response.torrents)
                if self._pfilter:
                    self._title_name += ' %s' % self._pfilter

            # Create list items our base widget can handle
            def peers_combined(torrents):
                for t in torrents:
                    yield from self._maybe_filter_peers(t['peers'])
            self._data_dict = {p['id']:p for p in peers_combined(response.torrents)}
        self._invalidate()

    def clear(self):
        for w in self._listbox.body:
            w.data.clearcache()
        super().clear()

    def refresh(self):
        self._poller.poll()

    @property
    def sort(self):
        return self._sort

    @sort.setter
    def sort(self, sort):
        ListWidgetBase.sort.fset(self, sort)
        self._poller.poll()

    @property
    def secondary_filter(self):
        return self._secondary_filter

    @secondary_filter.setter
    def secondary_filter(self, peer_filter):
        if peer_filter is None:
            self._secondary_filter = None
        else:
            self._secondary_filter = PeerFilter(peer_filter)
        self._invalidate()

    def _limit_items(self, peer_widgets):
        # Combine primary and secondary peer filters
        pfilter = self._pfilter
        spfilter = self._secondary_filter
        if pfilter is None:
            pfilter = spfilter
        elif spfilter is not None:
            pfilter = pfilter & spfilter

        if pfilter is not None:
            for pw in peer_widgets:
                if not pfilter.match(pw.data):
                    yield pw


import io
import shutil
import tempfile
from http import HTTPStatus
from urllib.parse import urljoin, unquote

from django import forms
from django.conf import settings
from django.test import TestCase, Client, override_settings
from django.shortcuts import reverse
from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.utils.http import urlencode
from django.core.files.uploadedfile import SimpleUploadedFile
from PIL import Image

from posts.models import Post, Group, Comment
from posts.forms import PostForm
from .utils import write_log

User = get_user_model()
# temporary location for media files to be stored at
TEMP_MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR)

class NamedClient(Client):
    def __init__(self, name):
        super().__init__()
        self.name = name

@override_settings(MEDIA_ROOT=TEMP_MEDIA_ROOT)
class PostsFormsTest(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.new_group = Group.objects.create(
            title='new group',
            slug='new-group',
            description='something descriptive'
        )
        cls.new_group_2 = Group.objects.create(
            title='new group 2',
            slug='new-group-2',
            description='something even more descriptive'
        )
        cls.user_random = User.objects.create(username='wacko wacko')
        cls.user_author = User.objects.create(username='danger-pwrs')
        cls.CREATE = reverse('posts:post_create')
        cls.PROFILE = reverse(
            'posts:profile',
            kwargs={'username': cls.user_author.username}
        )
        cls.EXPECTED_FIELD_TYPES = {
            'text': forms.CharField,
            'group': forms.ModelChoiceField,
            'image': forms.ImageField,
        }
        cls.EXPECTED_HTML_TAGS = {
            'text': (
                '<textarea name="text" cols="40" '
                'rows="10" required id="id_text">'
            ),
            'group': '<option value="" selected> Выберите группу </option>',
            'image': (
                '<input type="file" name="image" '
                'accept="image/*" id="id_image">'
            )
        }

    @classmethod
    def tearDownClass(cls):
        super().tearDownClass()
        cache.clear()
        shutil.rmtree(TEMP_MEDIA_ROOT, ignore_errors=True)

    @staticmethod
    def get_test_img(color: str) -> SimpleUploadedFile:
        image = Image.new('RGB', (10, 10), color)
        byte_arr = io.BytesIO()
        image.save(byte_arr, format='jpeg')
        file = SimpleUploadedFile(
            name=f'{color}.jpeg',
            content=byte_arr.getvalue(),
            content_type='image/jpeg'
        )
        return file

    def get_post_data(self, action):
        post_data = {
            'create': {
                'text': 'Test post 1',
                'group': self.new_group.pk,
                'image': self.get_test_img('red'),
            },
            'update': {
                'text': 'Test post 2',
                'group': self.new_group_2.pk,
                'image': self.get_test_img('blue')
            }
        }
        return post_data[action]

    def create_post(self, test_client):
        data = self.get_post_data('create')
        response = PostsFormsTest.post_to(
            test_client, PostsFormsTest.CREATE, data
        )
        return response

    def update_post(self, test_client, post_id):
        edit_url = reverse('posts:post_edit', args=(post_id,))
        data = self.get_post_data('update')
        response = PostsFormsTest.post_to(
            test_client, edit_url, data
        )
        return response

    def post_to(test_client, to, data):
        response = test_client.post(
            to,
            data,
            follow=True,
            multipart=True,
        )
        write_log(test_client, to, data, TEMP_MEDIA_ROOT, response)
        return response

    def setUp(self):
        self.form = PostForm()
        self.guest_client = NamedClient('Guest client')
        self.auth_client = NamedClient('Authorised client')
        self.auth_client.force_login(self.user_random)
        self.author_client = NamedClient('Author client')
        self.author_client.force_login(self.user_author)

    def test_expected_fields(self):
        """test if the fields are present"""
        for field in ('text', 'group'):
            with self.subTest(field_name=field):
                self.assertIn(field, self.form.fields)

    def test_create_form_is_rendered(self):
        """test if the fields are rendered correctly"""
        for field, html in self.EXPECTED_HTML_TAGS.items():
            with self.subTest(field_name=field):
                self.assertInHTML(html, str(self.form))

    def test_field_types(self):
        """test if the fields are of correct types"""
        for field_name, field_type in self.EXPECTED_FIELD_TYPES.items():
            with self.subTest(field_name=field_name):
                field = self.form.fields.get(field_name)
                self.assertIsInstance(field, field_type)

    def test_count_increment(self):
        """test if post objects count is incremented"""
        post_count = Post.objects.count()
        expected_increment = {
            self.guest_client: post_count,
            self.auth_client: post_count + 1,
        }
        for client, new_count in expected_increment.items():
            with self.subTest(client=client.name):
                self.create_post(client)
                self.assertEqual(
                    Post.objects.count(), new_count,
                )

    def test_create_redirects(self):
        """test if user is redirected to profile page"""
        response = self.create_post(self.author_client)
        self.assertRedirects(response, self.PROFILE)

    def test_edit_form_initial_state(self):
        """test if edit form's fields are correctly pre-populated"""
        self.create_post(self.author_client)
        test_post = Post.objects.latest('pub_date')
        edit_url = reverse(
            'posts:post_edit',
            kwargs={'pk': test_post.id}
        )
        r = self.author_client.get(edit_url)
        form = r.context['form']
        for field, value in form.initial.items():
            with self.subTest(field=field):
                field_name = 'group_id' if field == 'group' else field
                self.assertEqual(test_post.__dict__[field_name], value)

    def test_edit_form_change(self):
        """test if initial post is modified"""
        expected_asserts = {
            self.guest_client: self.assertEqual,
            self.auth_client: self.assertEqual,
            self.author_client: self.assertNotEqual
        }
        for client, func in expected_asserts.items():
            self.create_post(self.author_client)
            test_post = Post.objects.latest('pub_date')
            self.update_post(client, test_post.id)
            edited_post = Post.objects.get(id=test_post.id)
            for field in ('text', 'group', 'image'):
                with self.subTest(client=client.name, field=field):
                    func(
                        getattr(test_post, field), getattr(edited_post, field)
                    )

    def test_edit_redirects(self):
        """test if user is redirected to details page"""
        self.create_post(self.author_client)
        test_post = Post.objects.latest('pub_date')
        response = self.update_post(
            self.author_client, test_post.id
        )
        details_url = reverse('posts:post_detail', args=(test_post.id,))
        self.assertRedirects(response, details_url)

    def test_comment_redirects(self):
        """test if unauthorised user is redirected to login page"""
        self.create_post(self.author_client)
        test_post = Post.objects.latest('pub_date')
        add_comment_url = reverse(
            'posts:add_comment',
            kwargs={'post_id': test_post.id}
        )
        query_string = '?' + unquote(urlencode({'next': add_comment_url}))
        response = self.client.post(
            path=add_comment_url,
            data={'text': 'Hello there'},
            follow=True
        )
        self.assertRedirects(
            response=response,
            expected_url=urljoin(
                reverse(settings.LOGIN_URL),
                query_string
            ),
            status_code=HTTPStatus.FOUND,
            target_status_code=HTTPStatus.OK
        )

    def test_comment_created(self):
        """test if a comment left by an authorised user is created and shown"""
        self.create_post(self.author_client)
        test_post = Post.objects.latest('pub_date')
        test_text = 'Hello there'
        self.auth_client.post(
            path=reverse('posts:add_comment', args=(test_post.id,)),
            data={'text': test_text},
            follow=True
        )
        expected_comment = Comment.objects.latest('pub_date')
        expected_context = self.client.get(
            reverse(
                'posts:post_detail',
                kwargs={'post_id': test_post.id}
            )
        ).context
        self.assertTrue(expected_comment in test_post.comments.all())
        self.assertTrue(expected_comment in expected_context['comments'])
        self.assertEqual(expected_comment.text, test_text)


#Recebo tres valores e utilizandoa a formula (a + b + abs(a - b)) / 2 exibo o maior valor dos tres recebidos

values = input().split()
a,b,c = values
maiorAB = (int(a) + int(b) + abs(int(a) - int(b))) / 2

if maiorAB > int(c):
	print(int(maiorAB), "eh o maior")
else:
	print(int(c), "eh o maior")


#https://www.youtube.com/watch?v=5o-kdjv7FD0
#pending
def num(n):
	if n == 0 or n ==  1 : return 1
	nums[0] = 1; nums[1] = 1
	for i in range (2, n):
		nums[i] = nums[i-1] + nums[i-2]
	return nums[n]

#num(5)


import itertools
from pysc2.lib.named_array import NamedNumpyArray
from pysc2.lib import features, actions, units, buffs
from settings import STEP_MUL

class Memory:
    def __init__(self, agent):
        self.agent = agent
        self.obs = None

        class CustomDict(dict):
            def __getitem__(self, key):
                try:
                    return super().__getitem__(key)
                except KeyError:
                    return []

        self.self_units = CustomDict()
        self.enemy_units = CustomDict()
        self.neutral_units = CustomDict()
        self.birth_dates = {}
        self.base_locations = []
        self.discarded_units = []
        self.has_rally_point = []
        self.spell_targets = {}
        self.expired_tumors = set()
        self.scouts = {}
        self.scout_timeout = {}
        self.creep_tumor_tries = {}
        self.function_timeout = {}
        self.game_step = 0

    def update(self, obs):
        self.obs = obs
        self.update_units()
        self.update_miscellaneous()
        self.game_step += 1

    def update_miscellaneous(self):
        try:
            for u in self.self_units[units.Zerg.CreepTumorBurrowed]:
                if u.order_id_0 == actions.RAW_FUNCTIONS.Build_CreepTumor_Tumor_pt.id:
                    self.expired_tumors.add(u.tag)
        except KeyError:
            pass

        def tick_timeout(timeout_dict):
            to_remove = []
            for key in timeout_dict:
                timeout_dict[key] -= STEP_MUL
                if timeout_dict[key] < 0:
                    to_remove.append(key)
            for key in to_remove:
                timeout_dict.pop(key)

        tick_timeout(self.scout_timeout)
        tick_timeout(self.function_timeout)

        for b in self.agent.get_units_agg('Hatchery'):
            if b.buff_id_0 == buffs.Buffs.QueenSpawnLarvaTimer:
                queen_tag = [q for q, h in self.spell_targets.items() if h == b.tag]
                if queen_tag:
                    self.spell_targets.pop(queen_tag[0])

    def update_units(self):
        alliances = self.obs.observation.raw_units[:, features.FeatureUnit.alliance]
        self_units = self.obs.observation.raw_units[alliances == features.PlayerRelative.SELF]
        enemy_units = self.obs.observation.raw_units[alliances == features.PlayerRelative.ENEMY]
        neutral_units = self.obs.observation.raw_units[alliances == features.PlayerRelative.NEUTRAL]

        killed = self.obs.observation._response_observation().observation.raw_data.event.dead_units
        self._update_units(self.self_units, self_units, killed)
        self._update_units(self.enemy_units, enemy_units, killed)
        self._update_units(self.neutral_units, neutral_units, killed)

    def _update_units(self, old, new, killed):
        # Only keep visible units
        displays = new[:, features.FeatureUnit.display_type]
        new = new[displays != 2] # remove snapshots
        new = [self._add_unit_variables(u) for u in new]

        # Add empty lists for previously unseen unit types
        visible_types = set([u.unit_type for u in new])
        for v_type in visible_types:
            if v_type not in old:
                old[v_type] = []

        # Update / remove old, unseen units
        new_tags = [u.tag for u in new]
        to_remove = [u.tag for u in new]
        missing = [u for u in list(itertools.chain.from_iterable(old.values()))
                   if u.tag not in new_tags]
        zerg_build_fcts = []
        for unit in dir(units.Zerg):
            try:
                zerg_build_fcts.append(getattr(actions.RAW_FUNCTIONS, f'Build_{unit}_pt').id)
            except KeyError:
                pass
            try:
                zerg_build_fcts.append(getattr(actions.RAW_FUNCTIONS, f'Build_{unit}_unit').id)
            except KeyError:
                pass

        visibility_map = self.obs.observation.feature_minimap.visibility_map.T
        for u in missing:
            # Untrack dead units
            # Make sure that we are not cheating :
            # Only include units that we were seeing, or that are ours :
            died = u.tag in killed \
                   and (u.display_type != 2 or u.alliance == features.PlayerRelative.SELF)

            # Also untrack our zerg workers that are currently building
            died = died or (u.alliance == features.PlayerRelative.SELF
                           and u.unit_type == units.Zerg.Drone
                           and u.order_id_0 in zerg_build_fcts)

            if died or u.tag < 0:
                to_remove.append(u.tag)
                self.discarded_units.append(u.tag)
                for key in self.scouts:
                    if u.tag in self.scouts[key]:
                        self.scouts[key].remove(u.tag)
                if u.alliance == features.PlayerRelative.SELF \
                                        and u.unit_type in [units.Zerg.Hatchery,
                                                            units.Zerg.Lair,
                                                            units.Zerg.Hive,
                                                            units.Protoss.Nexus,
                                                            units.Terran.CommandCenter,
                                                            units.Terran.CommandCenterFlying,
                                                            units.Terran.OrbitalCommand,
                                                            units.Terran.OrbitalCommandFlying,
                                                            units.Terran.PlanetaryFortress]:
                    self.base_locations.remove((u.x, u.y))
                if u.alliance == features.PlayerRelative.SELF and u.unit_type == units.Zerg.Queen:
                    try:
                        self.spell_targets.pop(u.tag)
                    except KeyError:
                        pass
            else:
                u.display_type = 2 # seen
                u.time_unseen += 1
                u.time_alive += 1
                if visibility_map[u.x, u.y] == features.Visibility.VISIBLE:
                    u.pos_tracked = 0

        for key, type_units in old.items():
            old[key] = [u for u in type_units if u.tag not in to_remove]

        # Add / update new units
        for u in new:
            old[u.unit_type].append(u)

    def _add_unit_variables(self, unit):
        if unit.tag == 0:
            unit.tag = min(0, min(self.birth_dates.keys())) - 1
        if unit.tag not in self.birth_dates:
            self.birth_dates[unit.tag] = self.game_step
            if unit.unit_type in [units.Terran.CommandCenter, units.Protoss.Nexus, units.Zerg.Hatchery] \
                                                    and unit.alliance == features.PlayerRelative.SELF:
                self.base_locations.append((unit.x, unit.y))

        values = {'time_unseen': 0,
                  'time_alive': self.game_step - self.birth_dates[unit.tag],
                  'pos_tracked': 1}

        new_values = unit.tolist() + list(values.values())
        new_vars = list(unit._index_names[0].keys()) + list(values.keys())
        return NamedNumpyArray(new_values, new_vars)


# #Aula 10 Condições
#
# nome = str(input('Qual é seu nome? '))
# if nome =='Leonardo':
#     print('Que nome lindo você tem!')
#
# else:
#     print('Seu nome é tão chato!')
#
# print(f'Bom dia, {nome}')

n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
n = (n1+n2)/2

if n >=6:

    print(f'Parabéns, sua média é {n:.1f} e ela foi muito acima do esperado! ')

else:

    print(f'Sua média é: {n:.1f} e ela foi abaixo do esperado')


# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import product
from sys import stdin

def getInputs():
    return list(map(int, stdin.readline().strip().split()))

def cartesian_product(A,B):
    result = sorted(list(product(A,B)))
    for pair in result:
        print(pair, end=' ')

# {
# Driver Code starts
if __name__ == "__main__":
    # write your code here
    A = getInputs()
    B = getInputs()
    cartesian_product(A,B)

# } Driver Code ends


import configparser
import os
import sys

from supabase import Client, create_client

config = configparser.ConfigParser()
config.read(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'config.ini'))

parent_module = sys.modules[".".join(__name__.split(".")[:-1]) or "__main__"]
if __name__ == "__main__" or parent_module.__name__ == "__main__":
    from CSVHandler import CSVHandler
    from Skill import Skill
else:
    from .CSVHandler import CSVHandler
    from .Skill import Skill

SUPABASE_URL = config["DATABASE"]["DATABASE_URL"]
SUPABASE_KEY = config["DATABASE"]["DATABASE_API_KEY"]

class DatabaseHandler:
    def __init__(self, database:str = "Skills") -> None:
        self.database = database

    def update_data(self) -> int:
        data = CSVHandler.load_skills_from_csv()
        data = [item.export() for item in data]
        supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)

        try:
            return_data = supabase.table(self.database).upsert(data).execute()

            inserted = len(return_data.data)
        except:
            # conn.rollback()
            raise
        print(f"Inserted {inserted} new rows")
        return inserted

    def get_data(self, raw=False) -> list[Skill] or list[tuple]:
        supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)

        data = supabase.table(self.database).select("*").execute()

        skills = [tuple(skill.values()) for skill in data.data]
        if raw:
            return skills
        skills = [Skill().import_data(data) for data in skills]
        return skills

    def get_headers(self) -> list[str]:
        supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)

        data = supabase.table(self.database).select("*").limit(1).execute()

        headers = [column for column in data.data[0].keys()]

        return headers

if __name__ == "__main__":
    db = DatabaseHandler()

    db.update_data()


"""
model equilibrium, profile adjust
"""
import numpy as np
from Namelist import Namelist
from ipsframework import Component

class modeleq_constraint_pscale(Component):
    def __init__(self, services, config):
        Component.__init__(self, services, config)
        print('Created %s' % (self.__class__))

    def init(self, timeid=0):
        print('modeleq_constraint_pscale.init() called')
        return

    def step(self, timeid=0):
        print('modeleq_constraint_pscale.step() started')

        self.services.stage_state()
        cur_instate_file = self.services.get_config_param('CURRENT_INSTATE')

        pscale = float(self.PSCALE)

        scale_pressure(cur_instate_file, pscale)

        self.services.update_state()
        self.services.stage_output_files(timeid, self.OUTPUT_FILES, save_plasma_state=False)

def scale_pressure(f_instate, pscale=1.):
    instate = Namelist(f_instate)
    rho = instate["inmetric"]["rho"]
    pmhd = np.array(instate["instate"]["pmhd"])

    instate["instate"]["pmhd"] = pscale*pmhd

    instate.write(f_instate)