# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, print_function, unicode_literals
from collections import namedtuple, OrderedDict
import numpy as np
from astropy.table import Table
from astropy.units import Unit, Quantity
from astropy.coordinates import Angle, SkyCoord
from astropy.time import Time
from astropy.utils import lazyproperty
from ..utils.scripts import make_path
from ..utils.time import time_relative_to_ref
from ..utils.testing import Checker
from .gti import GTI

__all__ = ["ObservationTable"]

class ObservationTable(Table):
    """Observation table.

    Data format specification: :ref:`gadf:obs-index`
    """

    @classmethod
    def read(cls, filename, **kwargs):
        """Read an observation table from file.

        Parameters
        ----------
        filename : `~gammapy.extern.pathlib.Path`, str
            Filename
        """
        filename = make_path(filename)
        return super(ObservationTable, cls).read(str(filename), **kwargs)

    @property
    def pointing_radec(self):
        """Pointing positions as ICRS (`~astropy.coordinates.SkyCoord`)"""
        return SkyCoord(self["RA_PNT"], self["DEC_PNT"], unit="deg", frame="icrs")

    @property
    def pointing_galactic(self):
        """Pointing positions as Galactic (`~astropy.coordinates.SkyCoord`)"""
        return SkyCoord(
            self["GLON_PNT"], self["GLAT_PNT"], unit="deg", frame="galactic"
        )

    @lazyproperty
    def _index_dict(self):
        """Dict containing row index for all obs ids"""
        # TODO: Switch to http://docs.astropy.org/en/latest/table/indexing.html once it is more stable
        temp = zip(self["OBS_ID"], np.arange(len(self)))
        return dict(temp)

    def get_obs_idx(self, obs_id):
        """Get row index for given ``obs_id``.

        Raises KeyError if observation is not available.

        Parameters
        ----------
        obs_id : int, list
            observation ids

        Returns
        -------
        idx : list
            indices corresponding to obs_id
        """
        idx = [self._index_dict[key] for key in np.atleast_1d(obs_id)]
        return idx

    def select_obs_id(self, obs_id):
        """Get `~gammapy.data.ObservationTable` containing only ``obs_id``.

        Raises KeyError if observation is not available.

        Parameters
        ----------
        obs_id: int, list
            observation ids
        """
        return self[self.get_obs_idx(obs_id)]

    def summary(self):
        """Info string (str)"""
        obs_name = self.meta.get("OBSERVATORY_NAME", "N/A")

        return "\n".join(
            [
                "Observation table:",
                "Observatory name: {!r}".format(obs_name),
                "Number of observations: {}".format(len(self)),
                # TODO: clean this up. Make those properties?
                # ontime = Quantity(self['ONTIME'].sum(), self['ONTIME'].unit)
                #
                # ss += 'Total observation time: {}\n'.format(ontime)
                # livetime = Quantity(self['LIVETIME'].sum(), self['LIVETIME'].unit)
                # ss += 'Total live time: {}\n'.format(livetime)
                # dtf = 100. * (1 - livetime / ontime)
                # ss += 'Average dead time fraction: {:5.2f}%\n'.format(dtf)
                # time_ref = time_ref_from_dict(self.meta)
                # time_ref_unit = time_ref_from_dict(self.meta).format
                # ss += 'Time reference: {} {}'.format(time_ref, time_ref_unit)
            ]
        )

    def select_linspace_subset(self, num):
        """Select subset of observations.

        This is mostly useful for testing, if you want to make
        the analysis run faster.

        Parameters
        ----------
        num : int
            Number of samples to select.

        Returns
        -------
        table : `ObservationTable`
            Subset observation table (a copy).
        """
        indices = np.linspace(start=0, stop=len(self), num=num, endpoint=False)
        # Round down to nearest integer
        indices = indices.astype("int")
        return self[indices]

    def select_range(self, selection_variable, value_range, inverted=False):
        """Make an observation table, applying some selection.

        Generic function to apply a 1D box selection (min, max) to a
        table on any variable that is in the observation table and can
        be casted into a `~astropy.units.Quantity` object.

        If the range length is 0 (min = max), the selection is applied
        to the exact value indicated by the min value. This is useful
        for selection of exact values, for instance in discrete
        variables like the number of telescopes.

        If the inverted flag is activated, the selection is applied to
        keep all elements outside the selected range.

        Parameters
        ----------
        selection_variable : str
            Name of variable to apply a cut (it should exist on the table).
        value_range : `~astropy.units.Quantity`-like
            Allowed range of values (min, max). The type should be
            consistent with the selection_variable.
        inverted : bool, optional
            Invert selection: keep all entries outside the (min, max) range.

        Returns
        -------
        obs_table : `~gammapy.data.ObservationTable`
            Observation table after selection.
        """
        value_range = Quantity(value_range)

        # read values into a quantity in case units have to be taken into account
        value = Quantity(self[selection_variable])

        mask = (value_range[0] <= value) & (value < value_range[1])

        if np.allclose(value_range[0].value, value_range[1].value):
            mask = value_range[0] == value

        if inverted:
            mask = np.invert(mask)

        return self[mask]

    def select_time_range(self, selection_variable, time_range, inverted=False):
        """Make an observation table, applying a time selection.

        Apply a 1D box selection (min, max) to a
        table on any time variable that is in the observation table.
        It supports both fomats: absolute times in
        `~astropy.time.Time` variables and [MET]_.

        If the inverted flag is activated, the selection is applied to
        keep all elements outside the selected range.

        Parameters
        ----------
        selection_variable : str
            Name of variable to apply a cut (it should exist on the table).
        time_range : `~astropy.time.Time`
            Allowed time range (min, max).
        inverted : bool, optional
            Invert selection: keep all entries outside the (min, max) range.

        Returns
        -------
        obs_table : `~gammapy.data.ObservationTable`
            Observation table after selection.
        """
        if self.meta["TIME_FORMAT"] == "absolute":
            # read times into a Time object
            time = Time(self[selection_variable])
        else:
            # transform time to MET
            time_range = time_relative_to_ref(time_range, self.meta)
            # read values into a quantity in case units have to be taken into account
            time = Quantity(self[selection_variable])

        mask = (time_range[0] <= time) & (time < time_range[1])

        if inverted:
            mask = np.invert(mask)

        return self[mask]

    def select_observations(self, selection=None):
        """Select subset of observations.

        Returns a new observation table representing the subset.

        There are 3 main kinds of selection criteria, according to the
        value of the **type** keyword in the **selection** dictionary:

        - sky regions (boxes or circles)

        - time intervals (min, max)

        - intervals (min, max) on any other parameter present in the
          observation table, that can be casted into an
          `~astropy.units.Quantity` object

        Allowed selection criteria are interpreted using the following
        keywords in the **selection** dictionary under the **type** key.

        - ``sky_box`` and ``sky_circle`` are 2D selection criteria acting
          on sky coordinates

            - ``sky_box`` is a squared region delimited by the **lon** and
              **lat** keywords: both tuples of format (min, max); uses
              `~gammapy.catalog.select_sky_box`

            - ``sky_circle`` is a circular region centered in the coordinate
              marked by the **lon** and **lat** keywords, and radius **radius**;
              uses `~gammapy.catalog.select_sky_circle`

          in each case, the coordinate system can be specified by the **frame**
          keyword (built-in Astropy coordinate frames are supported, e.g.
          ``icrs`` or ``galactic``); an aditional border can be defined using
          the **border** keyword

        - ``time_box`` is a 1D selection criterion acting on the observation
          start time (**TSTART**); the interval is set via the
          **time_range** keyword; uses
          `~gammapy.data.ObservationTable.select_time_range`

        - ``par_box`` is a 1D selection criterion acting on any
          parameter defined in the observation table that can be casted
          into an `~astropy.units.Quantity` object; the parameter name
          and interval can be specified using the keywords **variable** and
          **value_range** respectively; min = max selects exact
          values of the parameter; uses
          `~gammapy.data.ObservationTable.select_range`

        In all cases, the selection can be inverted by activating the
        **inverted** flag, in which case, the selection is applied to keep all
        elements outside the selected range.

        A few examples of selection criteria are given below.

        Parameters
        ----------
        selection : dict
            Dictionary with a few keywords for applying selection cuts.

        Returns
        -------
        obs_table : `~gammapy.data.ObservationTable`
            Observation table after selection.

        Examples
        --------
        >>> selection = dict(type='sky_box', frame='icrs',
        ...                  lon=Angle([150, 300], 'deg'),
        ...                  lat=Angle([-50, 0], 'deg'),
        ...                  border=Angle(2, 'deg'))
        >>> selected_obs_table = obs_table.select_observations(selection)

        >>> selection = dict(type='sky_circle', frame='galactic',
        ...                  lon=Angle(0, 'deg'),
        ...                  lat=Angle(0, 'deg'),
        ...                  radius=Angle(5, 'deg'),
        ...                  border=Angle(2, 'deg'))
        >>> selected_obs_table = obs_table.select_observations(selection)

        >>> selection = dict(type='time_box',
        ...                  time_range=Time(['2012-01-01T01:00:00', '2012-01-01T02:00:00']))
        >>> selected_obs_table = obs_table.select_observations(selection)

        >>> selection = dict(type='par_box', variable='ALT',
        ...                  value_range=Angle([60., 70.], 'deg'))
        >>> selected_obs_table = obs_table.select_observations(selection)

        >>> selection = dict(type='par_box', variable='OBS_ID',
        ...                  value_range=[2, 5])
        >>> selected_obs_table = obs_table.select_observations(selection)

        >>> selection = dict(type='par_box', variable='N_TELS',
        ...                  value_range=[4, 4])
        >>> selected_obs_table = obs_table.select_observations(selection)
        """
        from ..catalog import select_sky_box, select_sky_circle

        if "inverted" not in selection.keys():
            selection["inverted"] = False

        if selection["type"] == "sky_circle":
            lon = selection["lon"]
            lat = selection["lat"]
            radius = selection["radius"] + selection["border"]
            return select_sky_circle(
                self,
                lon_cen=lon,
                lat_cen=lat,
                radius=radius,
                frame=selection["frame"],
                inverted=selection["inverted"],
            )

        elif selection["type"] == "sky_box":
            lon = selection["lon"]
            lat = selection["lat"]
            border = selection["border"]
            lon = Angle([lon[0] - border, lon[1] + border])
            lat = Angle([lat[0] - border, lat[1] + border])
            return select_sky_box(
                self,
                lon_lim=lon,
                lat_lim=lat,
                frame=selection["frame"],
                inverted=selection["inverted"],
            )

        elif selection["type"] == "time_box":
            return self.select_time_range(
                "TSTART", selection["time_range"], selection["inverted"]
            )

        elif selection["type"] == "par_box":
            return self.select_range(
                selection["variable"], selection["value_range"], selection["inverted"]
            )

        else:
            raise ValueError("Invalid selection type: {}".format(selection["type"]))

    def create_gti(self, obs_id):
        """Returns a GTI table containing TSTART and TSTOP from the table.

        TODO: This method can be removed once GTI tables are explicitly required in Gammapy.

        Parameters
        ----------
        obs_id : int
            ID of the observation for which the GTI table will be created

        Returns
        -------
        gti : `~gammapy.data.GTI`
            GTI table containing one row (TSTART and TSTOP of the observation with `obs_id`)
        """
        meta = OrderedDict(
            EXTNAME="GTI",
            HDUCLASS="GADF",
            HDUDOC="https://github.com/open-gamma-ray-astro/gamma-astro-data-formats",
            HDUVERS="0.2",
            HDUCLAS1="GTI",
            MJDREFI=self.meta["MJDREFI"],
            MJDREFF=self.meta["MJDREFF"],
            TIMEUNIT=self.meta.get("TIMEUNIT", "s"),
            TIMESYS=self.meta["TIMESYS"],
            TIMEREF=self.meta.get("TIMEREF", "LOCAL"),
        )

        obs = self.select_obs_id(obs_id)

        gti = Table(meta=meta)
        gti["START"] = obs["TSTART"].quantity.to("s")
        gti["STOP"] = obs["TSTOP"].quantity.to("s")

        return GTI(gti)

