import os

ALPACA_KEY_ID = os.getenv('ALPACA_KEY_ID')
ALPACA_SECRET_KEY = os.getenv('ALPACA_SECRET_KEY')
HEADERS = {'APCA-API-KEY-ID': ALPACA_KEY_ID, 'APCA-API-SECRET-KEY': ALPACA_SECRET_KEY}
ALPACA_ENDPOINT = 'https://paper-api.alpaca.markets'

import alpaca_trade_api as tradeapi

# from .models import Positions
# from .models import Account

client = tradeapi.REST(ALPACA_KEY_ID, ALPACA_SECRET_KEY, base_url=ALPACA_ENDPOINT, api_version='v2')

def get_portfolio():
	account = client.get_account()
	# print(account, account.status)
	return account

def get_positions():
	return client.list_positions()

def get_name(symbol):
	return client.get_asset(symbol.upper()).name

def get_asset_info(symbol):
	symbol_data = client.get_asset(symbol.upper())
	# print(symbol_data, symbol_data_month)
	asset_info = {
	    'name': symbol_data.name,
	    'symbol': symbol_data.symbol,
	    'status': symbol_data.status,
		'class': 'us_equity',
		'exchange': symbol_data.exchange,
	    'easy to borrow': symbol_data.easy_to_borrow,
	    'fractionable': symbol_data.fractionable,
	    'id': symbol_data.id,
	    'marginable': symbol_data.marginable,
	    'shortable': symbol_data.shortable,
	    'tradable': symbol_data.tradable
	}
	return asset_info

def get_symbol_dataframe(symbol):
	df = populate_historical(symbol, "1Min", limit=10, end=client.get_clock().timestamp)
	return df

def validate_symbol(symbol):
	try:
		symbol = client.get_asset(symbol)
		return True
	except:
		return False
def get_minute_update(symbol):
	minute_update = populate_historical(symbol, '1Min', 1, end=client.get_clock().timestamp)[symbol][0]
	minute_update_object = {
		'timestamp': minute_update.t.strftime('%Y-%m-%d %H:%M:%S'),
		'open': minute_update.o,
		'close': minute_update.c,
		'high': minute_update.h,
		'low': minute_update.l,
		'volume': minute_update.v

	}
	return minute_update_object

def return_df(alpaca_entity):
	return alpaca_entity.df

def populate_historical(symbol, timeframe="day", limit=30, start=None, end=None, after=None, until=None):

	symbol = symbol.upper()
	name = get_name(symbol)
	limit = limit
	timeframe = timeframe

	return client.get_barset(symbol, timeframe, limit)

	# postition = Positions(name=name, symbol=symbol)
	# return df

def market_status():
	return client.get_clock().is_open == True

def submit_order(symbol, qty, side, type, time_in_force='day'):
	print(f'{symbol} {side} {qty} {type} {time_in_force}')
	try:
		# client.submit_order(symbol.upper(), qty, side, type, time_in_force)
		return True
	except:
		return False


import pandas as pd
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import *
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.externals import joblib
from sklearn.metrics import mean_absolute_error

# Disable some useless pandas warnings to prevent some junk from showing up in the output window
pd.options.mode.chained_assignment = None

# Load our data set
df = pd.read_csv("house_data.csv")

# Create the X and y arrays
X = df[["sq_feet", "num_bedrooms", "num_bathrooms"]]
y = df[["sale_price"]]

# Data needs to be scaled to  0 to 1 for the neural network to train correctly.
X_scaler = MinMaxScaler(feature_range=(0, 1))
y_scaler = MinMaxScaler(feature_range=(0, 1))

# Scale both the training inputs and outputs
X[X.columns] = X_scaler.fit_transform(X[X.columns])
y[y.columns] = y_scaler.fit_transform(y[y.columns])

# Convert the inputs and outputs to numpy format so TensorFlow doesn't complain
X = X.to_numpy()
y = y.to_numpy()

# Split the data set in a training set (75%) and a test set (25%)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)