class ObservationTableChecker(Checker):
    """Event list checker.

    Data format specification: ref:`gadf:iact-events`

    Parameters
    ----------
    event_list : `~gammapy.data.EventList`
        Event list
    """

    CHECKS = {
        "meta": "check_meta",
        "columns": "check_columns",
        # "times": "check_times",
        # "coordinates_galactic": "check_coordinates_galactic",
        # "coordinates_altaz": "check_coordinates_altaz",
    }

    # accuracy = {"angle": Angle("1 arcsec"), "time": Quantity(1, "microsecond")}

    # https://gamma-astro-data-formats.readthedocs.io/en/latest/events/events.html#mandatory-header-keywords
    meta_required = [
        "HDUCLASS",
        "HDUDOC",
        "HDUVERS",
        "HDUCLAS1",
        "HDUCLAS2",
        # https://gamma-astro-data-formats.readthedocs.io/en/latest/general/time.html#time-formats
        "MJDREFI",
        "MJDREFF",
        "TIMEUNIT",
        "TIMESYS",
        "TIMEREF",
        # https://gamma-astro-data-formats.readthedocs.io/en/latest/general/coordinates.html#coords-location
        "GEOLON",
        "GEOLAT",
        "ALTITUDE",
    ]

    _col = namedtuple("col", ["name", "unit"])
    columns_required = [
        _col(name="OBS_ID", unit=""),
        _col(name="RA_PNT", unit="deg"),
        _col(name="DEC_PNT", unit="deg"),
        _col(name="TSTART", unit="s"),
        _col(name="TSTOP", unit="s"),
    ]

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

    def _record(self, level="info", msg=None):
        return {"level": level, "hdu": "obs-index", "msg": msg}

    def check_meta(self):
        m = self.obs_table.meta

        meta_missing = sorted(set(self.meta_required) - set(m))
        if meta_missing:
            yield self._record(
                level="error", msg="Missing meta keys: {!r}".format(meta_missing)
            )

        if m.get("HDUCLAS1", "") != "INDEX":
            yield self._record(level="error", msg="HDUCLAS1 must be INDEX")
        if m.get("HDUCLAS2", "") != "OBS":
            yield self._record(level="error", msg="HDUCLAS2 must be OBS")

    def check_columns(self):
        t = self.obs_table

        if len(t) == 0:
            yield self._record(level="error", msg="Observation table has zero rows")

        for name, unit in self.columns_required:
            if name not in t.colnames:
                yield self._record(
                    level="error", msg="Missing table column: {!r}".format(name)
                )
            else:
                if Unit(unit) != (t[name].unit or ""):
                    yield self._record(
                        level="error", msg="Invalid unit for column: {!r}".format(name)
                    )


# -*- coding: UTF-8 -*-
from django.core import mail
from django.test import TestCase
from django.utils import timezone
from django.contrib.humanize.templatetags.humanize import date, naturaltime

from toolkit import settings
from toolkit.casper.workflow_case import BaseScenarios

from model_mommy import mommy

import datetime