# Create a Neural Network model
model = Sequential()
model.add(Dense(50, input_dim=3, activation='relu'))
model.add(Dense(100, activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(1, activation='linear'))
model.compile(
    loss='mean_squared_error',
    optimizer='SGD'
)

# Train the model
model.fit(
    X_train,
    y_train,
    epochs=50,
    batch_size=8,
    shuffle=True,
    verbose=2
)

# Save the scalers to files so we can use it to pre-process new data later
joblib.dump(X_scaler, "X_scaler.pkl")
joblib.dump(y_scaler, "y_scaler.pkl")

# Save the trained model to a file so we can use it to make predictions later
model.save("house_value_model.h5")

# Report how well the model is performing
print("Model training results:")

# Report mean absolute error on the training set in a value scaled back to dollars so it's easier to understand.
predictions_train = model.predict(X_train, verbose=0)

mse_train = mean_absolute_error(
    y_scaler.inverse_transform(predictions_train),
    y_scaler.inverse_transform(y_train)
)
print(f" - Training Set Error: {mse_train}")

# Report mean absolute error on the test set in a value scaled back to dollars so it's easier to understand.
predictions_test = model.predict(X_test, verbose=0)

mse_test = mean_absolute_error(
    y_scaler.inverse_transform(predictions_test),
    y_scaler.inverse_transform(y_test)
)
print(f" - Test Set Error: {mse_test}")


import openpyxl

path = "/home/sheetal/PycharmProjects/Selenium_Basics/Resources/ExcelFile/testing.xlsx"
workbook = openpyxl.load_workbook(path)
sheet = workbook.active
rows = sheet.max_row
cols = sheet.max_column
print("Number of Rows", rows)
print("Number of Column", cols)
print()
for r in range(1, rows + 1):
    for c in range(1, cols + 1):
        print(sheet.cell(row=r, column=c).value, end="  ")
    print()

# To Write data into excel file
for r in range(1, rows + 1):
    for c in range(1, cols + 1):
        sheet.cell(row=r, column=c).value = "Hello"

workbook.save(path)


#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import numpy as np
import matplotlib.pyplot as plt
import sys

try: fname = sys.argv[1]
except IndexError: exit() #fname = ['mag.dat']

try: tag = sys.argv[2]
except IndexError: tag = 'dfct'

#fname = '/tmp/OUTs/simple1_l2/nv0_d0.0_alpha0.0/e0.0/'
ban = fname + tag + '.bands'
dos = fname + tag + '.dos'
bas = fname + tag + '.basis'
ind,nat = np.loadtxt(bas,usecols=(0,1),dtype=int,unpack=True)
ats,orbs,sub = np.loadtxt(bas,usecols=(2,3,4),dtype=bytes,unpack=True)
ats = np.array([str(x,'utf-8') for x in ats])
orbs = np.array([str(x,'utf-8') for x in orbs])
sub = np.array([str(x,'utf-8') for x in sub])

#Xdos,Ydos = np.loadtxt(dos,unpack=True)
print(dos)
M = np.loadtxt(dos,unpack=True)
Mm = M[1:][orbs=='pz']
Xdos = M[0]
Ydos = np.sum(M[1:],axis=0)
Yesp = np.sum(Mm,axis=0)
Xban,Yban,Zban = np.loadtxt(ban,unpack=True)

print('-- Bands ----')
for x,y,z in zip(Xban,Yban,Zban):
   print(x,y,z)
print('\n-- DOS ----')
for x,y,ys in zip(Xdos,Ydos,Yesp):
   print(x,y,ys)

from matplotlib import gridspec

fig = plt.figure()
gs = gridspec.GridSpec(1, 2)
fig.subplots_adjust(wspace=0.,hspace=0.1)
ax1 = plt.subplot(gs[0,0])
ax2 = plt.subplot(gs[0,1],sharey=ax1)
## Bands
ax1.scatter(Xban,Yban,c='b',edgecolor='none')
#ax1.scatter(Xban,Yban,c=Zban,edgecolor='none')
ax1.set_xlim([min(Xban),max(Xban)])
ax1.set_ylim([-10,10])
ax1.set_xticks([])
ax1.set_xlabel('K-Path')
ax1.set_ylabel('$E$ $(eV)$',fontsize=17)
## DOS
ax2.plot(Ydos,Xdos,'b-',lw=2,label='$DOS$')
ax2.plot(Yesp,Xdos,'r-',lw=2,label='$DOS_s$')
ax2.axvspan(0,0.01, alpha=0.5, color='k')
ax2.set_xlim([0,1.75])
ax2.set_xlabel('$DOS$ $(a.u.)$',fontsize=17)

ax2.grid()
ax2.legend(loc=4)

plt.show()


"""
Cement logging extension module.
"""

import os
import logging
from ..core import log
from ..utils.misc import is_true, minimal_logger
from ..utils import fs

LOG = minimal_logger(__name__)

try:                                        # pragma: no cover
    NullHandler = logging.NullHandler       # pragma: no cover
except AttributeError:                      # pragma: no cover
    # Not supported on Python < 3.1/2.7     # pragma: no cover
    class NullHandler(logging.Handler):     # pragma: no cover

        def handle(self, record):           # pragma: no cover
            pass                            # pragma: no cover
            # pragma: no cover

        def emit(self, record):             # pragma: no cover
            pass                            # pragma: no cover
            # pragma: no cover

        def createLock(self):               # pragma: no cover
            self.lock = None                # pragma: no cover

class LoggingLogHandler(log.LogHandler):

    """
    This class is an implementation of the :ref:`Log <cement.core.log>`
    interface, and sets up the logging facility using the standard Python
    `logging <http://docs.python.org/library/logging.html>`_ module.

    """

    class Meta:

        """Handler meta-data."""

        #: The string identifier of this handler.
        label = 'logging'

        #: The logging namespace.
        #:
        #: Note: Although Meta.namespace defaults to None, Cement will set
        #: this to the application label (App.Meta.label) if not set
        #: during setup.
        namespace = None

        #: Class to use as the formatter
        formatter_class = logging.Formatter

        #: The logging format for the file logger.
        file_format = "%(asctime)s (%(levelname)s) %(namespace)s : " + \
                      "%(message)s"

        #: The logging format for the consoler logger.
        console_format = "%(levelname)s: %(message)s"

        #: The logging format for both file and console if ``debug==True``.
        debug_format = "%(asctime)s (%(levelname)s) %(namespace)s : " + \
                       "%(message)s"

        #: List of logger namespaces to clear.  Useful when imported software
        #: also sets up logging and you end up with duplicate log entries.
        #:
        #: Changes in Cement 2.1.3.  Previous versions only supported
        #: `clear_loggers` as a boolean, but did fully support clearing
        #: non-app logging namespaces.
        clear_loggers = []

        #: The default configuration dictionary to populate the ``log``
        #: section.
        config_defaults = dict(
            file=None,
            level='INFO',
            to_console=True,
            rotate=False,
            max_bytes=512000,
            max_files=4,
        )

        #: List of arguments to use for the cli options
        #: (ex: [``-l``, ``--list``]).  If a log-level argument is not wanted,
        #: set to ``None`` (default).
        log_level_argument = None

        #: The help description for the log level argument
        log_level_argument_help = 'logging level'

    levels = ['INFO', 'WARNING', 'ERROR', 'DEBUG', 'FATAL']

    def __init__(self, *args, **kw):
        super(LoggingLogHandler, self).__init__(*args, **kw)
        self.app = None

    def _setup(self, app_obj):
        super(LoggingLogHandler, self)._setup(app_obj)
        if self._meta.namespace is None:
            self._meta.namespace = "%s" % self.app._meta.label

        self.backend = logging.getLogger("cement:app:%s" %
                                         self._meta.namespace)

        # hack for application debugging
        if is_true(self.app._meta.debug):
            self.app.config.set(self._meta.config_section, 'level', 'DEBUG')

        level = self.app.config.get(self._meta.config_section, 'level')
        self.set_level(level)

        LOG.debug("logging initialized for '%s' using %s" %
                  (self._meta.namespace, self.__class__.__name__))

    def set_level(self, level):
        """
        Set the log level.  Must be one of the log levels configured in
        self.levels which are
        ``['INFO', 'WARNING', 'ERROR', 'DEBUG', 'FATAL']``.

        :param level: The log level to set.

        """
        self.clear_loggers(self._meta.namespace)
        for namespace in self._meta.clear_loggers:
            self.clear_loggers(namespace)

        level = level.upper()
        if level not in self.levels:
            level = 'INFO'
        level = getattr(logging, level.upper())

        self.backend.setLevel(level)

        # console
        self._setup_console_log()

        # file
        self._setup_file_log()

    def get_level(self):
        """Returns the current log level."""
        return logging.getLevelName(self.backend.level)

    def clear_loggers(self, namespace):
        """Clear any previously configured loggers for ``namespace``."""

        for i in logging.getLogger("cement:app:%s" % namespace).handlers:
            logging.getLogger("cement:app:%s" % namespace).removeHandler(i)

        self.backend = logging.getLogger("cement:app:%s" % namespace)

    def _get_console_format(self):
        if self.get_level() == logging.getLevelName(logging.DEBUG):
            format = self._meta.debug_format
        else:
            format = self._meta.console_format

        return format

    def _get_file_format(self):
        if self.get_level() == logging.getLevelName(logging.DEBUG):
            format = self._meta.debug_format
        else:
            format = self._meta.file_format

        return format

    def _get_file_formatter(self, format):
        return self._meta.formatter_class(format)

    def _get_console_formatter(self, format):
        return self._meta.formatter_class(format)

    def _setup_console_log(self):
        """Add a console log handler."""
        namespace = self._meta.namespace
        to_console = self.app.config.get(self._meta.config_section,
                                         'to_console')
        if is_true(to_console):
            console_handler = logging.StreamHandler()
            format = self._get_console_format()
            formatter = self._get_console_formatter(format)
            console_handler.setFormatter(formatter)
            console_handler.setLevel(getattr(logging, self.get_level()))
        else:
            console_handler = NullHandler()

        # FIXME: self._clear_loggers() should be preventing this but its not!
        for i in logging.getLogger("cement:app:%s" % namespace).handlers:
            if isinstance(i, logging.StreamHandler):
                self.backend.removeHandler(i)

        self.backend.addHandler(console_handler)

    def _setup_file_log(self):
        """Add a file log handler."""

        namespace = self._meta.namespace
        file_path = self.app.config.get(self._meta.config_section, 'file')
        rotate = self.app.config.get(self._meta.config_section, 'rotate')
        max_bytes = self.app.config.get(self._meta.config_section,
                                        'max_bytes')
        max_files = self.app.config.get(self._meta.config_section,
                                        'max_files')
        if file_path:
            file_path = fs.abspath(file_path)
            log_dir = os.path.dirname(file_path)
            if not os.path.exists(log_dir):
                os.makedirs(log_dir)

            if rotate:
                from logging.handlers import RotatingFileHandler
                file_handler = RotatingFileHandler(
                    file_path,
                    maxBytes=int(max_bytes),
                    backupCount=int(max_files),
                )
            else:
                from logging import FileHandler
                file_handler = FileHandler(file_path)

            format = self._get_file_format()
            formatter = self._get_file_formatter(format)
            file_handler.setFormatter(formatter)
            file_handler.setLevel(getattr(logging, self.get_level()))
        else:
            file_handler = NullHandler()

        # FIXME: self._clear_loggers() should be preventing this but its not!
        for i in logging.getLogger("cement:app:%s" % namespace).handlers:
            if isinstance(i, file_handler.__class__):   # pragma: nocover
                self.backend.removeHandler(i)           # pragma: nocover

        self.backend.addHandler(file_handler)

    def _get_logging_kwargs(self, namespace, **kw):
        if namespace is None:
            namespace = self._meta.namespace

        if 'extra' in kw.keys() and 'namespace' in kw['extra'].keys():
            pass
        elif 'extra' in kw.keys() and 'namespace' not in kw['extra'].keys():
            kw['extra']['namespace'] = namespace
        else:
            kw['extra'] = dict(namespace=namespace)

        return kw

    def info(self, msg, namespace=None, **kw):
        """
        Log to the INFO facility.

        Args:
            msg (str): The message to log.

        Keyword Args:
            namespace (str): A log prefix, generally the module ``__name__``
                that the log is coming from.  Will default to
                ``self._meta.namespace`` if none is passed.

        Other Parameters:
            kwargs: Keyword arguments are passed on to the backend logging
                system.

        """
        kwargs = self._get_logging_kwargs(namespace, **kw)
        self.backend.info(msg, **kwargs)

    def warning(self, msg, namespace=None, **kw):
        """
        Log to the WARNING facility.

        Args:
            msg (str): The message to log.

        Keyword Args:
            namespace (str): A log prefix, generally the module ``__name__``
                that the log is coming from.  Will default to
                ``self._meta.namespace`` if none is passed.

        Other Parameters:
            kwargs: Keyword arguments are passed on to the backend logging
                system.

        """
        kwargs = self._get_logging_kwargs(namespace, **kw)
        self.backend.warning(msg, **kwargs)

    def error(self, msg, namespace=None, **kw):
        """
        Log to the ERROR facility.

        :Args:
            msg (str): The message to log.

        Keyword Args:
            namespace (str): A log prefix, generally the module ``__name__``
                that the log is coming from.  Will default to
                ``self._meta.namespace`` if none is passed.

        Other Parameters:
            kwargs: Keyword arguments are passed on to the backend logging
                system.

        """
        kwargs = self._get_logging_kwargs(namespace, **kw)
        self.backend.error(msg, **kwargs)

    def fatal(self, msg, namespace=None, **kw):
        """
        Log to the FATAL (aka CRITICAL) facility.

        Args:
            msg (str): The message to log.

        Keyword Args:
            namespace (str): A log prefix, generally the module ``__name__``
                that the log is coming from.  Will default to
                ``self._meta.namespace`` if none is passed.

        Other Parameters:
            kwargs: Keyword arguments are passed on to the backend logging
                system.

        """
        kwargs = self._get_logging_kwargs(namespace, **kw)
        self.backend.fatal(msg, **kwargs)

    def debug(self, msg, namespace=None, **kw):
        """
        Log to the DEBUG facility.

        Args:
            msg (str): The message to log.

        Keyword Args:
            namespace (str): A log prefix, generally the module ``__name__``
                that the log is coming from.  Will default to
                ``self._meta.namespace`` if none is passed.

        Other Parameters:
            kwargs: Keyword arguments are passed on to the backend logging
                system.

        """
        kwargs = self._get_logging_kwargs(namespace, **kw)
        self.backend.debug(msg, **kwargs)

def add_logging_arguments(app):
    if app.log._meta.log_level_argument is not None:
        app.args.add_argument(*app.log._meta.log_level_argument,
                              dest='log_logging_level',
                              help=app.log._meta.log_level_argument_help,
                              choices=[x.lower() for x in app.log.levels])

def handle_logging_arguments(app):
    if hasattr(app.pargs, 'log_logging_level'):
        if app.pargs.log_logging_level is not None:
            app.log.set_level(app.pargs.log_logging_level)
        if app.pargs.log_logging_level in ['debug', 'DEBUG']:
            app._meta.debug = True

def load(app):
    app.handler.register(LoggingLogHandler)
    app.hook.register('pre_argument_parsing', add_logging_arguments)
    app.hook.register('post_argument_parsing', handle_logging_arguments)


load(
    "@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl",
    "action_config",
    "artifact_name_pattern",
    "env_entry",
    "env_set",
    "feature",
    "feature_set",
    "flag_group",
    "flag_set",
    "make_variable",
    "tool",
    "tool_path",
    "variable_with_value",
    "with_feature_set",
)
load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES")

def _impl(ctx):
    objcopy_embed_data_action = action_config(
        action_name = "objcopy_embed_data",
        enabled = True,
        tools = [tool(path = "root/x86_64-linux-gnu/bin/objcopy")],
    )

    fortran_feature = feature(
        name = "fortran",
        enabled = True,
    )

    fortran_compile_action = action_config(
        action_name = "fortran_compile",
        enabled = True,
        tools = [tool(path = "root/bin/gfortran")],
    )

    action_configs = [
        objcopy_embed_data_action,
        fortran_compile_action,
    ]

    default_compile_flags_feature = feature(
        name = "default_compile_flags",
        enabled = True,
        flag_sets = [
            flag_set(
                actions = [
                    ACTION_NAMES.assemble,
                    ACTION_NAMES.preprocess_assemble,
                    ACTION_NAMES.linkstamp_compile,
                    ACTION_NAMES.c_compile,
                    ACTION_NAMES.cpp_compile,
                    ACTION_NAMES.cpp_header_parsing,
                    ACTION_NAMES.cpp_module_compile,
                    ACTION_NAMES.cpp_module_codegen,
                    ACTION_NAMES.lto_backend,
                    ACTION_NAMES.clif_match,
                ],
                flag_groups = [
                    flag_group(
                        flags = [
                            "-Wall",
                            "-Wunused-but-set-parameter",
                            "-Wno-free-nonheap-object",
                            "-fno-omit-frame-pointer",
                        ],
                    ),
                ],
            ),
            flag_set(
                actions = [
                    ACTION_NAMES.assemble,
                    ACTION_NAMES.preprocess_assemble,
                    ACTION_NAMES.linkstamp_compile,
                    ACTION_NAMES.c_compile,
                    ACTION_NAMES.cpp_compile,
                    ACTION_NAMES.cpp_header_parsing,
                    ACTION_NAMES.cpp_module_compile,
                    ACTION_NAMES.cpp_module_codegen,
                    ACTION_NAMES.lto_backend,
                    ACTION_NAMES.clif_match,
                ],
                flag_groups = [flag_group(flags = ["-g"])],
                with_features = [with_feature_set(features = ["dbg"])],
            ),
            flag_set(
                actions = [
                    ACTION_NAMES.assemble,
                    ACTION_NAMES.preprocess_assemble,
                    ACTION_NAMES.linkstamp_compile,
                    ACTION_NAMES.c_compile,
                    ACTION_NAMES.cpp_compile,
                    ACTION_NAMES.cpp_header_parsing,
                    ACTION_NAMES.cpp_module_compile,
                    ACTION_NAMES.cpp_module_codegen,
                    ACTION_NAMES.lto_backend,
                    ACTION_NAMES.clif_match,
                ],
                flag_groups = [
                    flag_group(
                        flags = [
                            "-g",
                            "-O2",
                            "-DNDEBUG",
                            "-ffunction-sections",
                            "-fdata-sections",
                        ],
                    ),
                ],
                with_features = [with_feature_set(features = ["opt"])],
            ),
        ],
    )

    cc_std_feature = feature(
        name = "cc_std_feature",
        enabled = ctx.attr.compiler != "cuda",
        flag_sets = [
            flag_set(
                actions = [
                    ACTION_NAMES.linkstamp_compile,
                    ACTION_NAMES.cpp_compile,
                    ACTION_NAMES.cpp_header_parsing,
                    ACTION_NAMES.cpp_module_compile,
                    ACTION_NAMES.cpp_module_codegen,
                    ACTION_NAMES.lto_backend,
                    ACTION_NAMES.clif_match,
                ],
                flag_groups = [flag_group(flags = ["-std=gnu++17"])],
            ),
        ],
    )

    fdo_optimize_feature = feature(
        name = "fdo_optimize",
        flag_sets = [
            flag_set(
                actions = [ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile],
                flag_groups = [
                    flag_group(
                        flags = [
                            "-fprofile-use=%{fdo_profile_path}",
                            "-fprofile-correction",
                        ],
                        expand_if_available = "fdo_profile_path",
                    ),
                ],
            ),
        ],
        provides = ["profile"],
    )

    supports_start_end_lib_feature = feature(name = "supports_start_end_lib", enabled = True)

    per_object_debug_info_feature = feature(
        name = "per_object_debug_info",
        enabled = True,
        flag_sets = [
            flag_set(
                actions = [
                    ACTION_NAMES.c_compile,
                    ACTION_NAMES.cpp_compile,
                    ACTION_NAMES.cpp_module_codegen,
                    ACTION_NAMES.assemble,
                    ACTION_NAMES.preprocess_assemble,
                    ACTION_NAMES.lto_backend,
                ],
                flag_groups = [
                    flag_group(
                        flags = ["-gsplit-dwarf"],
                        expand_if_available = "is_using_fission",
                    ),
                ],
            ),
        ],
    )

    objcopy_embed_flags_feature = feature(
        name = "objcopy_embed_flags",
        enabled = True,
        flag_sets = [
            flag_set(
                actions = ["objcopy_embed_data"],
                flag_groups = [flag_group(flags = ["-I", "binary"])],
            ),
        ],
    )

    opt_feature = feature(name = "opt")

    all_link_actions = [
        ACTION_NAMES.cpp_link_executable,
        ACTION_NAMES.cpp_link_dynamic_library,
        ACTION_NAMES.cpp_link_nodeps_dynamic_library,
    ]
    default_link_flags_feature = feature(
        name = "default_link_flags",
        enabled = True,
        flag_sets = [
            flag_set(
                actions = all_link_actions,
                flag_groups = [
                    flag_group(
                        flags = [
                            "-fuse-ld=gold",
                            "-pass-exit-codes",
                            "-Wl,--build-id",
                            "-Wl,--hash-style=gnu",
                            "-lm",
                            "-lstdc++",
                        ],
                    ),
                ],
            ),
            flag_set(
                actions = all_link_actions,
                flag_groups = [flag_group(flags = ["-Wl,--gc-sections"])],
                with_features = [with_feature_set(features = ["opt"])],
            ),
        ],
    )

    dynamic_interpreter_feature = feature(
        name = "dynamic_interpreter",
        enabled = True,
        flag_sets = [
            flag_set(
                actions = [
                    ACTION_NAMES.cpp_link_executable,
                    ACTION_NAMES.cc_flags_make_variable,
                ],
                flag_groups = [
                    flag_group(
                        flags = ["-Wl,-I" + ctx.attr.rtld],
                    ),
                ],
            ),
        ],
    )

    supports_pic_feature = feature(name = "supports_pic", enabled = True)

    user_compile_flags_feature = feature(
        name = "user_compile_flags",
        enabled = True,
        flag_sets = [
            flag_set(
                actions = [
                    ACTION_NAMES.assemble,
                    ACTION_NAMES.preprocess_assemble,
                    ACTION_NAMES.linkstamp_compile,
                    ACTION_NAMES.c_compile,
                    ACTION_NAMES.cpp_compile,
                    ACTION_NAMES.cpp_header_parsing,
                    ACTION_NAMES.cpp_module_compile,
                    ACTION_NAMES.cpp_module_codegen,
                    ACTION_NAMES.lto_backend,
                    ACTION_NAMES.clif_match,
                ],
                flag_groups = [
                    flag_group(
                        flags = ["%{user_compile_flags}"],
                        iterate_over = "user_compile_flags",
                        expand_if_available = "user_compile_flags",
                    ),
                ],
            ),
        ],
    )

    unfiltered_compile_flags_feature = feature(
        name = "unfiltered_compile_flags",
        enabled = True,
        flag_sets = [
            flag_set(
                actions = [
                    ACTION_NAMES.assemble,
                    ACTION_NAMES.preprocess_assemble,
                    ACTION_NAMES.linkstamp_compile,
                    ACTION_NAMES.c_compile,
                    ACTION_NAMES.cpp_compile,
                    ACTION_NAMES.cpp_header_parsing,
                    ACTION_NAMES.cpp_module_compile,
                    ACTION_NAMES.cpp_module_codegen,
                    ACTION_NAMES.lto_backend,
                    ACTION_NAMES.clif_match,
                ],
                flag_groups = [
                    flag_group(
                        flags = [
                            "-no-canonical-prefixes",
                            "-fno-canonical-system-headers",
                            "-Wno-builtin-macro-redefined",
                            "-D__DATE__=\"redacted\"",
                            "-D__TIMESTAMP__=\"redacted\"",
                            "-D__TIME__=\"redacted\"",
                        ],
                    ),
                ],
            ),
        ],
    )

    supports_dynamic_linker_feature = feature(name = "supports_dynamic_linker", enabled = True)

    dbg_feature = feature(name = "dbg")

    sysroot_feature = feature(
        name = "sysroot",
        enabled = True,
        flag_sets = [
            flag_set(
                actions = [
                    ACTION_NAMES.preprocess_assemble,
                    ACTION_NAMES.linkstamp_compile,
                    ACTION_NAMES.c_compile,
                    ACTION_NAMES.cpp_compile,
                    ACTION_NAMES.cpp_header_parsing,
                    ACTION_NAMES.cpp_module_compile,
                    ACTION_NAMES.cpp_module_codegen,
                    ACTION_NAMES.lto_backend,
                    ACTION_NAMES.clif_match,
                    ACTION_NAMES.cpp_link_executable,
                    ACTION_NAMES.cpp_link_dynamic_library,
                    ACTION_NAMES.cpp_link_nodeps_dynamic_library,
                ],
                flag_groups = [
                    flag_group(
                        flags = ["--sysroot=%{sysroot}"],
                        expand_if_available = "sysroot",
                    ),
                ],
            ),
        ],
    )

    features = [
        default_compile_flags_feature,
        cc_std_feature,
        default_link_flags_feature,
        dynamic_interpreter_feature,
        fdo_optimize_feature,
        fortran_feature,
        supports_dynamic_linker_feature,
        supports_start_end_lib_feature,
        supports_pic_feature,
        per_object_debug_info_feature,
        objcopy_embed_flags_feature,
        opt_feature,
        dbg_feature,
        user_compile_flags_feature,
        sysroot_feature,
        unfiltered_compile_flags_feature,
    ]

    tool_paths = [
        tool_path(
            name = "ar",
            path = "root/x86_64-linux-gnu/bin/ar",
        ),
        tool_path(name = "cpp", path = "root/bin/cpp"),
        tool_path(
            name = "dwp",
            path = "root/x86_64-linux-gnu/bin/dwp",
        ),
        tool_path(name = "gcov", path = "root/bin/gcov"),
        tool_path(
            name = "ld",
            path = "root/x86_64-linux-gnu/bin/ld.gold",
        ),
        tool_path(
            name = "nm",
            path = "root/x86_64-linux-gnu/bin/nm",
        ),
        tool_path(
            name = "objcopy",
            path = "root/x86_64-linux-gnu/bin/objcopy",
        ),
        tool_path(
            name = "objdump",
            path = "root/x86_64-linux-gnu/bin/objdump",
        ),
        tool_path(
            name = "strip",
            path = "root/x86_64-linux-gnu/bin/strip",
        ),
    ]
    if ctx.attr.compiler == "cuda":
        tool_paths.append(tool_path(name = "gcc", path = "root/bin/cuda_wrap_gcc"))
    else:
        tool_paths.append(tool_path(name = "gcc", path = "root/bin/gcc"))

    return [
        cc_common.create_cc_toolchain_config_info(
            ctx = ctx,
            features = features,
            action_configs = action_configs,
            artifact_name_patterns = [],
            cxx_builtin_include_directories = ctx.attr.builtin_include_directories,
            toolchain_identifier = ctx.attr.toolchain_identifier,
            host_system_name = "local",
            target_system_name = "local",
            target_cpu = "k8",
            target_libc = "local",
            compiler = ctx.attr.compiler,
            abi_version = "local",
            abi_libc_version = "local",
            tool_paths = tool_paths,
            make_variables = [],
            builtin_sysroot = ctx.attr.builtin_sysroot,
            cc_target_os = None,
        ),
    ]

drte_toolchain_config = rule(
    implementation = _impl,
    attrs = {
        "compiler": attr.string(mandatory = True, values = ["compiler", "cuda"]),
        "toolchain_identifier": attr.string(mandatory = True, values = ["local", "cuda"]),
        "builtin_sysroot": attr.string(mandatory = True),
        "rtld": attr.string(mandatory = True),
        "builtin_include_directories": attr.string_list(),
    },
    provides = [CcToolchainConfigInfo],
)


r, D, x = map(int,input().split())

def function(y):
    y = r * y - D

    return y

z = 1
while z <= 10:
    z += 1
    ans = function(x)
    x = function(x)
    print(ans)


# Faça a função ficha() que receba 2 parâmetros opcionais: o nome do jogador e quantos gols marcou. Mesmo que nada tenha sido informado, deverá retornar <desconhecido> ou 0 gol(s)
def ficha(player = '<irineu>', gols = 0):
    return f'{player} fez {gols} gol(s)'

player = str(input('Nome do jogador: ')).title()
gols = str(input('Gols feitos: '))
if gols.isnumeric():
    gols = int(gols)
else:
    gols = 0

if player == '':
    player = '<irineu>'

print(ficha(player, gols))


'''
Created on 8 apr 2013

@author: Jonas
'''
from fursten.simulatorproxy.proxy import Proxy
from fursten.simulatorproxy import resource_pb2

class ResourceProxy(Proxy):

    REST_PATH = 'resources'
    _instance = None
    _protobuf_instance = None

    def __new__(cls, mime_type=None, *args, **kwargs):

        if mime_type == Proxy.MimeType.PROTOBUF:
            if not cls._protobuf_instance:
                cls._protobuf_instance = super(ResourceProxy, cls).__new__(cls, mime_type, *args, **kwargs)
            return cls._protobuf_instance
        else:
            if not cls._instance:
                cls._instance = super(ResourceProxy, cls).__new__(cls, mime_type, *args, **kwargs)
            return cls._instance

    def __init__(self, mime_type=None):
        super(ResourceProxy, self).__init__(mime_type)

    def getResource(self, key):
        path = self.REST_PATH + "/" + key
        return super(ResourceProxy, self).get(path=path)

    def addResource(self, data, parentKey=None):
        #post to root for new root resource
        if parentKey is None:
            path = self.REST_PATH
        else:
            path = self.REST_PATH + "/" + str(parentKey)

        return super(ResourceProxy, self).post(path=path, data=data)

    def replaceResource(self, data, key):
        path = self.REST_PATH + "/" + key
        return super(ResourceProxy, self).put(path=path, data=data)

    def deleteResource(self, key):
        path = self.REST_PATH + "/" + key
        return super(ResourceProxy, self).delete(path=path)

    def getResources(self, details=False, resource_keys=None, method=None):
        path = self.REST_PATH
        params = {}

        if details is not None:
            params['details'] = details

        if resource_keys is not None:
            params['r'] = resource_keys

            if method is not None:
                params['method'] = method

        return super(ResourceProxy, self).get(path=path, params=params)

    def replaceResources(self, data):
        path = self.REST_PATH
        return super(ResourceProxy, self).put(path=path, data=data)

    def deleteResources(self, resource_keys=None, method=None):
        path = self.REST_PATH
        params = {}

        if resource_keys is not None:
            params['r'] = resource_keys

            if method is not None:
                params['method'] = method

        return super(ResourceProxy, self).delete(path=path, params=params)

    def parseProtobufData(self, send_data):

        #Add data as protobuf class or raw encoded string
        if isinstance(send_data, resource_pb2.ResourceCollection):
            return send_data.SerializeToString()
        else:
            return send_data

    def parseProtobufResponse(self, respons_data):
        resourceCollection = resource_pb2.ResourceCollection()
        resourceCollection.ParseFromString(respons_data)
        return resourceCollection


#用python操作excel
#第一步：导入load_workbook模块中的load_workbook函数
from openpyxl import load_workbook
#第二步：打开读取excel
wb=load_workbook(filename)#使用openpyxl读取xlsx文件，创建workbook,()里有多个参数，只有filename必填项
print(wb.sheetnames)#显示所有sheet名称，['sheet1名称', 'sheet2名称', ...]
#第三步：定位表单
ws=wb[sheetname]
#第四步：操作表单
#4.1定位单元格cell，根据行列读取数据
mm=ws.cell(row=2,column=3).value#读取某个sheet页第2行第3列单元格C2的值
#读取多个sheet的单元格
for i in wb.sheetnames:
    ws=wb[i]
    ws.cell(row=1,column=3).value#遍历所有的sheet页，读取每个sheet页C1的值
#4.2定位单元格（cell），根据行列值，更改原有的数据、写入新的测试数据，
mm="hello"#C2单元格写入'hello'
wb.save(filename)#wb.save('1.xlsx')保存文件
#4.3统计行列数
print(ws.max_row)#表行数
print(ws.max_column)#表列数
#类型
#excel 存储的数据，数字还是数字：int—>int、 float—>float 、其他类型—>str
#执行用例时需要将str()类型转化为原来的类型,eval(数据)
wb.close()#关闭


from telegram import Bot, ParseMode
import requests
from bs4 import BeautifulSoup

# Telegram bot API token
TELEGRAM_TOKEN = ""
CHANNEL_ID = "CHANNEL-ID"

# BBC News URL to scrape
BBC_CHELSEA_NEWS_URL = r"https://www.bbc.com/sport/football/teams/chelsea"

# Initialize the Telegram bot
bot = Bot(token=TELEGRAM_TOKEN)

# Function to scrape news from BBC News
def scrape_bbc_chelsea_news():
    # Send a GET request to the BBC News website
    response = requests.get(BBC_CHELSEA_NEWS_URL)
    response.raise_for_status()

    # Parse the HTML response
    soup = BeautifulSoup(response.content, 'html.parser')

    # Find all the news articles on the page
    articles = soup.find_all('article', {'class': 'ssrcss-1wieoaj-ContentPost e6wdqbx2'})

    # Extract the relevant information from each article
    news_items = []
    invalid_news_item = [None, 'Listen to the full episode here', 'Listen to Football Daily on BBC Sounds',
                         'Listen to Euro Leagues on BBC Sounds', 'Here are some more thoughts:',
                         'Want more transfer news?']

    for article in articles[:4]:
        title = article.header.span.span.string
        contents = [content.string for content in article.find_all('p') if content.string not in invalid_news_item]
        news_items.append({'title': title, 'contents': contents})
    return news_items

# Function to send news to Telegram
def send_news_to_telegram(news_items):
    for item in news_items:
        if len(item['contents']) != 0:
            i_title = item['title']
            i_content = '\n'.join(item['contents'])

            message = f"? {i_title}\n\n{i_content}\n\n@BBC News"

            try:
                with open("log.txt", "r") as file:
                    saved_titles = [line.rstrip("\n") for line in file.readlines()]

                if i_title not in saved_titles:
                    try:
                        # Save the title
                        with open("log.txt", 'a') as file:
                            file.write(i_title)
                            file.write("\n")

                        # Send the message to Telegram
                        bot.send_message(chat_id=CHANNEL_ID, text=message, parse_mode=ParseMode.MARKDOWN)
                        print(message)

                    except UnicodeError:
                        pass

            except FileNotFoundError:
                # Incase Logfile not found
                with open("log.txt", 'a') as file:
                    file.write(i_title)
                    file.write("\n")

# Main function to run the bot
def main():
    # Scrape the news from BBC News
    news_items = scrape_bbc_chelsea_news()

    # Send the news to Telegram
    send_news_to_telegram(news_items)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
<header>
    <input>PhokharaEvtgenData.root</input>
    <output>PhokharaEvtgenAnalysis.root</output>
    <contact>Kirill Chilikin (K.A.Chilikin@inp.nsk.su)</contact>
    <description>Analysis of e+ e- -> J/psi eta_c events.</description>
</header>
"""

import basf2 as b2
import ROOT
import numpy
from ROOT import Belle2

class PhokharaEvtgenAnalysisModule(b2.Module):
    """ Analysis module for PhokharaEvtgen. """

    def __init__(self):
        """Initialization."""
        super(PhokharaEvtgenAnalysisModule, self).__init__()
        #: Output file.
        self.output_file = ROOT.TFile('PhokharaEvtgenAnalysis.root', 'recreate')
        #: Output tree.
        self.tree = ROOT.TTree('tree', '')
        #: Beam energy.
        self.ecms = numpy.zeros(1, dtype=numpy.float32)
        #: Virtual photon energy.
        self.gamma_e = numpy.zeros(1, dtype=numpy.float32)
        #: Virtual photon momentum (x component).
        self.gamma_px = numpy.zeros(1, dtype=numpy.float32)
        #: Virtual photon momentum (y component).
        self.gamma_py = numpy.zeros(1, dtype=numpy.float32)
        #: Virtual photon momentum (z component).
        self.gamma_pz = numpy.zeros(1, dtype=numpy.float32)
        #: J/psi energy.
        self.jpsi_e = numpy.zeros(1, dtype=numpy.float32)
        #: J/psi momentum (x component).
        self.jpsi_px = numpy.zeros(1, dtype=numpy.float32)
        #: J/psi momentum (y component).
        self.jpsi_py = numpy.zeros(1, dtype=numpy.float32)
        #: J/psi momentum (z component).
        self.jpsi_pz = numpy.zeros(1, dtype=numpy.float32)
        #: Lepton energy.
        self.lepton_e = numpy.zeros(1, dtype=numpy.float32)
        #: Lepton momentum (x component).
        self.lepton_px = numpy.zeros(1, dtype=numpy.float32)
        #: Lepton momentum (y component).
        self.lepton_py = numpy.zeros(1, dtype=numpy.float32)
        #: Lepton momentum (z component).
        self.lepton_pz = numpy.zeros(1, dtype=numpy.float32)
        self.tree.Branch('ecms', self.ecms, 'ecms/F')
        self.tree.Branch('gamma_e', self.gamma_e, 'gamma_e/F')
        self.tree.Branch('gamma_px', self.gamma_px, 'gamma_px/F')
        self.tree.Branch('gamma_py', self.gamma_py, 'gamma_py/F')
        self.tree.Branch('gamma_pz', self.gamma_pz, 'gamma_pz/F')
        self.tree.Branch('jpsi_e', self.jpsi_e, 'jpsi_e/F')
        self.tree.Branch('jpsi_px', self.jpsi_px, 'jpsi_px/F')
        self.tree.Branch('jpsi_py', self.jpsi_py, 'jpsi_py/F')
        self.tree.Branch('jpsi_pz', self.jpsi_pz, 'jpsi_pz/F')
        self.tree.Branch('lepton_e', self.lepton_e, 'lepton_e/F')
        self.tree.Branch('lepton_px', self.lepton_px, 'lepton_px/F')
        self.tree.Branch('lepton_py', self.lepton_py, 'lepton_py/F')
        self.tree.Branch('lepton_pz', self.lepton_pz, 'lepton_pz/F')

    def event(self):
        """ Event function. """
        mc_initial_particles = Belle2.PyStoreObj('MCInitialParticles')
        self.ecms[0] = mc_initial_particles.getMass()
        mc_particles = Belle2.PyStoreArray('MCParticles')
        for mc_particle in mc_particles:
            # Select virtual photons.
            if (mc_particle.getPDG() != 10022):
                continue
            p = mc_particle.getMomentum()
            self.gamma_e[0] = mc_particle.getEnergy()
            self.gamma_px[0] = p.X()
            self.gamma_py[0] = p.Y()
            self.gamma_pz[0] = p.Z()
            jpsi = mc_particle.getDaughters()[0]
            p = jpsi.getMomentum()
            self.jpsi_e[0] = jpsi.getEnergy()
            self.jpsi_px[0] = p.X()
            self.jpsi_py[0] = p.Y()
            self.jpsi_pz[0] = p.Z()
            lepton = jpsi.getDaughters()[0]
            p = lepton.getMomentum()
            self.lepton_e[0] = lepton.getEnergy()
            self.lepton_px[0] = p.X()
            self.lepton_py[0] = p.Y()
            self.lepton_pz[0] = p.Z()
            self.tree.Fill()

    def terminate(self):
        """ Termination function. """
        self.output_file.cd()
        self.tree.Write()
        self.output_file.Close()

# Input.
root_input = b2.register_module('RootInput')
root_input.param('inputFileName', 'PhokharaEvtgenData.root')

# Analysis.
phokhara_evtgen = PhokharaEvtgenAnalysisModule()

# Create main path.
main = b2.create_path()

# Add modules to main path
main.add_module(root_input)
main.add_module(phokhara_evtgen)

main.add_module('Progress')
# Run.
b2.process(main)

print(b2.statistics)


import math, pygame
import button

class Graph():
	def __init__(self, screen, rect, title, data, minValue=0, maxValue=0):

		self.screen = screen
		self.rect = rect
		self.colour = (200,200,200)		# Background colour

		self.title = title

		self.font = pygame.font.SysFont(None, 30)

		self.data = data

		self.oldLength = len(self.data)

		# Initialise min/max values for the graph to render with
		self.minValue = minValue
		self.maxValue = maxValue
		for i in self.data:
			if i>self.maxValue:
				self.maxValue = i
			elif i<self.minValue:
				self.minValue = i

		self.scale = 0

		self.buttonList = [
			button.Button(self.screen, pygame.Rect(self.rect.right-40, self.rect.top+10, 30, 30), ">", 40, self.scale_up),
			button.Button(self.screen, pygame.Rect(self.rect.right-75, self.rect.top+10, 30, 30), "<", 40, self.scale_down)
		]

	def update(self, mouseState):	# Starts the main update loop

		# Buttons for changing scale
		for button in self.buttonList:
			button.update(mouseState)

		# Test if items have been added to data and update min/max accordingly
		if self.oldLength < len(self.data):
			for i in self.data[self.oldLength:]:
				if i>self.maxValue:
					self.maxValue = i
				elif i<self.minValue:
					self.minValue = i

	def render(self, mouseState):
		pygame.draw.rect(self.screen, self.colour, self.rect)
		pygame.draw.rect(self.screen, (0,0,0), self.rect, 3)

		if len(self.data) >= 2 and self.maxValue != self.minValue:
			pygame.draw.lines(self.screen, (255,0,0), False, [
				[
					self.rect.left + self.rect.w*(k/(len(self.data)-1)),
					self.rect.bottom - self.rect.h*((i-self.minValue)/(self.maxValue-self.minValue))
				] for k,i in enumerate(self.data)
			], 2)

		# Render min/max value
		text = self.font.render(str(self.maxValue), True, (0,0,0))
		self.screen.blit(text, [self.rect.left+5, self.rect.top+5])
		text = self.font.render(str(self.minValue), True, (0,0,0))
		self.screen.blit(text, [self.rect.left+5, self.rect.bottom-text.get_rect().h-5])

		# Render No. of items
		text = self.font.render(str(len(self.data)), True, (0,0,0))
		self.screen.blit(text, [self.rect.right-text.get_rect().w-5, self.rect.bottom-text.get_rect().h-5])

		# Render title
		text = self.font.render(str(self.title), True, (0,0,0))
		self.screen.blit(text, [self.rect.centerx-text.get_rect().w/2, self.rect.top+5])

		# Render scale
		text = self.font.render(str(10**self.scale)+"x", True, (0,0,0))
		self.screen.blit(text, [self.rect.right-text.get_rect().w-85, self.rect.top+15])

		for button in self.buttonList:
			button.render(mouseState)

	def scale_up(self):
		self.scale += 1

	def scale_down(self):
		if self.scale > 0:
			self.scale -= 1


from edc_constants.constants import (
    DEAD,
    MALIGNANCY,
    NOT_APPLICABLE,
    OTHER,
    TUBERCULOSIS,
    UNKNOWN,
)
from edc_constants.disease_constants import (
    ANAEMIA,
    BACTERAEMIA,
    BACTERIAL_PNEUMONIA,
    NEUTROPAENIA,
    PNEUMONIA,
    RENAL_IMPAIRMENT,
    THROMBOCYTOPENIA,
)

list_data = {
    "edc_adverse_event.causeofdeath": [
        (BACTERAEMIA, "Bacteraemia"),
        (BACTERIAL_PNEUMONIA, "Bacterial pneumonia"),
        (MALIGNANCY, "Malignancy"),
        ("art_toxicity", "ART toxicity"),
        ("IRIS_non_CM", "IRIS non-CM"),
        ("diarrhea_wasting", "Diarrhea/wasting"),
        (UNKNOWN, "Unknown"),
        (OTHER, "Other"),
    ],
    "edc_adverse_event.aeclassification": [
        (ANAEMIA, "Anaemia"),
        ("bacteraemia/sepsis", "Bacteraemia/Sepsis"),
        ("CM_IRIS", "CM IRIS"),
        ("diarrhoea", "Diarrhoea"),
        ("hypokalaemia", "Hypokalaemia"),
        (NEUTROPAENIA, "Neutropaenia"),
        (PNEUMONIA, "Pneumonia"),
        (RENAL_IMPAIRMENT, "Renal impairment"),
        ("respiratory_distress", "Respiratory distress"),
        (TUBERCULOSIS, "TB"),
        (THROMBOCYTOPENIA, "Thrombocytopenia"),
        ("thrombophlebitis", "Thrombophlebitis"),
        (OTHER, "Other"),
    ],
    "edc_adverse_event.saereason": [
        (NOT_APPLICABLE, "Not applicable"),
        (DEAD, "Death"),
        ("life_threatening", "Life-threatening"),
        ("significant_disability", "Significant disability"),
        (
            "in-patient_hospitalization",
            (
                "In-patient hospitalization or prolongation "
                "(17 or more days from study inclusion)"
            ),
        ),
        (
            "medically_important_event",
            "Medically important event (e.g. Severe thrombophlebitis, Bacteraemia, "
            "recurrence of symptoms not requiring admission, Hospital acquired "
            "pneumonia)",
        ),
    ],
}


"""
CORRESPOND: matrix IO utilities in matrix.cpp
"""
import sys
from typing import Optional, Iterable

import torch
import numpy as np
from ..constants.engineering import COMMENT_CHAR
from .. import VERSION
from .helper_functions import check_tensor
from enum import Enum

class ByteOrder(Enum):
    BIG_ENDIAN = "be"
    LITTLE_ENDIAN = "le"
    NATIVE = "native"

    @staticmethod
    def options():
        return ["be", "le", "native"]

    def to_np_representation(self):
        if self == ByteOrder.BIG_ENDIAN:
            return '>'
        elif self == ByteOrder.LITTLE_ENDIAN:
            return '<'
        else:
            return '='

def need_reverse_byte_order(byte_order: ByteOrder):
    if byte_order == ByteOrder.BIG_ENDIAN:
        return sys.byteorder == "little"
    elif byte_order == ByteOrder.LITTLE_ENDIAN:
        return sys.byteorder == "big"
    else:
        return False

def read_matrix_text(filepath):
    """
    Read a matrix from a txt file,
    whose first line species dimensions and the rest are data
    :param filepath:
    :return: 2D tensor
    """
    with open(filepath, "r") as f:
        lines = f.readlines()
    valid_lines = []
    for line in lines:
        if not line.startswith(COMMENT_CHAR):
            valid_lines.append(line.strip())

    first_line = valid_lines.pop(0).split(" ")
    m = int(first_line[0])
    n = int(first_line[1])

    matrix_content_strings = " ".join(valid_lines)
    matrix = np.fromstring(matrix_content_strings, dtype=np.float64, sep=" ").reshape(m, n)
    return torch.from_numpy(matrix).double()

def write_matrix_text_with_headers(matrix: torch.Tensor, file_path, *header_strings):
    """
    Writes a matrix to a txt file, with optional headers
    :param matrix: matrix to be written
    :param file_path: file path
    :param header_strings: optional
    """
    # CORRESPOND: write_matrix_text_valist() without conv
    check_tensor(matrix, dimensionality=2)
    header_string = " ".join(header_strings)
    matrix_strings = str(matrix.numpy()).replace("[", "").replace("]", "").split("\n")
    matrix_strings = [string.strip() for string in matrix_strings]
    file_content = []
    file_content.append(f"{COMMENT_CHAR} File created by TEM-simulator, version {VERSION}\n")
    file_content.append(f"{matrix.shape[0]} {matrix.shape[1]}\n")
    file_content.append(f"{COMMENT_CHAR} {header_string}\n")
    file_content.append("\n".join(matrix_strings))
    with open(file_path, "w") as f:
        f.writelines(file_content)

def write_tensor_to_binary(tensor: torch.Tensor,
                           filepath: str,
                           as_type: Optional[torch.dtype] = None,
                           append: Optional[bool] = False,
                           endian: Optional[ByteOrder] = None):
    """
    Dumps a tensor to a binary file

    :param tensor: tensor to be dumped
    :param filepath: file path
    :param as_type: Optional casting data type
    :param append: enable append mode
    :param endian:
    """
    if as_type is not None:
        tensor = tensor.to(as_type)
    mode = "ab" if append else "wb"
    with open(filepath, mode) as f:
        if endian is None:
            f.write(tensor.numpy().tobytes())
        else:
            np_array = tensor.numpy()
            dtype = np.dtype(np_array.dtype).newbyteorder(endian.to_np_representation())
            f.write(np_array.astype(dtype).tobytes())

def read_tensor_from_binary(filepath: str, dtype: torch.dtype,
                            shape: Optional[Iterable[int]] = None,
                            endian: Optional[ByteOrder] = None):
    """
    Read a tensor from a binary file

    :param filepath: file path
    :param dtype: data type of the reading tensor
    :param shape: shape of the reading tensor
    :param endian:
    :return: read tensor
    """
    np_dtype = torch.ones(1, dtype=dtype).numpy().dtype
    if endian is not None:
        np_dtype = np.dtype(np_dtype).newbyteorder(endian.to_np_representation())
    with open(filepath, "rb") as f:
        byte_array = f.read()
        t = torch.from_numpy(np.frombuffer(byte_array, dtype=np_dtype))

    if shape is None:
        return t
    else:
        return t.reshape(*shape)


import sys
import dbus
import math
import subprocess
from traceback import print_exc
from os.path import dirname
from adapt.intent import IntentBuilder
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger

__author__ = 'aix'

LOGGER = getLogger(__name__)

class KonversationControlDesktopSkill(MycroftSkill):

    # The constructor of the skill, which calls MycroftSkill's constructor
    def __init__(self):
        super(KonversationControlDesktopSkill, self).__init__(name="KonversationControlDesktopSkill")

    # This method loads the files needed for the skill's functioning, and
    # creates and registers each intent that the skill uses
    def initialize(self):
        self.load_data_files(dirname(__file__))

        konversationcontrol_showwin_intent = IntentBuilder("KonversationShowKeywordIntent").\
            require("InternalKonversationShowKeyword").build()
        self.register_intent(konversationcontrol_showwin_intent, self.handle_konversationcontrol_showwin_intent)

        konversationcontrol_quitwin_intent = IntentBuilder("KonversationQuitKeywordIntent").\
            require("InternalKonversationQuitKeyword").build()
        self.register_intent(konversationcontrol_quitwin_intent, self.handle_konversationcontrol_quitwin_intent)

        konversationcontrol_openservlist_intent = IntentBuilder("KonversationOpenServListIntent").\
            require("InternalKonversationOpenServListKeyword").build()
        self.register_intent(konversationcontrol_openservlist_intent, self.handle_konversationcontrol_openservlist_intent)

        konversationcontrol_openidentity_intent = IntentBuilder("KonversationOpenIdentityIntent").\
            require("InternalKonversationOpenIdentityKeyword").build()
        self.register_intent(konversationcontrol_openidentity_intent, self.handle_konversationcontrol_openidentity_intent)

    def handle_konversationcontrol_showwin_intent(self, message):
                bus = dbus.SessionBus()
                remote_object = bus.get_object("org.kde.konversation","/konversation/MainWindow_1")
                remote_object.showNormal(dbus_interface = "org.qtproject.Qt.QWidget")
                remote_object.activateAndRaiseWindow(dbus_interface = "org.kde.konversation.MainWindow")

    def handle_konversationcontrol_quitwin_intent(self, message):
                bus = dbus.SessionBus()
                remote_object = bus.get_object("org.kde.konversation","/konversation/MainWindow_1")
                remote_object.quitProgram(dbus_interface = "org.kde.konversation.MainWindow")

    def handle_konversationcontrol_openservlist_intent(self, message):
                bus = dbus.SessionBus()
                remote_object = bus.get_object("org.kde.konversation","/konversation/MainWindow_1")
                remote_object.openServerList(dbus_interface = "org.kde.konversation.MainWindow")
                remote_object.activateAndRaiseWindow(dbus_interface = "org.kde.konversation.MainWindow")

    def handle_konversationcontrol_openidentity_intent(self, message):
                bus = dbus.SessionBus()
                remote_object = bus.get_object("org.kde.konversation","/konversation/MainWindow_1")
                remote_object.openIdentitiesDialog(dbus_interface = "org.kde.konversation.MainWindow")
                remote_object.activateAndRaiseWindow(dbus_interface = "org.kde.konversation.MainWindow")

    def stop(self):
        pass

# The "create_skill()" method is used to create an instance of the skill.
# Note that it's outside the class itself.
def create_skill():
    return KonversationControlDesktopSkill()


import cv2
import math
from pyspark.context import SparkContext
from pyspark.sql.session import SparkSession
from pyspark.sql.types import IntegerType, StructField, StructType
import sys
import os

class imageProcessing:

    @staticmethod
    def get_grayClasses(landsatGrayImage):
        rows, columns = landsatGrayImage.shape
        grayClasses = set()

        for pixelX in range(rows):
            for pixelY in range(columns):
                #print(landsatGrayImage[pixelX, pixelY])
                grayClasses.add(landsatGrayImage[pixelX, pixelY])
        return grayClasses

    @staticmethod
    def get_grayClassesProbability(grayClasses, landsatGrayImage):
        P = []
        rows, columns = landsatGrayImage.shape

        for grayClass in grayClasses:
            P.append(grayClass / (rows * columns))
        return P

    @staticmethod
    def get_momentum(P):
        omega = []
        omega.append(P[1])
        mu = []
        mu.append(0)

        for grayIndex in range(1, len(P)):
            omega.append(omega[grayIndex - 1] + P[grayIndex])
            mu.append(mu[grayIndex - 1] + ((grayIndex-1)*P[grayIndex]))
        return mu, omega

    @staticmethod
    def image_normalization(img, umbral):
        #print(landsatImage.shape[0])
        cv2.normalize(img, img, 0, umbral, cv2.NORM_MINMAX, -1)#poner antes de otsu
        #cv2.imshow("normaltiff", img)
        ret, img = cv2.threshold(img, 0, umbral, cv2.THRESH_BINARY)
        #cv2.thre

#        img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        #cv2.imwrite(r"..\imageOut\NoSquare.tif",img)
        return img

    @staticmethod
    def __otsu_thesholdMAX(mu, omega):
        sigmaMax = 0
        mut = mu[-1]

        for index in range(1, len(omega)):
            omega1 = omega[index]
            omega2 = 1 - omega1
            if omega1!=0 and omega2!=0:
                mu1 = mu[index] / omega1
                mu2 = (mut - mu[index]) / omega2

                sigma = omega1 * math.pow((mu1 - mut), 2) + omega2 * math.pow((mu2 - mut),2)
                if sigma > sigmaMax:
                    sigmaMax = sigma
                    umbralOptimo = index - 1
        return sigmaMax, umbralOptimo

    @staticmethod
    def otsu_threshold(landsatGrayImage):
        grayClasses = imageProcessing.get_grayClasses(landsatGrayImage) #Pi
        print("Gray Classes detected: ",len(grayClasses))
        P = imageProcessing.get_grayClassesProbability(grayClasses, landsatGrayImage)
        #print("Valor de  P calculado: ", P)
        mu, omega = imageProcessing.get_momentum(P)
        #print ("Mu:, ", mu)
        #print("Omega, ", omega)
        Max, umbral = imageProcessing.__otsu_thesholdMAX(mu, omega)
        print("FINAL Max-> ",Max, umbral)
        #Min, umbral = imageProcessing.__otsu_thesholdMAX(mu, omega)
        #print("FINAL Min -> ", Min, umbral)
        return umbral

    @staticmethod
    def main(landsatTiffImage, df_total):

        landsatImage = cv2.imread(landsatTiffImage, cv2.IMREAD_UNCHANGED)
        if imageProcessing.get_imageChannels(landsatImage):
            landsatGrayImage = cv2.cvtColor(landsatImage, cv2.COLOR_RGB2GRAY)
        else:
            landsatGrayImage = landsatImage
        umbral = imageProcessing.otsu_threshold(landsatGrayImage)
        landsatImage = imageProcessing.image_normalization(landsatGrayImage, umbral)
        return imageProcessing.createDataFrame(landsatImage, df_total)

    @staticmethod
    def createDataFrame(landsatImage, df_total):
        testOriginal = [landsatImage[pixelX, pixelY] for pixelX in range(landsatImage.shape[0]) for pixelY in range(landsatImage.shape[1])]
        #testOriginal = [1,2,3]
        schema = StructType([
            StructField('pixelsLabel', IntegerType(), True)
        ])
        rdd = spark.sparkContext.parallelize(testOriginal, numSlices=1000)
        if df_total is None:
            df_total = spark.createDataFrame(rdd, schema)
            df_total.show()
        else:
            dfOtsu = spark.createDataFrame(rdd, schema)
            df_total = df_total.union(dfOtsu)
        return df_total

    @staticmethod
    def get_imageChannels(img):
        try:
            return img.shape[2]
        except IndexError:
            return None

if __name__ == '__main__':
    originalPath = sys.argv[1]
    df_total = None
    sc = SparkContext('local')
    spark = SparkSession(sc)
    for landsatTiffImage in os.listdir(originalPath):
        originalImg = "{}\{}".format(originalPath, landsatTiffImage)
        df_total = imageProcessing.main(originalImg, df_total)

    #saving as parquet file
    df_total.write.parquet("output/proto.parquet")


import ivy
import ivy.functional.frontends.tensorflow as tf_frontend
from ivy.functional.frontends.tensorflow.func_wrapper import to_ivy_arrays_and_back
from ivy import with_supported_dtypes

ACTIVATION_FUNCTIONS = [
    "gelu",
    "leaky_relu",
    "log_softmax",
    "relu",
    "sigmoid",
    "silu",
    "softmax",
    "softplus",
]

@with_supported_dtypes(
    {"2.14.0 and below": ("float16", "float32", "float64")},
    "tensorflow",
)
def deserialize(name, custom_objects=None):
    if name is None:
        return None

    elif isinstance(name, str):
        if custom_objects and name in custom_objects:
            return custom_objects.get(name)

        # To replicate tensorflow framework
        elif (
            ivy.current_backend().__name__.split(".")[-1] == "tensorflow"
            and name in tf_frontend.keras.activations.__dict__
        ):  # noqa
            return tf_frontend.keras.activations.__dict__[name]

        # On other backends, query the function from global ivy dict
        elif name in ACTIVATION_FUNCTIONS:
            return ivy.__dict__[name]

        else:
            raise ValueError(f"Unknown activation function: {name}.")

    else:
        raise ValueError(f"Could not interpret activation function: {name}")

@with_supported_dtypes(
    {"2.14.0 and below": ("bfloat16", "float16", "float32", "float64")},
    "tensorflow",
)
@to_ivy_arrays_and_back
def elu(x, alpha=1.0):
    zeros = ivy.zeros_like(x, dtype=ivy.dtype(x))
    ones = ivy.ones_like(x, dtype=ivy.dtype(x))
    alpha = ivy.astype(ivy.array(alpha), ivy.dtype(x))
    ret_val = ivy.where(
        x > zeros, x, ivy.multiply(alpha, ivy.subtract(ivy.exp(x), ones))
    )
    return ret_val

@to_ivy_arrays_and_back
def gelu(x, approximate=False):
    return ivy.gelu(x, approximate=approximate)

def get(identifier):
    if identifier is None:
        return tf_frontend.keras.activations.linear

    elif isinstance(identifier, str):
        return tf_frontend.keras.activations.deserialize(identifier)

    elif callable(identifier):
        return identifier

    else:
        raise ValueError(f"Could not interpret function identifier: {identifier}")

@to_ivy_arrays_and_back
def hard_sigmoid(x):
    dtype_in = x.dtype
    point_two = ivy.full(x.shape, 0.2)
    point_five = ivy.full(x.shape, 0.5)
    x = ivy.multiply(x, point_two)
    x = ivy.add(x, point_five)
    x = ivy.clip(x, 0.0, 1.0)
    x = ivy.asarray(x, dtype=dtype_in)
    return x

@to_ivy_arrays_and_back
def linear(x):
    return ivy.array(x)

@to_ivy_arrays_and_back
def relu(x, alpha=0.0, max_value=None, threshold=0.0):
    return ivy.relu(x)

@with_supported_dtypes(
    {"2.14.0 and below": ("float16", "float32", "float64")},
    "tensorflow",
)
@to_ivy_arrays_and_back
def selu(x):
    return ivy.selu(x)

@with_supported_dtypes(
    {"2.14.0 and below": ("float16", "float32", "float64")},
    "tensorflow",
)
def serialize(activation, use_legacy_format=False, custom_objects=None):
    # If the activation function is None, return None
    if activation is None:
        return None

    # If the activation function is already a string, return it
    elif isinstance(activation, str):
        return activation

    # If the activation function is callable (a function), get its name
    elif callable(activation):
        # Check if the function is in the custom_objects dictionary
        if custom_objects:
            for name, custom_func in custom_objects.items():
                if custom_func == activation:
                    return name

        # Check if the function is in the ACTIVATION_FUNCTIONS list
        if activation.__name__ in ACTIVATION_FUNCTIONS:
            return activation.__name__

        # Check if the function is in the TensorFlow frontend activations
        elif activation in tf_frontend.keras.activations.__dict__.values():
            for name, tf_func in tf_frontend.keras.activations.__dict__.items():
                if tf_func == activation:
                    return name

        else:
            raise ValueError(f"Unknown activation function: {activation}.")

    else:
        raise ValueError(f"Could not interpret activation function: {activation}")

@to_ivy_arrays_and_back
def sigmoid(x):
    return ivy.sigmoid(x)

@to_ivy_arrays_and_back
def softmax(x, axis=-1):
    return ivy.softmax(x, axis=axis)

@to_ivy_arrays_and_back
def softplus(x):
    return ivy.softplus(x)

@to_ivy_arrays_and_back
def softsign(x):
    return ivy.divide(x, ivy.add(1, ivy.abs(x)))

@to_ivy_arrays_and_back
def swish(x):
    return ivy.multiply(x, ivy.sigmoid(x))

@to_ivy_arrays_and_back
def tanh(x):
    return ivy.tanh(x)


import data

MAX_PLAYERS_FROM_TEAM = 5 if data.FIVE_PLAYERS_FROM_TEAM else 4
MAX_UNCERTAINTY = 3.2 if data.EXTRA_STRIKER else 3

class Player:
    def __init__(self, player_row):
        self.id = player_row['player_id']
        self.name = player_row['player_name']
        self.pos = player_row['pos']
        self.team = player_row['team']
        self.price = player_row['price']
        self.points = player_row['total_points']
        self.uncertainty = 90 / player_row['total_mins']

def budget_pick(df):
    knapsack = []
    for _ in range(int(4 * data.TOTAL_BUDGET + .1) + 1):
        knapsack.append({})

    for player_index, player_row in df.iterrows():
        print(f'Processing player {player_index}')
        player = Player(player_row)

        new_knapsack = []
        for i in range(len(knapsack)):
            capacity = i / 4
            new_knapsack.append(knapsack[i].copy())

            if player.price >= capacity + .1 or player.uncertainty >= MAX_UNCERTAINTY:
                continue

            alone_formation = [0] * 4
            alone_formation[['gk', 'd', 'm', 'st'].index(player.pos)] += 1
            alone_formation = ''.join(str(n) for n in alone_formation)
            if(alone_formation not in new_knapsack[i]) or \
                    (player.points > new_knapsack[i][alone_formation][1]):
                new_knapsack[i][alone_formation] = ([player], player.points, player.uncertainty)

            for formation, v in knapsack[int(4 * (capacity - player.price) + .1)].items():
                if data.EXTRA_STRIKER:
                    if (sum(int(c) for c in formation) == 16) or \
                            (player.pos == 'gk' and formation[0] == '2') or \
                            (player.pos == 'd' and formation[1] == '6') or \
                            (player.pos == 'm' and formation[2] == '6') or \
                            (player.pos == 'st' and formation[3] == '5') or \
                            (player.pos in ('m', 'st') and int(formation[2]) + int(formation[3]) == 10) or \
                            (player.pos in ('d', 'm') and int(formation[1]) + int(formation[2]) == 11) or \
                            (player.pos in ('d', 'st') and int(formation[1]) + int(formation[3]) == 10) or \
                            (player.pos != 'gk' and int(formation[1]) + int(formation[2]) + int(
                                formation[3]) == 14):
                        continue
                else:
                    if (sum(int(c) for c in formation) == 15) or \
                            (player.pos == 'gk' and formation[0] == '2') or \
                            (player.pos == 'd' and formation[1] == '6') or \
                            (player.pos == 'm' and formation[2] == '6') or \
                            (player.pos == 'st' and formation[3] == '4') or \
                            (player.pos in ('m', 'st') and int(formation[2]) + int(formation[3]) == 9) or \
                            (player.pos in ('d', 'm') and int(formation[1]) + int(formation[2]) == 11) or \
                            (player.pos in ('d', 'st') and int(formation[1]) + int(formation[3]) == 9) or \
                            (player.pos != 'gk' and int(formation[1]) + int(formation[2]) + int(formation[3]) == 13):
                        continue

                same_team_count = 0
                for selected_player in v[0]:
                    if player.team == selected_player.team:
                        same_team_count += 1
                if same_team_count == MAX_PLAYERS_FROM_TEAM:
                    continue

                new_formation = [int(c) for c in formation]
                new_formation[['gk', 'd', 'm', 'st'].index(player.pos)] += 1
                new_formation = ''.join(str(n) for n in new_formation)

                if (new_formation not in new_knapsack[i]) or \
                        (v[1] + player.points > new_knapsack[i][new_formation][1]):
                    if v[2] + player.uncertainty <= MAX_UNCERTAINTY:
                        new_knapsack[i][new_formation] = (v[0] + [player], v[1] + player.points, v[2] + player.uncertainty)

        knapsack = new_knapsack.copy()

    for team, v in data.managers_dict.items():
        price, points = v
        print(f'Processing manager of {team}')
        new_knapsack = []
        for i in range(len(knapsack)):
            capacity = i / 4
            new_knapsack.append(knapsack[i].copy())
            if price < capacity + .1:
                for formation, v1 in knapsack[int(4 * (capacity - price) + .1)].items():
                    if data.EXTRA_STRIKER:
                        if sum(int(c) for c in formation) != 16:
                            continue
                    else:
                        if sum(int(c) for c in formation) != 15:
                            continue

                    new_formation = formation + '1'

                    if (new_formation not in new_knapsack[i]) or \
                            (v1[1] + points > new_knapsack[i][new_formation][1]):
                        new_knapsack[i][new_formation] = (v1[0] + [team], v1[1] + points)

        knapsack = new_knapsack.copy()

    max_total_pts = 0
    max_formation = 'None'
    max_i = -1
    for i in range(len(knapsack)):
        for formation, v in knapsack[i].items():
            if not (len(formation) == 5 and formation[-1] == '1'):
                continue

            if v[1] > max_total_pts:
                max_total_pts = v[1]
                max_formation = formation
                max_i = i

    suggested_squad = []
    for player in knapsack[max_i][max_formation][0]:
        suggested_squad.append(player)

    suggested_manager = suggested_squad.pop()

    suggested_squad.sort(key=lambda x: {'gk': 0, 'd': 1, 'm': 2, 'st': 3}[x.pos])
    return suggested_squad, suggested_manager


import os
import shutil

truth_file = "/home/darg2/Desktop/truth_truth_dataset_2.csv"
dataset = "/mnt/671728fd-b9e2-46ed-b18b-9f45f387f63e/turkish_tweets_dataset/turkish_tweets/text"
portion_of_dataset = "/home/darg2/Desktop/portion_dataset"

person = ["Algın Poyraz Arslan", "Hasan Para", "Elgun Jabrayilzade", "Erhan Sezerer"]

users_to_copy = []

with open(truth_file, "r", encoding="utf8") as f:
	for line in f:
		if line.strip().split(",")[0] == person[1]:
			users_to_copy.append(line.strip().split(",")[1])

for user in users_to_copy:
	filename = str(int(user))+".xml"

	text_file_path_src = os.path.join(dataset, filename)
	text_file_path_dest = os.path.join(portion_of_dataset, filename)

	try:
		shutil.copy2(text_file_path_src, text_file_path_dest)
	except:
		print(user)


import requests
import logging
import db_helper
from flask import jsonify, Flask, request
from os import environ
from poi_server import handle_poi_request

class InvalidUsage(Exception):
    status_code = 400

    def __init__(self, message, status_code=None, payload=None):
        Exception.__init__(self)
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        return rv

app = Flask(__name__)
logging.basicConfig(level=logging.DEBUG, format='%(message)s')
log = logging.getLogger(__name__)
log.setLevel(logging.ERROR)

PREFIX = '/api'

auth_headers = {
        'X-Application-Id': environ.get('APP_ID', 'test'),
        'X-Api-Key': environ.get('APP_KEY', 'test'),
        'Accept': 'application/json',
        'Content-type': 'application/json'
    }

engine = db_helper.make_engine(section="docker")
session = db_helper.set_session(engine)

def proxy_to_source(url):
    url = f'https://api.traveltimeapp.com/{url}'
    return url

@app.route(f'{PREFIX}/')
def root():
    return '.'

@app.route(f'{PREFIX}/metrics',  methods=['GET', 'POST'])
def metrics():
    return 'Alive'

@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response

@app.route(f'{PREFIX}/PoiApi/<path:url>', methods=['GET', 'POST'])
def poi(url):
    try:
        if not request.is_json:
            return 'invalid request'
        return handle_poi_request(url, request)
    except Exception as e:
        log.error(e)
        raise InvalidUsage("Bad request", status_code=400)

@app.route(f'{PREFIX}/TravelTimeApi/<path:url>', methods=['GET', 'POST'])
def proxy(url):
    try:
        url = proxy_to_source(url)
        method = requests.post if request.method == 'POST' else requests.get
        resp = method(
            url,
            stream=True,
            data=request.data,
            params=request.args,
            headers=auth_headers
        )
        return resp.content
    except Exception as e:
        log.error(e)


"""Write a function that encrypts a string with a variable rotary cipher.

The function should take in a number and string and shift the string's
characters by that number:

>>> rot_encode(1, 'abcxyz')
'bcdyza'

It should be able to shift characters by any number:

>>> rot_encode(3, 'abcxyz')
'defabc'

It should preserve capitalization, whitespace, and any special characters:

>>> rot_encode(1, 'Wow! This is 100% amazing.')
'Xpx! Uijt jt 100% bnbajoh.'
"""

def rot_encode(shift, txt):
    """Encode `txt` by shifting its characters to the right."""
    print(shift, txt)
    alphabet = ['a', 'b', 'c', 'd', 'e']
    alphabet = 'abcdefg'
    alphabet_upper = 'ABCD'

    #iterate through txt, skipping Upper/symbols/numbers

    # string: "abc" shift 1 = "bcd"
    # shift 2: "cde"
    # shift 3: "dea"
    shift3 = "dea"
    shift = []
    i = 0
    #shift by len(chunk)/3, every time, add to new list
    #when we reach the end of the list/alphabet[-1]
        #add to the beginning/shift[0]

    string = 'ace'
    # result = 'bda'
    # str1 = string[-1] + string[0] + string[1]
    shift = 1
    result = ''
    for x in string:
        # a
        current_index = alphabet.index(x)
        new_index = current_index + shift

        # len(alphabet)
        # new_index == 5
        if new_index > len(alphabet) - 1:
            new_index = new_index - len(alphabet)
        print(x, new_index, alphabet[new_index])
        result+=alphabet[new_index]
    print(result)

    #for n in range(len(alphabet)):
     #   shift.append(alphabet[(i+n)::(i+n+3)])

if __name__ == '__main__':
    import doctest
    if doctest.testmod().failed == 0:
        print('\n✨ ALL TESTS PASSED!\n')


from tkinter import *
# what is Tkinter ?
# in python2 it's Twinter while in python3 it's twinter

canvas = Canvas(width=800, height=600, bg='yellow')
canvas.pack(expand=YES, fill=BOTH)
k = 1
j = 1
for i in range(0,26):
    canvas.create_oval(310 - k,250 - k,310 + k,250 + k, width=1)
    k += j
    j += 0.3

mainloop()

if __name__ == '__main__':
    import turtle
    turtle.title("画圆")
    turtle.setup(800,600,0,0)
    pen=turtle.Turtle()
    pen.color("yellow")
    pen.width(5)
    pen.shape("turtle")
    pen.speed(1)
    pen.circle(100)


from locust import HttpUser, task, between, tag
from locust import events
import random
import copy
import re
import json
import uuid
import csv
from datetime import datetime, timedelta
import logging

logger = logging.getLogger(__name__)

class Checkout(HttpUser):
    wait_time = between(.3, 5)

    @events.init.add_listener
    def on_locust_init(environment, **kwargs):
        environment.token_exp = datetime.now()
        host = re.search(r".*\/\/([^\/:]+)", environment.host)[1].lower()

        with open('datafiles/{}/env.json'.format(host), 'r') as f:
            environment.env = json.load(f)
        environment.products = []
        with open('datafiles/{}/products.csv'.format(host), 'r') as csvfile:
            csvreader = csv.reader(csvfile)
            # if header
            # fields = next(csvreader)
            for row in csvreader:
                environment.products.append(row)
        environment.users = []
        with open('datafiles/{}/users.csv'.format(host), 'r') as csvfile:
            csvreader = csv.reader(csvfile)
            # if header
            # fields = next(csvreader)
            for row in csvreader:
                environment.users.append(row)

    def get_token(self):
        if datetime.now() >= self.environment.token_exp:
            self.client.headers = {}
            resp = self.client.post(
                '{}/api/platform/applications/authtickets/oauth'.format(
                    self.environment.env['auth_server']),
                data={
                    "client_id": str(self.environment.env["app_id"]),
                    "client_secret": str(self.environment.env["app_secrete"]),
                    "grant_type": "client"
                },
                name='oauth')
            self.environment.token = resp.json()
            self.environment.token_exp = datetime.now(
            ) + timedelta(seconds=self.environment.token["expires_in"])
        return self.environment.token['access_token']

    def get_or_create_cart(self, user_id):
        resp = self.client.post(
            '/api/commerce/carts/user/{}?responseFields=id'.format(user_id),
            name='get_or_create_cart'
        )
        self.log_on_non_success(resp)
        return resp.json()['id']

    def log_on_non_success(self, resp):
        if (resp.status_code > 400):
            msg = resp.json()
            logger.warning(msg)
            return False
        return True

    def add_product_to_cart(self, product, cart_id):
        body = {
            "product": {
                "productCode": product[0],
                "variationProductCode": product[1],
                "options": [
                    {
                        "attributeFQN": product[2],
                        "value": product[3],
                    }]
            },
            "quantity": 1,
            "fulfillmentMethod": "Ship"
        }
        resp = self.client.post(
            '/api/commerce/carts/{}/items?responseFields=id'.format(
                cart_id),
            json=body,
            name='add_item_to_cart'
        )
        return self.log_on_non_success(resp)

    def create_order_from_cart(self, cart_id):
        resp = self.client.post(
            '/api/commerce/orders?cartId={}&responseFields=id'.format(
                cart_id),
            name='create_order_from_cart'
        )
        self.log_on_non_success(resp)

        order_id = resp.json()['id']
        return order_id

    def set_fulfillment(self, order_id, user):
        address = random.choice(self.environment.env["addresses"])
        body = {
            "fulfillmentContact": {
                "address": address,
                "orderId": order_id,
                "firstName": "test",
                "lastNameOrSurname": "user",
                "email": user[1],
                "phoneNumbers": {
                    "home": "5555551212"
                }
            },
            "shippingMethodCode": "flat"
        }

        resp = self.client.put(
            '/api/commerce/orders/{}/fulfillmentinfo?responseFields=id'.format(
                order_id),
            json=body,
            name='set_fulfillment_info')
        self.log_on_non_success(resp)

    def set_payment(self, order_id, user):
        body = {
            "currencyCode": "USD",
            "newBillingInfo": {
                "check": {
                    "nameOnCheck": "bing bong",
                    "routingNumber": "123",
                    "checkNumber": "123"
                },
                "card": {
                    "isSavedCard": False
                },
                "paymentWorkflow": "Mozu",
                "usingSavedCard": False,
                "paymentType": "Check",
                "isSameBillingShippingAddress": True
            }
        }

        resp = self.client.post(
            '/api/commerce/orders/{}/payments/actions?responseFields=id'.format(
                order_id),
            json=body,
            name='set_payment_info')
        self.log_on_non_success(resp)

    def create_customer(self, order_id, user):
        body = {
            "emailAddress": user[1],
            "userName": user[1],
            "firstName": user[1].split('.')[0],
            "lastName": user[1].split('.')[-1],
            "userId": user[0],
            "isActive": True,
            "accountType": "B2C"
        }
        resp = self.client.post(
            '/api/commerce/customer/accounts?responseFields=id',
            json=body,
            name='create_user')
        self.log_on_non_success(resp)
        return resp.json()['id']

    def add_customer_to_order(self, order_id, customer_id):
        body = self.client.get('/api/commerce/orders/{}?responseFields=fulfillmentInfo,email,userId'.format(
            order_id),
            name='get_order').json()
        body['customerAccountId'] = customer_id

        resp = self.client.put(
            '/api/commerce/orders/{}?responseFields=id'.format(
                order_id),
            json=body,
            name='update_order')
        self.log_on_non_success(resp)
        return resp.json()['id']

    def submit_order(self, order_id, user):
        body = {
            "actionName": "SubmitOrder"
        }
        resp = self.client.post(
            '/api/commerce/orders/{}/actions?responseFields=id'.format(
                order_id),
            json=body,
            name='submit_order')
        self.log_on_non_success(resp)

    # @tag('auth_user')
    # @task(5)
    # def auth_user(self):
    #     token = self.get_token()
    #     self.client.headers.update(
    #         {'Authorization': 'Bearer {}'.format(token)})
    #     user = random.choice(
    #         self.environment.users)
    #     cart_id = self.get_or_create_cart(user[0])
    #     for x in range(0, 5):
    #         product = random.choice(
    #             self.environment.products)
    #         self.add_product_to_cart(product, cart_id)
    #     order_id = self.create_order_from_cart(cart_id)
    #     self.set_fulfillment(order_id, user)
    #     self.set_payment(order_id, user)
    #     self.submit_order(order_id, user)

    @ tag('anon_user')
    @ task(5)
    def anaon_user(self):
        token = self.get_token()
        self.client.headers.update(
            {'Authorization': 'Bearer {}'.format(token)})
        user_id = str(uuid.uuid4()).replace('-', '')
        user_email = 'test.user{}@test.com'.format(
            random.randrange(1, 1000000000, 1))
        user = [user_id, user_email]
        cart_id = self.get_or_create_cart(user[0])
        for x in range(0, 5):
            product = random.choice(
                self.environment.products)
            self.add_product_to_cart(product, cart_id)
        order_id = self.create_order_from_cart(cart_id)
        self.set_fulfillment(order_id, user)
        self.set_payment(order_id, user)
        customer_id = self.create_customer(order_id, user)
        self.add_customer_to_order(order_id, customer_id)
        self.submit_order(order_id, user)


import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

dataframe = pd.read_csv('input/data.csv')

#Remove columns we don't care about
dataframe = dataframe.drop(["index", "price", "sq_price"], axis=1 )

dataframe = dataframe[0:15]
dataframe.loc[:, ("y1")] = [1, 1, 1, 0, 0, 1, 0, 1, 1, 1,0,0,0,1,1]

dataframe.loc[:, ("y2")] = dataframe["y1"] == 0
dataframe.loc[:, ("y2")] = dataframe["y2"].astype(int)

inputX = dataframe.loc[: , ['area', 'bathrooms']].as_matrix()
inputY = dataframe.loc[:, ["y1", "y2"]].as_matrix()

#Parameters
learning_rate = 0.00001
training_epochs = 2000
display_steps = 50
n_samples = inputY.size

# Okay TensorFlow, we'll feed you an array of examples. Each example will
# be an array of two float values (area, and number of bathrooms).
# "None" means we can feed you any number of examples

x = tf.placeholder(tf.float32, [None, 2])
W = tf.Variable(tf.zeros([2, 2]))
b = tf.Variable(tf.zeros([2]))

y_values = tf.add(tf.matmul(x,W),b)

## Now converting it into proabilities
y = tf.nn.softmax(y_values)

# feed in a matrix of labels
y_ = tf.placeholder(tf.float32, [None,2])

# Cost Function
cost = tf.reduce_sum(tf.pow(y_ - y, 2)) / (2*n_samples)

# Gradient Descent
optimizier = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

#Initialize variables and tensorflow session
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

for i in range (training_epochs):
    sess.run(optimizier, feed_dict= {x: inputX, y_: inputY})

    # Display logs per epoch step
    if (i)  % display_steps == 0:
        cc = sess.run(cost, feed_dict={x: inputX, y_: inputY})
        print("Training step:", '%04d' % (i), "Cost: :", "{:.9f}".format(cc) )

print("Optimization Done!")
training_cost = sess.run(cost, feed_dict={x: inputX, y_: inputY})
print ("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')

print(sess.run(y, feed_dict={x: inputX}))


import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda, Compose

#1. download train & test data
training_data = datasets.FashionMNIST(root='data', train=True, download=True, transform=ToTensor())
test_data = datasets.FashionMNIST(root='data', train=False, download=True, transform=ToTensor())

# initializing dataloader
batch_size = 64

train_dataloader = DataLoader(training_data, batch_size=batch_size)
test_dataloader = DataLoader(test_data, batch_size=batch_size)

for X, y in test_dataloader:
    print("Shape of X [N, C, H, W]: ", X.shape)
    print("Shape of y: ", y.shape, y.dtype)
    break

#2. Modeling
# set GPU or CPU
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using {device} device")

# defines a class in which nn.Module is inherited.
class NeuralNetwork(nn.Module):
    def __init__(self):
        super(NeuralNetwork, self).__init__()
        self.flatten = nn.Flatten()
        self.linear_relu_stack = nn.Sequential(nn.Linear(28*28, 512), nn.ReLU(),
                                               nn.Linear(512, 512), nn.ReLU(),
                                               nn.Linear(512, 10))
    def forward(self, x):
        x = self.flatten(x)
        logits = self.linear_relu_stack(x)
        return logits

model = NeuralNetwork().to(device)
print(model)

#3. Optimizing model parameters.
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)

def tutorial_train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader)
    for batch, (X, y) in enumerate(dataloader):
        X, y = X.to(device), y.to(device)

        # calculating loss
        pred = model(X)
        loss = loss_fn(pred, y)

        # backward
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if batch % 100 == 0:
            loss, current = loss.item(), batch * len(X)
            print(f"loss:\t{loss:>7f}\t[{current:>5d}/{size:>5d}]")

def tutorial_test(dataloader, model, loss_fn):
    size = len(dataloader)
    num_batches = len(dataloader)
    model.eval()
    test_loss, correct = 0, 0
    with torch.no_grad():
        for X, y in dataloader:
            X, y = X.to(device), y.to(device)
            pred = model(X)
            test_loss += loss_fn(pred, y).item()
            correct += (pred.argmax(1) == y).type(torch.float).sum().item()
    test_loss /= num_batches
    correct /= size
    print(f"Test Error:\n Accuracy:\t{(100 * correct):>0.1f}%, Avg loss:\t{test_loss:>8f}\n")

epochs = 5
for t in range(epochs):
    print(f"Epoch {t+1}\n------------------------------------")
    tutorial_train(train_dataloader, model, loss_fn, optimizer)
    tutorial_test(test_dataloader, model, loss_fn)
print("Done!")

#4. Model save
torch.save(model.state_dict(), "model.pth")
print("Saved PyTorch Model State to model.pth")

#5. Model load
model = NeuralNetwork()
model.load_state_dict(torch.load("model.pth"))

#6. Predict
classes = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat",
           "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"]

model.eval()
x, y = test_data[0][0], test_data[0][1]
with torch.no_grad():
    pred = model(x)
    predicted, actual = classes[pred[0].argmax(0)], classes[y]
    print(f"Predicted:\t{predicted}", f"Actual:\t{actual}")