class TaskReminderServiceTest(BaseScenarios, TestCase):
    def setUp(self):
        super(TaskReminderServiceTest, self).setUp()
        self.basic_workspace()
        item = mommy.make('item.Item',
                          matter=self.matter,
                          date_due=timezone.now() + datetime.timedelta(days=settings.REMIND_DUE_DATE_LIMIT - 1))
        self.task = mommy.make('task.Task',
                                item=item,
                                is_complete=False,
                                created_by=self.lawyer,
                                assigned_to=[self.user],
                                date_due=timezone.now() + datetime.timedelta(days=settings.REMIND_DUE_DATE_LIMIT + 1))

    def test_reminder_positive(self):
        # create item in reminding period

        self.task.send_reminder(from_user=self.lawyer)
        outbox = mail.outbox
        self.assertEqual(len(outbox), 1)
        email = outbox[0]
        self.assertEqual(email.subject, u'[ACTION REQUIRED] Please complete the task')
        self.assertTrue('
Warning, Task Overdue
' not in email.body)

    def test_reminder_overdue(self):
        self.task.date_due = timezone.now() + datetime.timedelta(days=-5)
        self.task.save(update_fields=['date_due'])

        self.task.send_reminder(from_user=self.lawyer)
        outbox = mail.outbox
        self.assertEqual(len(outbox), 1)
        email = outbox[0]
        self.assertEqual(email.subject, u'[ACTION REQUIRED] (Expired) Please complete the task')
        self.assertTrue('
Warning, Task Overdue
' in email.body)


from trading_ig.config import config
import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# if you need to cache to DB your requests
from datetime import timedelta
import requests_cache
from getting_realtime_data.data_retrieval import Data_Retrieval
from sending_orders.order_management import Order_Management
from management_of_position.position_management import Position_Management
from predefined_functions.initialisation import Initialisation
from get_data.get_market_data import Get_Market_Data
import time
from datetime import datetime, timedelta, date
from predefined_functions.defined_functionality import Defined_Functionality
import traceback
import pandas as pd
import sys
import math

# the newest one where you make market order base on price movements 5 or more and try to catch the trend

class Algo0:
    def __init__(self):
        logging.basicConfig(level=logging.INFO)
        self.df = Defined_Functionality()

    def run(self):

        while(True):

            try:

                start_time = datetime.now()
                self.check_all_working_orders()
                end_time = datetime.now() - start_time
                print(end_time)

            except Exception as e:
                print(e, "traceback back in custom algo frame work")
                traceback.print_exc()

    def check_all_working_orders(self):
        # check if opening market has passed , if we have a position in it then close all other orders, or if only one of that order remains
        orders = self.df.get_working_orders()
        for epic in orders["epic"].unique():
            self.checking_working_order_is_present_under_epic_and_amend_orders(epic=epic)

    def checking_working_order_is_present_under_epic_and_amend_orders(self, epic):
        # check there are two orders for each epic
        created_order = True
        while(True):
            orders = self.df.get_working_orders_by_epic(epic=epic)
            if orders.index.size == 2:
                directions = orders["direction"].to_list()
                if ("BUY" in directions and "SELL" in directions):
                    data = self.df.get_market_data(epic=epic)

                    if data == None:
                        continue
                    # market is still open
                    map_of_time = data["instrument"]["openingHours"]
                    if map_of_time == None:
                        break
                    single_time = map_of_time["marketTimes"][0]["openTime"]
                    opening_market_time = datetime.strptime(single_time, '%H:%M').time()
                    diff_in_time = datetime.combine(date.today(), opening_market_time) - datetime.now()

                    # if the time is bigger than x second then we can still put orders in place
                    total_seconds = diff_in_time.total_seconds()
                    # -1 seconds
                    if total_seconds < -(0.2):
                        # delete the orders if any are pending
                        break

                    position = self.df.find_open_position_by_epic(epic=epic)
                    if len(position) != 0:
                        break

                    print("market is not open yet and orders are in place nothing needs to be done yet")
                    return created_order

            break

        print("delete orders")
        self.df.cancel_orders_by_epic(epic=epic)
        created_order = False

        return created_order


import os
import pickle
import cv2

import numpy as np
import torch
from omegaconf import DictConfig

from bbr.datasets.tfs import get_flickr_transform

class ImageLoader(torch.utils.data.Dataset):
    def __init__(self, root, transform=None, split="train", img_path=False):
        annt_path = os.path.join(root, "annotations", split + ".pickle")
        with open(annt_path, "rb") as f:
            self.annotations = pickle.load(f, encoding="latin1")
        self.files = list(self.annotations.keys())
        print("num of data:{}".format(len(self.files)))
        self.transform = transform
        self.split = split
        self.img_folder = os.path.join(root, "ReferIt_Images")
        self.img_path = img_path

    def __getitem__(self, index):
        item = str(self.files[index])
        folder = (2 - len(str(int(item) // 1000))) * "0" + str(int(item) // 1000)
        img_path = os.path.join(self.img_folder, folder, "images", item + ".jpg")
        img = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)
        image_sizes = (img.shape[0], img.shape[1])
        img = self.transform(img)
        ann = self.annotations[item]["annotations"]
        if self.split == "train":
            region_id = np.random.randint(0, len(ann))
            return img, "image of " + ann[region_id]["query"]
        out = {}
        for i in range(0, len(ann)):
            tmp = {}
            bbox = ann[i]["bbox"]
            if (bbox[0][3] - bbox[0][1]) * (bbox[0][2] - bbox[0][0]) > 0.05 * image_sizes[0] * image_sizes[1]:
                tmp["sentences"] = "image of " + ann[i]["query"]
                tmp["bbox"] = bbox
                out[str(i)] = tmp
        if self.img_path:
            return img, out, image_sizes, img_path
        return img, out, image_sizes

    def __len__(self):
        return len(self.files)

    @property
    def name(self):
        return "referit"

def get_referit_test_dataset(cfg: DictConfig):
    datadir = cfg.val_path
    transform_train, transform_test = get_flickr_transform(image_size=cfg.image_size)
    ds_test = ImageLoader(datadir, split="test", transform=transform_test)
    return ds_test

def get_referit_dataset(cfg: DictConfig, only_test=False):
    datadir = cfg.data_path
    transform_train, transform_test = get_flickr_transform(image_size=cfg.image_size)
    ds_test = ImageLoader(datadir, split="val", transform=transform_test)
    ds_train = None
    if not only_test:
        ds_train = ImageLoader(datadir, split="train", transform=transform_train)
    return ds_train, ds_test


# You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
# You may assume the two numbers do not contain any leading zero, except the number 0 itself.

from typing import Optional

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        # Returns if either or both args are missing
        if not l1:
            return l2
        if not l2:
            return l1
        # set number holders for easier val access
        ll1, ll2 = [], []
        # Run through each LinkedList to grab vals
        runner = l1
        while runner:
            ll1.append(runner.val)
            runner = runner.next
        runner = l2
        while runner:
            ll2.append(runner.val)
            runner = runner.next
        print(ll1, ll2)
        # Set longest list and math intermediate
        work = ll1 if len(ll1)>=len(ll2) else ll2
        temp = 0
        # Do addition back to front of arrays
        for i in range(-1, -len(work)-1, -1):
            # Conditional depending on each lists length
            if abs(i) > len(ll1):
                temp = ll2[i]+temp
            elif abs(i) > len(ll2):
                temp = ll1[i]+temp
            else:
                temp = ll1[i]+ll2[i]+temp
            # Once a sum is acheived add the ones digit to current spot
            work[i] = temp % 10
            # Floor Divide by ten to reove ones place
            temp = temp//10
        # If any leftover sum process it
        if temp:
            # If large then 10 process down and add to end
            while temp > 9:
                work = [temp % 10]+work[:]
                temp = temp // 10
            # add final sum digit to end
            work = [temp]+work[:]
        # Put your result into the linked list
        runner = l1
        for i in work:
            runner.next = ListNode(i)
            runner=runner.next
        return l1.next

s = Solution()
print(s.addTwoNumbers(
        ListNode(7, ListNode(2, ListNode(4, ListNode(3)))),
        ListNode(5, ListNode(6, ListNode(4)))
        ))
print(s.addTwoNumbers(
        ListNode(2, ListNode(4, ListNode(3))),
        ListNode(5, ListNode(6, ListNode(4)))
        ))
print(s.addTwoNumbers(
        ListNode(),
        ListNode()
        ))
print(s.addTwoNumbers(
        ListNode(5),
        ListNode(5)
        ))


import csv
import requests
from bs4 import BeautifulSoup
import pdb

# List of URLS
urls = [
	'aliasinfosec.com',
	'github.com',
	'news.ycombinator.com'
]

results = []

# Loop through URLs
for u in urls:

	_r = requests.get(f"https://{u}")

	# Make sure 200 OK
	if _r.status_code == 200:

		soup = BeautifulSoup(_r.text, 'html.parser')
		title = soup.find('title')

		results.append([title.text, u])

# Open a CSV file, with write attribute.
with open(f"output.csv", "w") as f:

	# Create a writer, write header.
	writer = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC)
	writer.writerow(["Title", "URL"])

	# Loop through results and write rows.
	for r in results:
		writer.writerow([r[0], r[1]])


import sys
from collections import defaultdict
from random import randint

""" zad1 """

user_number = input('podaj liczbę:\n')
user_number = int(user_number)

print("{0:b}".format(user_number))
print("{0:x}".format(user_number))
print("{0:o}".format(user_number))

""" Zad2 """

user_number = input('podaj liczbę:\n')

try:
    int(user_number)
except Exception as e:
    print('nie rzutowalne na inta')
    print(e)

try:
    float(user_number)
except Exception as e:
    print('nie rzutowalne na stringa')
    print(e)

""" zad3 """

print("Podaj liczbę")
s = sys.stdin.readline()
s = s.strip('\n')
length = len(list(s))
print(list(s))
sys.stdout.write(f"Twój tekst to:")
for each in list(s):
    if each != '0':
        sys.stdout.write(f" {each} * {10**(length-1)},")
    length -= 1

""" Zad5 """

user_text = input('podaj zdanie:\n')

user_text_list = user_text.split(" ")
print(user_text_list)
user_text_dict = defaultdict(int)

for k in user_text_list:
    user_text_dict[k] = len(k)

num = 0
key = ""
used_keys = []
while num < len(user_text_list):
    minimum = 0
    for k, v in user_text_dict.items():
        if v >= minimum and k not in used_keys:
            minimum = v
            key = k
    print(key, minimum)
    used_keys.append(key)
    num += 1

""" Zad 6 """

talk_dict = {'col1': ['Koleżanki i koledzy ', 'Z drugiej strony ', 'Podobnie ', 'Nie zapominajmy jednak, że ',
                       'W ten oto sposób ', 'Różnorakie i bogate doświadczenia ', 'Wyższe założenia ideowe, a także '
                       'Wagi i znaczenia tych problemów nie trzeba szerzej uzasadniać, ponieważ ',
                       'Troska organizacji, a szczególnie ', 'Praktyka dnia codziennego dowodzi, że '],
             'col2': ['realizacja nakreślonych zadań programowych ', 'zakres i miejsce szkolenia kadr ',
                      'stały wzrost ilości i zakres naszej aktywności ', 'aktualna struktura organizacji ',
                      'nowy model działalności organizacyjnej ', 'dalszy rozwój różnych form działalności ',
                      'stałe zabezpieczenie informacyjno programowe naszej działalności ',
                      'wzmacnianie i rozwijanie struktur ', 'konsultacja z szerokim aktywem ',
                      'rozpoczęcie powszechnej akcji kształtowania postaw '],
             'col3': ['zmusza nas do przeanalizowania ', 'spełnia istotną rolę w kształtowaniu ',
                      'wymaga sprecyzowania i określenia ', 'pomaga w przygotowaniu i realizacji ',
                      'zabezpiecza udział szerokiej grupie w kształtowaniu ', 'spełnia ważne zadania w wypracowaniu ',
                      'umożliwia w większym stopniu tworzenie ', 'powoduje docenianie wagi ',
                      'przedstawia intersującą próbę sprawdzenia ', 'pociąga za sobą proces wdrażania i unowocześniania '],
             'col4': ['istniejących warunków administracyjno-finansowych. ', 'dalszych kierunków rozwoju. '
                      'systemu powszechnego uczestnictwa. ', 'postaw uczestników wobec zadań stawianych przez organizację. ',
                      'nowych propozycji. ', 'systemu szkolenia kadry odpowiadającego potrzebom. ',
                      'kierunków postępowego wychowania. ', 'odpowiednich waruknków aktywizacji. ',
                      'modelu rozwoju. ', 'form oddziaływania. ']}

number_of_sentences = input("ile zdan chcesz zobaczyc? Podaj liczbe\n")
for _ in range(int(number_of_sentences)):
    print(f"{talk_dict['col1'][randint(0, 9)]}{talk_dict['col2'][randint(0, 9)]}{talk_dict['col3'][randint(0, 9)]}"
          f"{talk_dict['col4'][randint(0, 9)]}")


# **************************************************************************
# *
# * Authors:     J.M. De la Rosa Trevin (jmdelarosa@cnb.csic.es)
# *
# * Unidad de  Bioinformatica of Centro Nacional de Biotecnologia , CSIC
# *
# * This program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License as published by
# * the Free Software Foundation; either version 2 of the License, or
# * (at your option) any later version.
# *
# * This program is distributed in the hope that it will be useful,
# * but WITHOUT ANY WARRANTY; without even the implied warranty of
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# * GNU General Public License for more details.
# *
# * You should have received a copy of the GNU General Public License
# * along with this program; if not, write to the Free Software
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
# * 02111-1307  USA
# *
# *  All comments concerning this program package may be sent to the
# *  e-mail address 'scipion@cnb.csic.es'
# *
# **************************************************************************

import os
from os.path import join
from glob import glob
import re
from datetime import datetime

import pyworkflow.utils as pwutils
import pyworkflow.protocol.params as params
from pyworkflow.utils.path import expandPattern, copyFile, createAbsLink
from pyworkflow.em.protocol import EMProtocol

class ProtImport(EMProtocol):
    """ Base class for other all Import protocols. """

class ProtImportFiles(ProtImport):
    """ Base class for other Import protocols.
    All imports protocols will have:
    1) Several options to import from (_getImportOptions function)
    2) First option will always be "from files". (for this option
      files with a given pattern will be retrieved  and the ### will
      be used to mark an ID part from the filename.
      - For each file a function to process it will be called
        (_importFile(fileName, fileId))
    """
    IMPORT_FROM_FILES = 0

    #--------------------------- DEFINE param functions ------------------------
    def _defineParams(self, form):
        importChoices = self._getImportChoices()
        filesCondition = self._getFilesCondition()

        form.addSection(label='Import')

        if len(importChoices) > 1: # not only from files
            form.addParam('importFrom', params.EnumParam,
                          choices=importChoices, default=self._getDefaultChoice(),
                          label='Import from',
                          help='Select the type of import.')
        else:
            form.addHidden('importFrom', params.EnumParam,
                          choices=importChoices, default=self.IMPORT_FROM_FILES,
                          label='Import from',
                          help='Select the type of import.')
        form.addParam('filesPath', params.PathParam,
                      condition=filesCondition,
                      label="Files directory",
                      help="Directory with the files you want to import.\n\n"
                           "The path can also contain wildcards to select"
                           "from several folders. \n\n"
                           "Examples:\n"
                           "  ~/Particles/data/day??_micrographs/\n"
                           "Each '?' represents one unknown character\n\n"
                           "  ~/Particles/data/day*_micrographs/\n"
                           "'*' represents any number of unknown characters\n\n"
                           "  ~/Particles/data/day#_micrographs/\n"
                           "'#' represents one digit that will be used as "
                           "micrograph ID\n\n"
                           "NOTE: wildcard characters ('*', '?', '#') "
                           "cannot appear in the actual path.)")
        form.addParam('filesPattern', params.StringParam,
                      label='Pattern',
                      condition=filesCondition,
                      help="Pattern of the files to be imported.\n\n"
                           "The pattern can contain standard wildcards such as\n"
                           "*, ?, etc, or special ones like ### to mark some\n"
                           "digits in the filename as ID.\n\n"
                           "NOTE: wildcards and special characters "
                           "('*', '?', '#', ':', '%') cannot appear in the "
                           "actual path.")
        form.addParam('copyFiles', params.BooleanParam, default=False,
                      expertLevel=params.LEVEL_ADVANCED,
                      label="Copy files?",
                      help="By default the files are not copied into the "
                           "project to avoid data duplication and to save "
                           "disk space. Instead of copying, symbolic links are "
                           "created pointing to original files. This approach "
                           "has the drawback that if the project is moved to "
                           "another computer, the links need to be restored.")

        self._defineImportParams(form)

        self._defineAcquisitionParams(form)

        form.addSection('Streaming')

        form.addParam('dataStreaming', params.BooleanParam, default=False,
              label="Process data in streaming?",
              help="Select this option if you want import data as it is "
                   "generated and process on the fly by next protocols. "
                   "In this case the protocol will keep running to check "
                   "new files and will update the output Set, which can "
                   "be used right away by next steps.")

        form.addParam('timeout', params.IntParam, default=43200,
              condition='dataStreaming',
              label="Timeout (secs)",
              help="Interval of time (in seconds) after which, if no new file "
                   "is detected, the protocol will end. When finished, "
                   "the output Set will be closed and no more data will be "
                   "added to it. \n"
                    "Note 1:  The default value is  high (12 hours) to avoid "
                   "the protocol finishes during the aqcuisition of the "
                   "microscope. You can also stop it from right click and press "
                   "STOP_STREAMING.\n"
                   "Note 2: If you're using individual frames when importing "
                   "movies, the timeout won't be refreshed until a whole "
                   "movie is stacked.")

        form.addParam('fileTimeout', params.IntParam, default=30,
              condition='dataStreaming',
              label="File timeout (secs)",
              help="Interval of time (in seconds) after which, if a file has "
                   "not changed, we consider it as a new file. \n")

        self._defineBlacklistParams(form)

    def _defineImportParams(self, form):
        """ Override to add options related to the different types
        of import that are allowed by each protocol.
        """
        pass

    def _defineAcquisitionParams(self, form):
        """ Override to add options related to acquisition info.
        """
        pass

    def _defineBlacklistParams(self, form):
        """ Override to add options related to blacklist info.
        """
        pass

    def _getDefaultChoice(self):
        return  self.IMPORT_FROM_FILES

    #--------------------------- INFO functions --------------------------------
    def _validate(self):
        errors = []
        if self.importFrom == self.IMPORT_FROM_FILES:
            if not self.getPattern():
                errors.append("The path and pattern can not be both empty!!!")
            else:
                # Just check the number of files matching the pattern
                self.getMatchFiles()
                if self.numberOfFiles == 0:
                    errors.append("There are no files matching the pattern %s"
                                  % self.getPattern())

        return errors

    #--------------------------- BASE methods to be overriden ------------------
    def _getImportChoices(self):
        """ Return a list of possible choices
        from which the import can be done.
        (usually packages formas such as: xmipp3, eman2, relion...etc.
        """
        return ['files']

    def _getFilesCondition(self):
        """ Return an string representing the condition
        when to display the files path and pattern to grab
        files.
        """
        return '(importFrom == %d)' % self.IMPORT_FROM_FILES

    #--------------------------- UTILS functions -------------------------------
    def getPattern(self):
        """ Expand the pattern using environ vars or username
        and also replacing special character # by digit matching.
        """
        self._idRegex = None
        filesPath = self.filesPath.get('').strip()
        filesPattern = self.filesPattern.get('').strip()

        if filesPattern:
            fullPattern = join(filesPath, filesPattern)
        else:
            fullPattern = filesPath

        pattern = expandPattern(fullPattern.replace("$", ""))
        match = re.match('[^#]*(#+)[^#]*', pattern)

        if match is not None:
            g = match.group(1)
            n = len(g)
            # prepare regex pattern - place ids, handle *, handle ?
            idregex = pattern.replace(g, '(%s)' % ('[0-9]'*n))
            idregex = idregex.replace('*','.*')
            idregex = idregex.replace('?', '.')
            self._idRegex = re.compile(idregex)
            pattern = pattern.replace(g, '[0-9]'*n)

        return pattern

    def getMatchFiles(self, pattern=None):
        """ Return a sorted list with the paths of files that
        matched the pattern.
        """
        if pattern is None:
            pattern = self.getPattern()

        filePaths = glob(pattern)
        filePaths.sort()
        self.numberOfFiles = len(filePaths)

        return filePaths

    def getCopyOrLink(self):
        # Set a function to copyFile or createLink
        # depending in the user selected option
        if self.copyFiles:
            return copyFile
        else:
            return createAbsLink

    def fileModified(self, fileName, fileTimeout):
        """ Check if the fileName modification time is less
        than a given timeout.
        Params:
            fileName: input filename that will be checked.
            fileTimeout: timeout """
        self.debug('Checking file: %s' % fileName)
        mTime = datetime.fromtimestamp(os.path.getmtime(fileName))
        delta = datetime.now() - mTime
        self.debug('   Modification time: %s' % pwutils.prettyTime(mTime))
        self.debug('   Delta: %s' % pwutils.prettyDelta(delta))

        return delta < fileTimeout

    def isBlacklisted(self, fileName):
        """ Overwrite in subclasses """
        return False

    def iterFiles(self):
        """ Iterate through the files matched with the pattern.
        Provide the fileName and fileId.
        """
        filePaths = self.getMatchFiles()

        for fileName in filePaths:
            if self._idRegex:
                # Try to match the file id from filename
                # this is set by the user by using #### format in the pattern
                match = self._idRegex.match(fileName)
                if match is None:
                    raise Exception("File '%s' doesn't match the pattern '%s'"
                                    % (fileName, self.getPattern()))

                fileId = int(match.group(1))

            else:
                fileId = None

            yield fileName, fileId

    def worksInStreaming(self):
        # Import protocols always work in streaming
        return True


import os
import sys
import tensorflow as tf
import subprocess
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--octree", type=str, required=False,
                    default='../../octree')
parser.add_argument("--cuda", type=str, required=False,
                    default='/usr/local/cuda-10.1')
parser.add_argument('--key64', type=str, required=False,
                    default='false')
parser.add_argument('--cc', type=str, required=False,
                    default='g++')

args = parser.parse_args()
OCTREE_DIR = args.octree
CUDA_DIR = args.cuda
CC = args.cc
KEY64 = '-DKEY64' if args.key64.lower() == 'true' else ''
LIBS_DIR = os.path.dirname(os.path.realpath(__file__))

TF_CFLAGS = " ".join(tf.sysconfig.get_compile_flags())
TF_LFLAGS = " ".join(tf.sysconfig.get_link_flags())

## g++-4.8
env_gcc = 'echo using g++ '
if CC == 'g++-4.8':
  cmds = [
    'sudo apt-get update',
    'sudo apt-get install gcc-4.8 --yes',
    'sudo apt-get install g++-4.8 --yes',]
  cmd = ' && '.join(cmds)
  print(cmd)
  os.system(cmd)
  env_gcc = 'echo using g++-4.8 && export CC=gcc-4.8 && export CXX=g++-4.8 '

## build octree
octree_ext = os.path.join(OCTREE_DIR, 'external/octree-ext')
if not os.path.exists(octree_ext):
  cmd = 'git clone --recursive https://github.com/wang-ps/octree-ext.git ' + octree_ext
  print(cmd)
  os.system(cmd)

octree_build = os.path.join(OCTREE_DIR, 'build')
if os.path.exists(octree_build):
  os.system('rm -r %s' % octree_build)

os.makedirs(octree_build)
os.chdir(octree_build)
abi = 'OFF' if '-D_GLIBCXX_USE_CXX11_ABI=1' in TF_CFLAGS else 'ON'
k64 = 'OFF' if KEY64 != '-DKEY64' else 'ON'
cmd = env_gcc + '&& cmake .. -DABI=%s -DKEY64=%s && make -j all' % (abi, k64)
print(cmd)
os.system(cmd)
os.system('./octree_test')  # run the test
os.chdir(LIBS_DIR)

## build ocnn-tf
lines = []
lines.append("TF_CFLAGS := %s" % TF_CFLAGS)
lines.append("TF_LFLAGS := %s" % TF_LFLAGS)
lines.append("OCT_CFLAGS := -I%s/octree" % OCTREE_DIR)
lines.append("OCT_LFLAGS := -L%s/build -loctree_lib" % OCTREE_DIR)
lines.append("")

lines.append("NVCC_FLAGS1 := -std=c++11 -O2 -c")
lines.append("NVCC_FLAGS2 := $(TF_CFLAGS) $(OCT_CFLAGS) -I %s/include "  \
             "-x cu -Xcompiler -fPIC -D GOOGLE_CUDA=1 -I /usr/local   "  \
             "-expt-relaxed-constexpr -DNDEBUG %s" % (CUDA_DIR, KEY64))
lines.append("CC_FLAGS1 := -std=c++11 -O2")
lines.append("CC_FLAGS2 := $(TF_CFLAGS) $(OCT_CFLAGS) -I %s/include   "  \
             "-L %s/lib64 -D GOOGLE_CUDA=1 $(TF_LFLAGS) $(OCT_LFLAGS) "  \
             "-fPIC -lcudart %s" % (CUDA_DIR, CUDA_DIR, KEY64))
lines.append("")

lines.append("CC := %s" % CC)
lines.append("NVCC := %s/bin/nvcc" % CUDA_DIR)
lines.append("")

cpu_objects = []
cpu_sources = []
gpu_objects = []
gpu_sources = []
all_headers = []
for filename in sorted(os.listdir(".")):
  if filename.endswith(".cu.cc") or filename.endswith(".cu"):
    targetname = filename + ".o"
    gpu_sources.append(filename)
    gpu_objects.append(os.path.join("object", targetname))
  elif filename.endswith(".cc") or filename.endswith(".cpp"):
    targetname = filename + ".o"
    cpu_sources.append(filename)
    cpu_objects.append(os.path.join("object", targetname))
  elif filename.endswith(".h"):
    all_headers.append(filename)

lines.append("cpu_objects := %s" % " ".join(cpu_objects))
lines.append("gpu_objects := %s" % " ".join(gpu_objects))
lines.append("")

lines.append(".PHONY : all clean")
lines.append("")

lines.append("all : libocnn.so")
lines.append("")

lines.append("libocnn.so : $(cpu_objects) $(gpu_objects)")
lines.append("\t$(CC) $(CC_FLAGS1) -shared -o libocnn.so object/*.o $(CC_FLAGS2)")
lines.append("")

for i in range(len(cpu_objects)):
  dependency = b" ".join(
      subprocess.Popen("%s -std=c++11 -MM -MG %s" % (CC, cpu_sources[i]),
                       stdin=subprocess.PIPE,
                       stdout=subprocess.PIPE,
                       shell=True).stdout.readlines()).decode("utf-8")
  headers = []
  for h in all_headers:
    if dependency.find(h) > 0:
      headers.append(h)
  headers = " ".join(headers)
  lines.append("%s : %s %s" % (cpu_objects[i], headers, cpu_sources[i]))
  lines.append("\t$(CC) $(CC_FLAGS1) -c %s $(CC_FLAGS2) -o %s" % \
               (cpu_sources[i], cpu_objects[i]))
  lines.append("")

for i in range(len(gpu_objects)):
  dependency = b" ".join(
      subprocess.Popen("%s -std=c++11 -MM -MG %s" % (CC, gpu_sources[i]),
                       stdin=subprocess.PIPE,
                       stdout=subprocess.PIPE,
                       shell=True).stdout.readlines()).decode("utf-8")
  headers = []
  for h in all_headers:
    if dependency.find(h) > 0:
      headers.append(h)
  headers = " ".join(headers)
  lines.append("%s : %s %s" % (gpu_objects[i], headers, gpu_sources[i]))
  lines.append("\t$(NVCC) $(NVCC_FLAGS1) %s $(NVCC_FLAGS2) -o %s" % \
               (gpu_sources[i], gpu_objects[i]))
  lines.append("")

lines.append("clean :")
lines.append("\t rm %s" % os.path.join("object", "*.o"))
lines.append("")

lines = [line + "\n" for line in lines]
with open("Makefile", "w") as f:
  f.writelines(lines)

# make
if os.path.exists("object"):
  os.system("rm -r object")
os.mkdir("object")
os.system("make -j all")

# test
os.chdir(LIBS_DIR + "/../test")
# env variable
cmd = 'export OCTREE_KEY=' + ('64' if KEY64 == '-DKEY64' else '32')
os.system(cmd + " && python test_all.py")


#Requirements: installed ffmpeg executable (add to PATH), and ffmpeg-python module.
import ffmpeg
import os

input_file = r"G:\My Drive\WORK\3D_Work\Ants_youtube\renders\map3_trails.mp4"
speed_factor = 5

output_name = os.path.basename(input_file).split(".")[0] + "_" + str(speed_factor) + "x_speed" + ".mp4"
ouput_file = os.path.join(os.path.dirname(input_file),output_name)
stream = ffmpeg.input(input_file)
stream = ffmpeg.output(stream, ouput_file, vf=f"setpts={1/speed_factor}*PTS")
ffmpeg.run(stream)


# -*- coding: utf-8 -*-
"""
Created on Wed Jun 28 15:57:01 2023

@author: user1
"""
import pandas as pd
#from madlan_data_prep import prepare_data
from sklearn.model_selection import cross_val_score
import pickle
from sklearn.linear_model import ElasticNet
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.preprocessing import FunctionTransformer
from sklearn.linear_model import ElasticNetCV

datafile = "C:/Users/user1/Downloads/output_all_students_Train_v9.xlsx"
df = pd.read_excel(datafile)
data = prepare_data(df)

X = data.drop('price', axis=1)
y = data['price']

num_cols = [col for col in X.columns if X[col].dtypes!='O']
num_cols
cat_cols = [col for col in X.columns if (X[col].dtypes=='O')]
cat_cols

numerical_pipeline = Pipeline([
    ('numerical_imputation', SimpleImputer(strategy='median', add_indicator=False)),
    ('scaling', StandardScaler())
])

categorical_pipeline = Pipeline([
    ('categorical_imputation', SimpleImputer(strategy='constant', add_indicator=False, fill_value='missing')),
    ('one_hot_encoding', OneHotEncoder(sparse_output=False, handle_unknown='ignore'))
])

column_transformer = ColumnTransformer([
    ('numerical_preprocessing', numerical_pipeline, num_cols),
    ('categorical_preprocessing', categorical_pipeline, cat_cols)
    ], remainder='drop')

pipe_preprocessing_model = Pipeline([
    ('preprocessing_step', column_transformer),
    ('model', ElasticNet(alpha=1435.9485453543987, l1_ratio=0.5))
])

model = pipe_preprocessing_model.fit(X, y)

# שמירת המודל לקובץ PKL
with open('trained_model.pkl', 'wb') as file:
    pickle.dump(model, file)


#!/usr/bin/env /Library/Frameworks/Python.framework/Versions/3.6/bin/python3

from .......API.XMLX.XMLX import XMLX
from .......PaloAltoNetworks.PaloAltoNetworks import PaloAltoNetworks
from .......Logger.NetworkLogger.NetworkLogger import NetworkLogger as NLogger
from .......PaloAltoNetworks.Panorama.Templates.Network_Templates.Zones import Zones
from xml.etree.ElementTree import Element
# from xml.etree.ElementTree import ElementTree
import xml.etree.ElementTree as Et

# TODO: Modify the class to add the interface to Zone and Virtual Router

class TunnelInterface(PaloAltoNetworks):
	"""
	Class to configure Tunnel Interface
	"""

	def __init__(self, panorama_ip, api_key):
		# print('++++ TunnelInterface Class')
		super().__init__(panorama_ip, api_key)
		# print('---- TunnelInterface Class')

	def __str__(self):
		return self.__class__.__name__

	@staticmethod
	def __xcode():
		"""
		Method to return Tunnel Interface xpath to place in API request string

		:return: xpath (XML code)
		:rtype: str
		"""

		xpath = (
			"/config/devices/entry[@name='localhost.localdomain']/template/entry[@name='%s']"
			"/config/devices/entry[@name='localhost.localdomain']/network/interface/tunnel/units"
		)

		ixpath = (
			"/config/devices/entry[@name='localhost.localdomain']/template/entry[@name='%s']"
			"/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/import/network/interface"
		)

		return xpath, ixpath

	def configure_tunnel_interface(self, action, template_name, tunnel=None):
		"""
		Method to add TunnelInterface to Panorama

		:param action: Action - Add or Update
		:type action: str
		:param template_name: Name of template to add Tunnel Interface to
		:type template_name: str
		:param tunnel: Dictionary of all Tunnel Interface parameters
		:type tunnel: dict
		:return: None
		:rtype: None

		Example:

		tunnel_parameters = {
		'tunnel_name': 'tunnel.21', 'zone_name': 'dmz',
		'ip_address': {'ip1': '192.168.100.1/24', 'ip2': '192.168.101.1/24'},
		'interface_management_profile': 'allow-all-int-mgmt'
		}

		configure_tunnel_interface(action='add', template_name='PANW', tunnel=tunnel_parameters)

		Parameters:

		Note: All possible parameters are as below. If the parameter is not included, it will be disabled by default.

		tunnel_name (mandatory): Name of the Tunnel Interface
		zone (optional): Name of Zone to add this tunnel interface to
		virtual_router (optional): Name of the virtual router to add this tunnel interface to
		ip_address (mandatory): Dictionary of IP Addresses to be configured; example is above
		interface_management_profile (optional): Interface management profile name

		"""

		xmx = XMLX()
		xpath, ixpath = self.__xcode()

		if action == 'add':
			element_root = Element('entry')
			element_root.set('name', '%s' % tunnel.get('tunnel_name'))

			tree_ip = Element('ip')

			ip_addresses = tunnel.get('ip_address')

			for ip in ip_addresses:
				ip_root = Element('entry')
				ip_root.set('name', '%s' % ip_addresses[ip])

				tree_ip.append(ip_root)

			element_root.append(tree_ip)

			if tunnel.get('interface_management_profile') is not None:
				tree_interface_management_profile = Element('interface-management-profile')
				tree_interface_management_profile.text = tunnel.get('interface_management_profile')

				element_root.append(tree_interface_management_profile)

			element = Et.tostring(element_root).decode('UTF-8')

			try:
				uri = xmx.configure.format(self.panorama_ip, xpath % template_name, element, self.api_key)
			except Exception as e:
				NLogger.network.info('{} - Tunnel Interface: {} - {}'.format(
					template_name, tunnel.get('tunnel_name'), e)
				)
			else:
				xmx.exec_xml_get(uri, NLogger.network, 'Tunnel Interface', tunnel.get('tunnel_name'))

			# /import/network/interface path

			ielement = '<member>%s</member>' % tunnel.get('tunnel_name')

			try:
				uri = xmx.configure.format(self.panorama_ip, ixpath % template_name, ielement, self.api_key)
			except Exception as e:
				NLogger.network.info('{} - Tunnel Interface: {} - {}'.format(
					template_name, tunnel.get('tunnel_name'), e)
				)
			else:
				xmx.exec_xml_get(uri, NLogger.network, 'Tunnel Interface', tunnel.get('tunnel_name'))

			if tunnel.get('zone_name') is not None:
				zone = Zones(panorama_ip=self.panorama_ip, api_key=self.api_key)

				zone_parameters = {
					'zone_name': '%s' % tunnel.get('zone_name'),
					'interface': {'int1': '%s' % tunnel.get('tunnel_name')}
				}

				zone.configure_zone(action='update', template_name='PANW', zone=zone_parameters)

			if tunnel.get('virtual_router') is not None:
				pass


import numpy as np
import pygame

class Environment:
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    GREEN = (0, 255, 0)
    BROWN = (222, 184, 135)
    LIGHTYELLOW = (250, 235, 215)
    LIGHTGREEN = (144, 238, 144)
    ROBOT_DIAMETER = 50
    DUST_DOTS_COLOR = LIGHTGREEN
    DUST_DOT_WIDTH = 3
    PADDING = 50

    def __init__(self, width=800, height=800, obstacles=None, robot=None, pygame_enabled=False):
        """
        :param width:           Width of window
        :param height:          Height of window
        :param obstacles:       list of lists where each sublist is [x_from, x_to, y_from, y_to]
        :param robot:           Robot Object
        """

        # initialize dimension of the world
        self.width = width
        self.height = height
        self.pygame_enabled = pygame_enabled

        if self.pygame_enabled:
            pygame.init()
            pygame.font.init()
            self.myfont = pygame.font.SysFont('Comic Sans MS', 30)

            self.gameDisplay = pygame.display.set_mode((self.width, self.height))
            pygame.display.set_caption('Differential Robot Simulator')
            self.clock = pygame.time.Clock()

        # initialize robot
        self.robot = robot

        # Initialize dust
        self.dust_dots_intensity = 4
        self.dust_matrix_width = int(self.width / self.dust_dots_intensity)
        self.dust_matrix_height = int(self.height / self.dust_dots_intensity)
        self.dust_total = self.dust_matrix_width * self.dust_matrix_height

        # Zero(0) means that there is dust.
        # Minus one (-1) means that robot passed by this spot so there is not dust anymore
        self.dust_matrix = np.ones((self.dust_matrix_width, self.dust_matrix_height))

        self.dust_coverage = 1  # 100% dust coverage when we start
        self.ground_coverage = 1 - self.dust_coverage
        if self.pygame_enabled:
            self.dust_point = [[None for j in range(self.dust_matrix_width)] for i in range(self.dust_matrix_height)]

        # OBSTACLES

        if self.pygame_enabled:
            # initialize walls object (rects)
            self.obstacles_rects = []

        # obstacle coordinates, handy for wall collision
        self.obstacles_coord = obstacles

        # If no coordinates are passed, initialize empty room (with border walls)
        if self.obstacles_coord is None:
            self.obstacles_coord = [
                [0 + self.PADDING, 0 + self.PADDING, self.width - self.PADDING, 0 + self.PADDING],
                [self.width - self.PADDING, 0 + self.PADDING, self.width - self.PADDING,self.height - self.PADDING],
                [self.width - self.PADDING, self.height - self.PADDING, 0 + self.PADDING,self.height - self.PADDING],
                [0 + self.PADDING, self.height - self.PADDING, 0 + self.PADDING, 0 + self.PADDING]
            ]

        # obstacles parameters, handy for sensor values
        self.obstacles_parameters = np.zeros((len(self.obstacles_coord), 2))

        # Add obstacles
        self.add_obstacles()

    def reset(self):
        self.dust_matrix = np.ones((self.dust_matrix_width, self.dust_matrix_height))
        self.dust_coverage = 1  # 100% dust coverage when we start
        self.ground_coverage = 1 - self.dust_coverage

    def add_obstacles(self):
        # obstacles parameters
        for count, obst in enumerate(self.obstacles_coord):
            # sensors functions parameters

            # slope m
            if self.obstacles_coord[count][3] - self.obstacles_coord[count][1] == 0:
                self.obstacles_parameters[count][0] = 0
            else:
                if self.obstacles_coord[count][2] - self.obstacles_coord[count][0] == 0:
                    self.obstacles_parameters[count][0] = float('inf')
                else:
                    self.obstacles_parameters[count][0] = (self.obstacles_coord[count][3] - self.obstacles_coord[count][
                        1]) / ((self.obstacles_coord[count][2] -
                                self.obstacles_coord[count][0]))

            # intercept q
            self.obstacles_parameters[count][1] = self.obstacles_coord[count][1] - (
                    self.obstacles_parameters[count][0] * self.obstacles_coord[count][0])

            if self.pygame_enabled:
                # draw current wall and store Rect object
                curr_wall = pygame.draw.line(self.gameDisplay, self.BLACK,
                                             (self.obstacles_coord[count][0], self.obstacles_coord[count][1]),
                                             (self.obstacles_coord[count][2], self.obstacles_coord[count][3]), 5)
                self.obstacles_rects.append(curr_wall)

            # print("############################ INIT WALLS COORD + PARAMS ############################")
            # print(self.obstacles_coord)
            # print(self.obstacles_parameters)

    def reset_background(self):
        # Draw everything white
        self.gameDisplay.fill(self.WHITE)

    def calculate_dust_and_ground_coverage(self):
        dust_on_screen = np.count_nonzero(self.dust_matrix)
        self.dust_coverage = dust_on_screen / self.dust_total
        self.ground_coverage = 1 - self.dust_coverage

    def draw_dust(self):
        # By knowing the position of the robot and it's radius we can mark all of the dust point in the matrix
        # that the robot "touches"
        # But instead of checking all of the dots of the grid and their distance to the robot we just check the closest
        # ones to it by taking the position of the robot dividing by the dot intensity to bring the robot to the same
        # cartesian system as the dots and then we go -10 +10 up and down and only check this part.
        for i in range(int(self.robot.position[0]) // self.dust_dots_intensity - 10,
                       int(self.robot.position[0]) // self.dust_dots_intensity + 10, 1):
            for j in range(int(self.robot.position[1]) // self.dust_dots_intensity - 10,
                           int(self.robot.position[1]) // self.dust_dots_intensity + 10, 1):
                pythagorian_distance = np.sqrt((self.robot.position[0] - i * self.dust_dots_intensity) ** 2 + (
                        self.robot.position[1] - j * self.dust_dots_intensity) ** 2)
                if pythagorian_distance < self.robot.radius:
                    self.dust_matrix[i][j] = 0

        # Draw this dot if the dust_matrix has the value 1 and pygame is enabled
        if self.pygame_enabled:
            for i in range(self.dust_matrix_width):
                for j in range(self.dust_matrix_height):
                    if self.dust_matrix[i][j] == 1:
                        self.dust_point[i][j] = pygame.draw.circle(self.gameDisplay, self.DUST_DOTS_COLOR,
                                                                   [i * self.dust_dots_intensity,
                                                                    j * self.dust_dots_intensity], self.DUST_DOT_WIDTH)

    def draw_obstacles(self):
        for count, obst in enumerate(self.obstacles_coord):
            pygame.draw.line(self.gameDisplay, self.BLACK,
                             (self.obstacles_coord[count][0], self.obstacles_coord[count][1]),
                             (self.obstacles_coord[count][2], self.obstacles_coord[count][3]), 3)

    def draw_osd(self):
        osd_text_1 = 'Robot Velocity:'
        osd_text_2 = 'Left Wheel:{0}'.format(self.robot.left_wheel_velocity)
        osd_text_3 = 'Right Wheel:{0}'.format(self.robot.right_wheel_velocity)
        osd_text_4 = 'Theta:{0:.2f}'.format(self.robot.theta)
        osd_text_5 = 'Ground Coverage:{0:.2f}'.format(self.ground_coverage)
        osd_1 = self.myfont.render(osd_text_1, False, (0, 0, 0))
        osd_2 = self.myfont.render(osd_text_2, False, (0, 0, 0))
        osd_3 = self.myfont.render(osd_text_3, False, (0, 0, 0))
        osd_4 = self.myfont.render(osd_text_4, False, (0, 0, 0))
        osd_5 = self.myfont.render(osd_text_5, False, (0, 0, 0))
        self.gameDisplay.blit(osd_1, (20, self.height - 120))
        self.gameDisplay.blit(osd_2, (20, self.height - 100))
        self.gameDisplay.blit(osd_3, (20, self.height - 80))
        self.gameDisplay.blit(osd_4, (20, self.height - 60))
        self.gameDisplay.blit(osd_5, (20, self.height - 40))

    def draw_robot(self):
        # Draw the circle of the robot
        self.robot.robot_rect = pygame.draw.circle(self.gameDisplay, self.BLACK,
                                                   [int(self.robot.position[0]), int(self.robot.position[1])],
                                                   self.robot.radius, 3)

        # Draw the small line indicating the direction that the robot is moving
        # End_x and end_y represent where the small line should end, starting from the centre of the circle
        end_x = self.robot.radius * np.cos(2 * np.pi + self.robot.theta)
        end_y = self.robot.radius * np.sin(2 * np.pi + self.robot.theta)

        # Draw the line
        pygame.draw.line(self.gameDisplay, self.BLACK,
                         [int(self.robot.position[0]), int(self.robot.position[1])],
                         [int(self.robot.position[0] + end_x), int(self.robot.position[1] + end_y)],
                         3)

    def draw_sensors(self):
        for sensor in range(len(self.robot.sensors_values)):
            osd_sensor_text = str(round(self.robot.sensors_values[sensor]))
            osd_sensor = self.myfont.render(osd_sensor_text, False, self.BLACK)
            self.gameDisplay.blit(osd_sensor,
                                  (self.robot.sensors_coords[sensor, 2], self.robot.sensors_coords[sensor, 3]))

        # update sensors Rect obj, to update parameters value
        if len(self.robot.sensors_coords) != 0:
            updated_sensors = []
            for sensor in self.robot.sensors_coords:
                updated_sensors.append(pygame.draw.line(self.gameDisplay, self.BLACK,
                                                        [int(sensor[0]), int(sensor[1])],
                                                        [int(sensor[2]), int(sensor[3])],
                                                        3))
            self.robot.sensors_rects = updated_sensors

    def render(self):
        if self.pygame_enabled:
            self.reset_background()

            # Draw components. Ordering of draw matters for the window to look nice
            self.draw_robot()
        self.draw_dust()
        if self.pygame_enabled:
            self.draw_osd()
            self.draw_obstacles()
            self.draw_sensors()

        # Calculate Dust coverage (needed or Evolutionary Algorithm)
        self.calculate_dust_and_ground_coverage()


#!/usr/bin/python3
"""12-model_state_update_id_2
python database manipulation program
uses Sqlalchemy and some base model
to update an entry where id=2 in
table States in database hbtn_0e_6_usa.
"""
import sys
from model_state import Base, State
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

"""_summary_
1. handle argv for db connections and error reporting
2. try create engine and connect
3. create session
4. fetch city entry object data where id=2
4.1. update city name and save
5. print formated data or throw error message on failiure
   and roll back to previous data object.
6. close session
"""

if __name__ == "__main__":
    if len(sys.argv) != 4:
        print("./12-m..<username><pswd> <db_name>")
        sys.exit(1)

    name, pwd, db = sys.argv[1], sys.argv[2], sys.argv[3]

    try:
        engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'
                               .format(name, pwd, db),
                               pool_pre_ping=True)

        Session = sessionmaker(bind=engine)
        db = Session()

        Target_entry = db.query(State).filter_by(id=2).first()
        Target_entry.name = "New Mexico"
        db.commit()

    except Exception as e:
        db.rollback()
        print("something went wrong: ", e)

    finally:
        db.close()


import numpy
from betfair.constants import Side
from structlog import get_logger
from datetime import datetime
from betfair_wrapper.betfair_wrapper_api import get_api

from selection_handlers.positionFetcher import positionFetcher
from selection_handlers.priceService import priceService

class Execution(positionFetcher, priceService):
    def __init__(self, market_id, selection_id, customer_order_ref = None, strategy_id = None):
        super(Execution, self).__init__(market_id, selection_id, customer_order_ref, strategy_id)

        self.current_orders = None
        self.current_back = None
        self.current_lay = None
        self.current_size = None
        self.status = None
        self.customer_ref_id = 0

    def quote_target(self, price, size):
        pass

    def quote(self, price, size, side):
        tradable = self.ask_for_price()

        if not tradable:
            get_logger("was not able to retrieve prices", status = self.status)
            return False

        betfair_position = self.get_betfair_matches(side)
        get_logger().info("position_betfair", betfair_position=betfair_position)

        betting_size = max(size - betfair_position, 0)
        well_priced_orders = []
        well_priced_position = 0
        for order in self.unmatched_order:
            if order["price"] == price and well_priced_position < betting_size:
                well_priced_orders.append(order)
                well_priced_position += order["size"]
            else:
                cancellation_report = get_api().cancel_order(self.market_id, order["bet_id"])

        difference_position = well_priced_position - betting_size

        if difference_position >0:
            get_api().cancel_order(self.market_id, well_priced_orders[-1]["bet_id"], difference_position)

        elif difference_position<0:
            remaining_size = -difference_position
            get_logger().info("placing bet", current_price=self.current_back, current_size=self.current_size,
                              price=price, size=size)
            ref = self.generate_oder_id(self.selection_id)
            match = get_api().place_bet(price, remaining_size, side.name, self.market_id, self.selection_id,
                                        customer_order_ref = ref)
            bet_id = match["bet_id"]
            if bet_id is None:
                get_logger().info("order refused")
                return False

            self.add_order_to_db(bet_id, size, price, side.name, match["size"], match["price"], ref, "active")

            return True

    def reach_stake(self, price, size, side):
        tradable = self.ask_for_price()

        if not tradable:
            get_logger("was not able to retrieve prices", status = self.status)
            return False

        betfair_position = self.get_betfair_matches(side)
        get_logger().info("position_betfair", betfair_position=betfair_position)

        betting_size = max(size - betfair_position, 0)
        well_priced_orders = []
        well_priced_position = 0
        for order in self.unmatched_order:
            if order["price"] == price and well_priced_position < betting_size:
                well_priced_orders.append(order)
                well_priced_position += order["size"]
            else:
                get_api().cancel_order(self.market_id, order["bet_id"])

        difference_position = well_priced_position - betting_size

        if difference_position >0:
            get_api().cancel_order(self.market_id, well_priced_orders[-1].bet_id, difference_position)

        elif difference_position<0:
            remaining_size = -difference_position
            get_logger().info("placing bet", current_price=self.current_back, current_size=self.current_size,
                              price=price, size=size)
            ref = self.generate_oder_id(self.selection_id)
            match = get_api().place_bet(price, remaining_size, side, self.market_id, self.selection_id,
                                        customer_order_ref=ref)
            bet_id = match["bet_id"]
            if bet_id is None:
                get_logger().info("order refused")
                return False

            self.add_order_to_db(bet_id, size, price, side, match["size"], match["price"], ref, "active")

            return True

    def place_order(self, price, size, side):
        ref = self.generate_oder_id(self.selection_id)
        match = get_api().place_bet(price, size, side, self.market_id, self.selection_id,
                                    customer_order_ref=ref)
        bet_id = match["bet_id"]
        if bet_id is None:
            get_logger().info("order refused")
            return False

        self.add_order_to_db(bet_id, size, price, side, match["size"], match["price"], ref, "active")

    def reach_exposure(self, exposure):
        unhedged_pos = self.compute_unhedged_position()

    def cashout(self, percentage = 1.0):
        unhedged_pos = self.compute_unhedged_position()
        self.ask_for_price()
        if unhedged_pos > 0:
            lay_hedge = unhedged_pos / self.current_lay
            lay_hedge = round(lay_hedge, 2)
            self.place_order(self.current_lay, lay_hedge, Side.LAY)
        elif unhedged_pos < 0:
            back_hedge = - unhedged_pos / self.current_back
            back_hedge = round(back_hedge, 2)
            self.place_order(self.current_back, back_hedge, Side.BACK)
        if percentage == 1.0:
            unhedged_pos = self.compute_unhedged_position()
            if numpy.abs(unhedged_pos) > 0.2:
                self.cancel_all_pending_orders()
                self.cashout()

    def cancel_all_pending_orders(self):
        self.get_betfair_matches()
        for order in self.unmatched_order:
            get_api().cancel_order(self.market_id, order["bet_id"])

    def compute_already_executed(self):
        sum = 0
        for match in self.matches:
            sum += match["size"]
        return sum

    def generate_oder_id(self, selection_id):
        time = datetime.now().strftime("%y%m%d%H%M%S")
        if self.customer_ref is None:
            return None
        ref = self.customer_ref + "_" + str(self.customer_ref_id) + str(selection_id) + time
        self.customer_ref_id =self.customer_ref_id +1
        return ref


import pygame
from cons import *
import random

class Plane:
    def __init__(self, x, y, image=pygame.image.load(r'C:\Users\hipaa\OneDrive\Pictures\hero_plane.png')):
        self.image = image
        self.x = x
        self.y = y
        self.direction = 5

    def blit(self, screen):
        screen.blit(self.image, (self.x, self.y))
        self.move()

    def move(self):
        if self.direction == UP:
            self.y -= 15
            if self.y < 0:
                self.y = 0
        elif self.direction == DOWN:
            self.y += 15
            if self.y > 800-97:
                self.y = 800-97
        elif self.direction == LEFT:
            self.x -= 15
            if self.x < 0:
                self.x = 0
        elif self.direction == RIGHT:
            self.x += 15
            if self.x > 480-97:
                self.x = 480-97

class Bullet:
    def __init__(self, plane, image=pygame.image.load(r'D:\Users\hipaa\Desktop\一些文件\打飞机游戏\素材\15465750502243.png')):
        self.x = plane.x + 97//2-1
        self.y = plane.y
        self.image = image

    def fly(self):
        self.y -= 35

    def blit(self, screen):
        screen.blit(self.image, (self.x, self.y))
        self.fly()


from flask import Flask
from flask_environments import Environments
from flask.ext.sqlalchemy import SQLAlchemy
from flask_restful import Api
from cbibs_api.reverse_proxy import ReverseProxied
import os

app = Flask(__name__)
app.wsgi_app = ReverseProxied(app.wsgi_app)

env = Environments(app)

env.from_yaml('config.yml')
if os.path.exists('config.local.yml'):
    env.from_yaml('config.local.yml')

if app.config['LOGGING'] == True:
    import logging
    logger = logging.getLogger('pyprojects.app')
    logger.setLevel(logging.DEBUG)

    log_directory = app.config['LOG_FILE_PATH']
    log_filename = os.path.join(log_directory,app.config['LOG_FILE'])
    if not os.path.exists(os.path.dirname(log_filename)):
        os.makedirs(os.path.dirname(log_filename))
    file_handler = logging.FileHandler(log_filename, mode='a+')

    stream_handler = logging.StreamHandler()
    formatter = logging.Formatter('%(asctime)s - %(process)d - %(name)s - %(module)s:%(lineno)d - %(levelname)s - %(message)s')
    file_handler.setFormatter(formatter)
    stream_handler.setFormatter(formatter)
    app.logger.addHandler(file_handler)
    #app.logger.addHandler(stream_handler)
    app.logger.setLevel(logging.DEBUG)
    app.logger.info('Application Process Started')

api = Api(app)
db = SQLAlchemy(app)


#!/usr/bin/env python

import apache_beam
import unittest

from sfm import CreatePipeline
from sfm import SetPipelineOptions

class TestCreatePipeline(unittest.TestCase):
    def setUp(self):
        return None

    def test_pipeline_create(self):
        pipeline = CreatePipeline(options=None)
        # bacon = Bacon(pipeline.pipeline)
        # print(bacon)
        self.assertIsInstance(pipeline, apache_beam.Pipeline)

    def test_pipeline_options(self):
        spo = SetPipelineOptions()
        google_cloud = spo.config.get('google_cloud')
        spo.options = spo.set_pipeline()
        spo.set_google_cloud_options(google_cloud, spo.options)
        options = spo.set_runner(spo.options, spo.config.get('standard').get('runner'))
        pipeline = CreatePipeline(options=options)
        self.assertIsInstance(pipeline, apache_beam.Pipeline)


from rest_framework.permissions import BasePermission

class SVIPPermission(BasePermission):
    message = "must be VIP"
    def has_permission(self, request, view):
        try:
            if request.user.user_type != 3:
                return False
            return True
        except Exception as e:
            print("permission error>>>>>>>",e)
            return False

class GeneralPermission(BasePermission):
    def has_permission(self, request, view):
        if request.user.user_type == 3:
            return False
        return True