from databricks.feature_store.client import FeatureStoreClient
from databricks.feature_store.constants import MERGE
from pyspark.sql import DataFrame
from pyspark.sql.streaming import StreamingQuery
from functools import wraps
from typing import List, Dict, Union, Any

def feature_table(func):  # noqa: D212,D400,D415
    """
    .. note::

       Experimental: This decorator may change or be
       removed in a future release without warning.

    The ``@feature_table`` decorator specifies that a
    function is used to generate feature data.
    Functions decorated with ``@feature_table`` must return a
    single :class:`DataFrame <pyspark.sql.DataFrame>`, which will be
    written to Feature Store. For example:

    .. code-block:: python

       from databricks.feature_store import feature_table

       @feature_table
       def compute_customer_features(data):
           '''Feature computation function that takes raw
              data and returns a DataFrame of features.'''
           return (data.groupBy('cid')
             .agg(count('*').alias('num_purchases'))
           )

    A function that is decorated with the ``@feature_table`` decorator will gain these function attributes:

    .. function:: compute_and_write(input: Dict[str, Any], feature_table_name: str, mode: str = 'merge') -> pyspark.sql.dataframe.DataFrame

       .. note::

          Experimental: This function may change or be removed in
          a future release without warning.

       Calls the decorated function using the provided ``input``, then writes
       the output :class:`DataFrame <pyspark.sql.DataFrame>` to the feature table specified by ``feature_table_name``.

       .. code-block:: python
          :caption: Example:

          compute_customer_features.compute_and_write(
              input={
                  'data': data,
              },
              feature_table_name='recommender_system.customer_features',
              mode='merge'
          )

       :param input: If ``input`` is not a dictionary,
          it is passed to the decorated function as the first positional argument.
          If ``input`` is a dictionary, the contents are unpacked and passed to
          the decorated function as keyword arguments.
       :param feature_table_name: A feature table name of the form
          ``<database_name>.<table_name>``, for example ``dev.user_features``.
          Raises exception if this feature table does not exist.
       :param mode: Two supported write modes: ``"overwrite"`` updates the whole table,
          while ``"merge"`` will upsert the rows in ``df`` into the feature table.
       :return: :class:`DataFrame <pyspark.sql.DataFrame>` (``df``) containing feature values.

    .. function:: compute_and_write_streaming(input: Dict[str, Any], feature_table_name: str, checkpoint_location: Optional[str] = None, trigger: Dict[str, Any] = {'processingTime': '5 minutes'}) -> pyspark.sql.streaming.StreamingQuery

       .. note::

          Experimental: This function may change or be removed in
          a future release without warning.

       Calls the decorated function using the provided input,
       then streams the output :class:`DataFrame <pyspark.sql.DataFrame>` to the
       feature table specified by ``feature_table_name``.

       .. code-block:: python
          :caption: Example:

          compute_customer_features.compute_and_write_streaming(
              input={
                  'data': data,
              },
              feature_table_name='recommender_system.customer_features',
          )

       :param input: If ``input`` is not a dictionary,
          it is passed to the decorated function as the first positional argument.
          If ``input`` is a dictionary, the contents are unpacked and passed
          to the decorated function as keyword arguments.
       :param feature_table_name: A feature table name of the form ``<database_name>.<table_name>``,
          for example ``dev.user_features``.
       :param checkpoint_location: Sets the Structured Streaming ``checkpointLocation`` option.
          By setting a ``checkpoint_location``, Spark Structured Streaming will store progress
          information and intermediate state, enabling recovery after failures.
          This parameter is only supported when the argument ``df``
          is a streaming :class:`DataFrame <pyspark.sql.DataFrame>`.
       :param trigger: ``trigger`` defines the timing of stream data processing,
          the dictionary will be unpacked and passed to :meth:`DataStreamWriter.trigger <pyspark.sql.streaming.DataStreamWriter.trigger>` as arguments.
          For example, ``trigger={'once': True}`` will result in a call to ``DataStreamWriter.trigger(once=True)``.
       :return: A PySpark :class:`StreamingQuery <pyspark.sql.streaming.StreamingQuery>`.
    """
    fs = FeatureStoreClient()

    @wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)

    def compute_and_write(
        input: Dict[str, Any], feature_table_name: str, mode: str = MERGE
    ) -> DataFrame:
        """Compute and write to a df."""
        df = func(**input) if isinstance(input, dict) else func(input)
        fs.write_table(
            feature_table_name,
            df,
            mode,
        )
        return df

    def compute_and_write_streaming(
        input: Dict[str, Any],
        feature_table_name: str,
        checkpoint_location: Union[str, None] = None,
        trigger: Dict[str, Any] = FeatureStoreClient._DEFAULT_WRITE_STREAM_TRIGGER,
    ) -> StreamingQuery:
        """Compute and write a streaming df."""
        df = func(**input) if isinstance(input, dict) else func(input)
        if not df.isStreaming:
            raise ValueError(
                "compute_and_write_streaming expects the decorated function to return a streaming DataFrame, "
                "received a non-streaming DataFrame."
            )
        streaming_query = fs.write_table(
            feature_table_name,
            df,
            MERGE,
            checkpoint_location=checkpoint_location,
            trigger=trigger,
        )
        return streaming_query

    wrapper.compute_and_write = compute_and_write
    wrapper.compute_and_write_streaming = compute_and_write_streaming
    return wrapper


from collections import deque

size = int(input())
array = list(map(int, input().split()))
leftSum, rightSum= sum(array[:size]), sum(array[size:])
array = deque(array)
found = False

for index in range(size):
    equal = (rightSum == leftSum)
    if equal:
        num = array.popleft()
        array.append(num)
        rightSum = rightSum - array[size - 1] + array[-1]
        leftSum = leftSum + array[size - 1] - array[-1]

    else:
        found = True
        print(*list(array))
        break

if not found:
    print(-1)


#
# @lc app=leetcode.cn id=102 lang=python
#
# [102] 二叉树的层序遍历
#

# @lc code=start
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

# 1. BFS
# 2. DFS（记录当前是哪一层）
# 3. 迭代---BFS

#DFS
# class Solution(object):
#     def levelOrder(self, root):
#         """
#         :type root: TreeNode
#         :rtype: List[List[int]]
#         """
#         if not root:
#             return []
#         res = []
#         def DFS(level, r, res):
#             if len(res) == level:
#                 res.append([])
#             res[level].append(r.val)
#             if r.left:
#                 DFS(level + 1, r.left, res)
#             if r.right:
#                 DFS(level + 1, r.right, res)
#         DFS(0, root, res)
#         return res

#BFS
class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []
        res = []
        queue = [root]
        while queue:
            size = len(queue)
            tmp = []
            for _ in range(size):
                node = queue.pop(0)
                tmp.append(node.val)
 #               print(tmp)
                if node.left:
                    queue.append(node.left)

                if node.right:
                    queue.append(node.right)
            res.append(tmp)
        return res

# @lc code=end

102.二叉树的层序遍历.py


from typing import List

class Solution:
    def countSmaller(self, nums: List[int]) -> List[int]:
        n = len(nums)
        count = [0] * n
        indices = list(range(n))
        # print(indices)
        def merge(l, mid, r):
            # print('lmidr:', l, mid, r)
            # print('start', indices[l:r+1])
            tmp = indices[l:mid+1]
            start_1, start_2 = 0, mid + 1
            i = l
            # print(tmp, indices[start_2: r+1])
            while start_1 <= (mid - l) and start_2 <= r:
                if nums[tmp[start_1]] <= nums[indices[start_2]]:
                    indices[i] = tmp[start_1]
                    count[indices[i]] += start_2 - mid - 1
                    start_1 += 1
                else:
                    indices[i] = indices[start_2]
                    start_2 += 1
                i += 1
            # print('middle', indices)
            # print('ssi:', start_1, start_2, i)
            while start_1 <= (mid - l):
                indices[i] = tmp[start_1]
                count[indices[i]] += start_2 - mid - 1
                start_1 += 1
                i += 1
            # print('end', indices[l:r+1])
        def merge_sort(l, r):
            if l >= r:
                return
            mid = (l + r) // 2
            merge_sort(l, mid)
            merge_sort(mid + 1, r)
            merge(l, mid, r)

        merge_sort(0, n - 1)
        # print(indices)
        return count

if __name__ == "__main__":
    s = Solution()
    l = [1, 2, 0]
    print(s.countSmaller(l))


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

def get_z(x, y):
    return np.sin(np.sqrt(x ** 2 + y ** 2))

x_1 = np.linspace(-6, 6, 30)
y_1 = np.linspace(-6, 6, 30)
x_1, y_1 = np.meshgrid(x_1, y_1)
z = get_z(x_1, y_1)
fig = plt.figure(figsize=(6, 6), dpi=300)
axes = fig.add_axes([0, 0, 0.8, 0.8], projection='3d')
axes.view_init(45, 55)
# axes.contour3D(x_1,y_1,z,90,cmap='Blues')
# axes.plot_wireframe(x_1,y_1,z,cmap='Reds')
axes.plot_surface(x_1, y_1, z, cmap='Greys', edgecolor='k', rstride=1, cstride=1)
axes.set_xlabel('X', color='blue')
axes.set_ylabel('Y', color='blue')
axes.set_zlabel('Z', color='blue')
axes.set_facecolor('green')
axes.set_title('SURFACE-PLOT', color='#001e2b')


import os

from imgui_bundle import imgui_md
from imgui_bundle import immapp
from imgui_bundle.demos_python.demo_utils.api_demos import GuiFunction
from imgui_bundle.demos_python.demo_utils.demo_app_table import DemoAppTable, DemoApp

DOC = """
# HelloImGui and ImmApp

* [HelloImGui](https://github.com/pthom/hello_imgui) is a library based on ImGui that enables to easily create applications with ImGui.
  Link to the [API documentation](https://github.com/pthom/hello_imgui/blob/master/src/hello_imgui/hello_imgui_api.md). Docking layout [documentation](https://github.com/pthom/hello_imgui/blob/master/src/hello_imgui/hello_imgui_api.md#docking)
* [ImApp](https://github.com/pthom/imgui_bundle/blob/dev/bindings/imgui_bundle/immapp/immapp_cpp.pyi) (aka "Immediate App", a submodule of ImGuiBundle) is a thin extension of HelloImGui that enables to easily initialize the ImGuiBundle addons that require additional setup at startup.

## Demo applications (*scroll with the mouse wheel below for more demos*)
    """

# This returns a closure function that will later be invoked to run the app
def make_gui() -> GuiFunction:
    demo_apps = [
        DemoApp(
            "demo_hello_world",
            "Hello world demo: how to create an app with ImmApp in a few lines.",
        ),
        DemoApp(
            "demo_assets_addons",
            "How to use assets, and how to use add-ons (Markdown and ImPlot)",
        ),
        DemoApp(
            "demo_docking",
            "How to build complex applications layouts, with dockable panels,that can even become independent windows. How to customize the theme.",
        ),
        DemoApp("demo_custom_background", "How to use a custom 3D background"),
        DemoApp("demo_custom_font", "How to load custom fonts"),
        DemoApp(
            "demo_powersave",
            "How to have smooth animations, and how spare the CPU when idling",
        ),
        DemoApp(
            "demo_testengine",
            "How to use ImGui Test Engine to test and automate your application",
        ),
        DemoApp(
            "demo_command_palette",
            "a Sublime Text or VSCode style command palette in ImGui",
        ),
        DemoApp(
            "demo_parametric_curve",
            "Illustration of the Immediate GUI paradigm, with a simple parametric curve",
        ),
        DemoApp("haiku_implot_heart", "Share some love for ImGui and ImPlot"),
        DemoApp(
            "imgui_example_glfw_opengl3",
            "Python translation of the [GLFW+OpenGL3 example](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_opengl3/main.cpp) from Dear ImGui. Demonstrates how to port from C++ to Python.",
        ),
        DemoApp(
            "imgui_example_glfw_opengl2",
            "Python translation of the [GLFW+OpenGL2 example](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_opengl2/main.cpp) from Dear ImGui",
        ),
        DemoApp(
            "imgui_example_sdl2_opengl3",
            "Python translation of the [SDL2+OpenGL3 example](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_opengl3/main.cpp) from Dear ImGui",
        ),
        DemoApp("demo_drag_and_drop", "Drag and drop demo"),
        DemoApp(
            "demo_implot_markdown",
            "How to quickly run an app that uses implot and/or markdown with ImmApp",
        ),
    ]

    this_dir = os.path.dirname(__file__)
    demo_python_folder = this_dir + "/demos_immapp"
    demo_cpp_folder = os.path.abspath(
        demo_python_folder + "/../../demos_cpp/demos_immapp"
    )
    demo_app_table = DemoAppTable(demo_apps, demo_python_folder, demo_cpp_folder)

    def gui():
        nonlocal demo_apps
        imgui_md.render(DOC)
        demo_app_table.gui()

    return gui

@immapp.static(gui=None)
def demo_gui():
    static = demo_gui
    if static.gui is None:
        static.gui = make_gui()
    static.gui()

def main():
    immapp.run(demo_gui, with_markdown=True, window_size=(1000, 800))  # type: ignore

if __name__ == "__main__":
    main()


import math
import glob
import os.path
import json
#Consumer Amount and Factory Amount
print("=== INPUT SELECTION ===")
print("1 for population")
print("2 for umits")
print("3 for most recent country file")
inputtype = input("Selection: ")

# Determine value input method

# Calculate value from population
if inputtype == "1":
    population = int(input("Input population (to nearest million)"))
    consumeamt = population

# Use manual value from user
elif inputtype == "2":
    consumeamt = float(input("How many Consumer Goods do you need?"))
    population = consumeamt

# Use dictionary element from other python scraper
elif inputtype == "3":
    # Find Nation JSON File
    folder_path = r'C:\Users\Cameron Labes\Documents\Programming\fandom_scraper-master\data'
    file_type = r'\*json'
    files = glob.glob(folder_path + file_type)
    natfile = max(files, key=os.path.getctime)
    print(natfile)

    # Extract Dictionary from JSON file
    with open(natfile, "r") as file:
        natdata = json.load(file)
    print(natdata)
    consumeamt = natdata['Consumers Required to Upkeep']

    # Conversion for calculation
    consumeamt = float(consumeamt)
    population = consumeamt

# Round variable to account for decimals and add overhead
if consumeamt < 40:
 consumeamt = 40
consumefac = float(round(consumeamt / 40))

#Ingrediant Amount and Factory Amount
fertamt = consumefac * 2.5
motoramt = consumefac * 2.5
elecamt = consumefac * 3
fertfac = math.ceil(fertamt / 12)
motorfac = math.ceil(motoramt / 6)
elecfac = math.ceil(elecamt / 16)
steelamt = motorfac
steelfac = math.ceil(steelamt / 3)

#Resource Amount
phosphateamt = math.ceil(fertfac * 3.5)
titaniumamt = math.ceil(steelfac * 0.2)
ironamt = math.ceil(steelfac * 4)
tugstenamt = math.ceil(motorfac * 2)
goldamt = math.ceil(elecfac * 2)
copperamt = math.ceil(elecfac * 2)

# Print result
print("For %d Million Population, you will need %d Consumer Goods which requires:" % (population, population))
print("=====================Factories=====================")
print("%d consumer factories." % (consumefac))
print("%d ferterlizer factories." % (fertfac))
print("%d motor factories." % (motorfac))
print("%d steel factories." % (steelfac))
print("%d electronic factories." % (elecfac))
print("===================Raw Resources===================")
print("%d units of phosphate." % (phosphateamt))
print("%d units of titanium." % (titaniumamt))
print("%d units of iron." % (ironamt))
print("%d units of tugsten." % (tugstenamt))
print("%d units of gold." % (goldamt))
print("%d units of copper." % (copperamt))
input('Press ENTER to exit')


from model.book import Book
from model.client import Client
from model.exception import LibraryException

class Command:

    Arguments_list = {
        "addbook":4,
        "addclient":3,
        "removebook":2,
        "removeclient":2,
        "updateid":3,
        "updatename":3,
        "updatetitle":3,
        "updateauthor":3,
        "updatedescription":3,
        "rentbook": 3,
        "returnbook": 3,
        "list": 1,
        "exit": 1,
        "delete": 1,
        "listbooks": 1,
        "listclients": 1,
        "listloans": 1,
        "save": 1,
        "help": 1
    }
    def __init__(self, stringInput):
        self._args = stringInput.split('|')
        self._args[0] = self._args[0].lower()
        if not self._args[0] in Command.Arguments_list.keys():
            raise LibraryException("Error - Unknown command!")
        if len(self._args) != Command.Arguments_list[self._args[0]]:
            raise LibraryException("Error - Argument size does not match!")
        for arg in self._args:
            if arg == "":
                raise LibraryException("Error - Empty parameters!")

    def __eq__(self, other):
        return (isinstance(other, self.__class__)
            and self.__dict__ == other.__dict__)

    def getArgs(self):
        return self._args

    def getArgsSize(self):
        return len(self._args)

    def getArg(self, pos):
        if pos >= self.getArgsSize():
            raise LibraryException("Error - Not enough parameters.")
        return self._args[pos]

    def toAddBook(self, id):
        return Book(id, self.getArg(1), self.getArg(2), self.getArg(3))

    def toAddClient(self):
        try:
            return Client(int(self.getArg(1)), self.getArg(2))
        except ValueError as ve:
            raise LibraryException("Client Id should be an integer.")

    def toRemoveClient(self):
        try:
            return int(self.getArg(1))
        except ValueError as ve:
            raise LibraryException("Client Id should be an integer.")

    def toRemoveBook(self):
        try:
            return int(self.getArg(1))
        except ValueError as ve:
            raise LibraryException("Book number should be an integer.")

    def toUpdateId(self):
        try:
            return (int(self.getArg(1)), int(self.getArg(2)))
        except ValueError:
            raise LibraryException("Client Id should be an integer.")

    def toUpdateName(self):
        try:
            return (int(self.getArg(1)), self.getArg(2))
        except ValueError:
            raise LibraryException("Client Id should be an integer.")

    def toUpdateTitle(self):
        try:
            return (int(self.getArg(1)), self.getArg(2))
        except ValueError:
            raise LibraryException("Book ID should be an integer.")

    def toUpdateDescription(self):
        try:
            return (int(self.getArg(1)), self.getArg(2))
        except ValueError:
            raise LibraryException("Book ID should be an integer.")

    def toUpdateAuthor(self):
        try:
            return (int(self.getArg(1)), self.getArg(2))
        except ValueError:
            raise LibraryException("Book ID should be an integer.")


print("""
*****************************

ATM MAKİNESİ

İşlemler:

1. Bakiye sorgulama

2. Para Yatırma

3. Para Çekme

(Programdan çıkmak için Q'ya basın)

*****************************""")

bakiye = 1000

while True:
    işlem = input("\nİşlemi seçiniz: ")

    if( işlem == "q" or "Q"):
        print("Görüşürüz..")
        break

    elif(işlem == "1"):
        print("\nBakiyeniz: {}₺'dir".format(bakiye))

    elif (işlem == "2"):
        miktar = int(input("\nLütfen yatırılacak m  iktarı girin: "))

        bakiye += miktar

        print("\nBakiyeniz artık {}₺'dir.".format(bakiye))

    elif(işlem == "3"):
        miktar = int(input("\nLütfen çekilecek miktarı girin: "))

        if(bakiye - miktar < 0):
            print("\nParayı çekemezsiniz, lütfen bakiyenizden fazla para çekme talebi oluşturmayın.")
            continue

        bakiye -= miktar

        print("\nBakiyeniz artık {}₺'dir..".format(bakiye))

    else:
        print("\n\nLütfen geçerli bir işlem giriniz...\n")


def shortestPath(grid, sr, sc, tr, tc):
    p = [(sr, sc, [])]

    while p:
        (i, j, path) = p.pop(0)
        if (i, j) == (tr, tc):
            path.append((i, j))
            return path

        newPath = path.copy()
        newPath.append((i, j))
        if get(grid, i + 1, j, path):
            p.append((i + 1, j, newPath))

        if get(grid, i - 1, j, path):
            p.append((i - 1, j, newPath))

        if get(grid, i, j + 1, path):
            p.append((i, j + 1, newPath))

        if get(grid, i, j - 1, path):
            p.append((i, j - 1, newPath))

    return []

def get(a, i, j, path):
    if 0 <= i < len(a) and 0 <= j < len(a[0]) and not (i, j) in path:
        return a[i][j]
    else:
        return 0

grid = [[1, 1, 1, 1], [1, 1, 0, 1], [1, 0, 1, 1]]
sr = 0
sc = 0
tr = 2
tc = 0
print(shortestPath(grid, sr, sc, tr, tc))


# coding: utf-8
from __future__ import print_function
import tensorflow as tf
import numpy as np
import time
import os

class Config(object):
    """RNN配置参数"""
    file_name = 'mlp'  #保存模型文件

    train_keep_prob = 0.8  # dropout保留比例
    learning_rate = 0.001  # 学习率

    batch_size = 64  # 每批训练大小
    max_steps = 2000  # 总迭代batch数

    log_every_n = 20  # 每多少轮输出一次结果
    save_every_n = 20  # 每多少轮校验模型并保存

class Model(object):

    def __init__(self, config, variable_size):
        self.config = config
        self.variable_size = variable_size

        # 待输入的数据
        self.X = tf.placeholder(dtype=tf.float32, shape=[None, self.variable_size])  # 20
        self.Y = tf.placeholder(dtype=tf.int32, shape=[None])
        self.keep_prob = tf.placeholder(tf.float32, name='keep_prob')

        # 全局变量
        self.global_step = tf.Variable(0, trainable=False, name="global_step")

        # Ann模型
        self.Ann()

        # 初始化session
        self.saver = tf.train.Saver()
        self.session = tf.Session()
        self.session.run(tf.global_variables_initializer())

    def Ann(self):
        """Ann模型"""

        # 词嵌入层
        Y_hot = tf.one_hot(self.Y, depth=2)  # 独热编码[1,2,3] depth=5 --> [[0,1,0,0,0],[0,0,1,0,0],[0,0,0,1,0]]，此时的输入节点个数为num_classes

        with tf.name_scope("ann"):
            # 定义ann网络
            w1 = tf.Variable(tf.random_normal([self.variable_size,  512], stddev=0.5))
            b1 = tf.Variable(tf.random_normal([512]))
            output = tf.matmul(self.X, w1) + b1

            # output = tf.nn.dropout(output, keep_prob=self.keep_prob)

            w2 = tf.Variable(tf.random_normal([512, 1024], stddev=.5))
            b2 = tf.Variable(tf.random_normal([1024]))
            output = tf.nn.softmax(tf.matmul(output, w2) + b2)

            w3 = tf.Variable(tf.random_normal([1024, 2], stddev=.5))
            b3 = tf.Variable(tf.random_normal([2]))
            output = tf.nn.softmax(tf.matmul(output, w3) + b3)

        with tf.name_scope("accuracy"):
            # 准确率
            prediction = tf.equal(tf.argmax(output, 1), tf.argmax(Y_hot, 1))
            self.accuracy = tf.reduce_mean(tf.cast(prediction, dtype=tf.float32))

        with tf.name_scope("optimize"):
            # 损失函数，交叉熵
            self.mean_loss = tf.reduce_mean(tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(labels=Y_hot, logits=output)))
            self.optim = tf.train.AdamOptimizer(learning_rate=self.config.learning_rate).minimize(self.mean_loss, global_step=self.global_step)

    def load(self, checkpoint):
        self.saver.restore(self.session, checkpoint)
        print('Restored from: {}'.format(checkpoint))

    def train(self, generate_batch, x_test, y_test ):
        with self.session as sess:
            for x_batch, y_batch in generate_batch:
                # _,test_accuracy,meanloss = self.session.run([self.optim,self.accuracy,self.mean_loss], feed_dict={self.X: x_batch, self.Y: y_batch, self.keep_prob: 1.0})
                self.optim.run(feed_dict={self.X: x_batch, self.Y: y_batch, self.keep_prob: 0.7})
                if self.global_step.eval() % self.config.log_every_n == 0:
                    mean_loss = self.mean_loss.eval(feed_dict={self.X: x_batch, self.Y: y_batch, self.keep_prob: 1.0})
                    print("step %d, training accuracy %g" % (self.global_step.eval(), mean_loss))

                if self.global_step.eval() >= self.config.max_steps:
                    # self.saver.save(sess, os.path.join(model_path, 'model'))
                    test_accuracy = self.session.run(self.accuracy, feed_dict={self.X: x_test, self.Y: y_test, self.keep_prob: 1.0})
                    print(" test accuracy :", test_accuracy)
                    break


import sys
input=sys.stdin.readline

n=int(input())

org_stack=[int(input()) for _ in range(n)]

sorted_org_stack=sorted(org_stack)

stack=[]
make_stack=[]
answer=[]
idx=0
for i in sorted_org_stack:
    stack.append(i)
    answer.append('+')
    while True:
        if not stack:
            break
        if stack[-1]==org_stack[idx]:
            make_stack.append(stack.pop())
            idx+=1
            answer.append('-')
        else:
            break

if org_stack == make_stack:
    for ans in answer:
        print(ans)
else:
    print('NO')


import os
from datetime import datetime, timedelta
import airflow
from airflow.utils import trigger_rule
from airflow.operators import bash_operator

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'email': None,
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 0,
    'retry_delay': timedelta(minutes=5),
    'dagrun_timeout' : timedelta(minutes=60),
}

project_id = os.environ['ENV_PROJECT_ID']

params_list = {
    "project_id" : project_id
    }

with airflow.DAG('sample-rideshare-website',
                 default_args=default_args,
                 start_date=datetime(2021, 1, 1),
                 # Add the Composer "Data" directory which will hold the SQL/Bash scripts for deployment
                 template_searchpath=['/home/airflow/gcs/data'],
                 # Not scheduled, trigger only
                 schedule_interval=None) as dag:

    # NOTE: The service account of the Composer worker node must have access to run these commands

    # Deploys an App Engine website
    deploy_website = bash_operator.BashOperator(
          task_id='deploy_website',
          bash_command='bash_deploy_rideshare_website.sh',
          params=params_list,
          dag=dag
      )

    # DAG Graph
    deploy_website

# [END dag]


import os

import numpy as np
import tensorflow.keras.backend as ktf
from matplotlib import pyplot as plt
from tensorflow.keras.models import load_model

from utils.dataloader import SegmentedDataLoader

class NodulePlot:
    def __init__(self, model_path, save_path):
        self.dataloader = SegmentedDataLoader(subset_number=5, img_res=(32, 32, 32))
        self.generator = load_model(os.path.join(model_path, "G_model.h5"),
                                    custom_objects={'ktf': ktf})
        self.save_path = save_path
        if not os.path.exists(save_path):
            os.makedirs(save_path)

    def plot(self, filename):
        r, c = 3, 3

        imgs_A, imgs_B = self.dataloader.load_data(batch_size=3)
        fake_A = self.generator.predict([imgs_B])

        gen_imgs = np.concatenate([imgs_B, fake_A, imgs_A])

        # Rescale images 0 - 1
        gen_imgs = 0.5 * gen_imgs + 0.5

        titles = ['Condition', 'Generated', 'Original']
        fig, axs = plt.subplots(r, c + 1)
        cnt = 0
        for i, title in zip(range(r), titles):
            axs[i, 0].text(0.35, 0.5, title)
            axs[i, 0].axis('off')
            for j in range(c):
                axs[i, j + 1].imshow(
                    gen_imgs[cnt].reshape((32, 32, 32))[16, :, :])
                axs[i, j + 1].axis('off')
                cnt += 1
        fig.savefig(os.path.join(self.save_path, filename))
        plt.close()


import argparse
import os
from logic import get_arbitrages

parser = argparse.ArgumentParser(
            prog='ArbitrageFinder',
            description='Finds arbitrages for a certain amount of sports using Odds API!')

parser.add_argument(
    "-k", "--key",
    default=os.environ.get("ODDS_API_KEY"),
    help="The API key of Odds API. Defaults to ODDS_API_KEY in environment."
)
parser.add_argument(
    "-r", "--regions",
    choices=["us", "us2", "eu", "au", "uk"],
    nargs = "+",
    default="us2",
    help="The region (or multiple regions) to be surveyed"
)
parser.add_argument(
    "-m", "--markets",
    choices=["h2h", "spreads", "totals"],
    nargs = "+",
    default="h2h",
    help="The market (or multiple markets) to be surveyed"
)
parser.add_argument(
    "-s", "--numsports",
    type=int,
    default=1,
    help="Number of sports to survey"
)
parser.add_argument(
    "-t", "--threshold",
    type=float,
    default=0.0,
    help="Accounts for percentage losses from vigorish (percentage commission fee from 0 to 1)"
)

args = parser.parse_args()

get_arbitrages(args.key, args.regions, args.markets, args.numsports, args.threshold)


import math

x = [0]
y = [1]
diff = []
dx = 0.02
h = dx
xmax = 0.5

def f(x, y):
    return (math.exp(x) * x - y) / 2

diff.append(f(x[0], y[0]))

def Runge_Kutta(i):
    k1 = h * f(x[i - 1], y[i - 1])
    k2 = h * f(x[i - 1] + h / 2, y[i - 1] + k1 / 2)
    k3 = h * f(x[i - 1] + h / 2, y[i - 1] + k2 / 2)
    k4 = h * f(x[i - 1] + h, y[i - 1] + k3)
    return y[i - 1] + (k1 + 2 * k2 + 2 * k3 + k4) / 6

for i in range(3):  # заполняю 2 и 3 первых значения x, y и f(x,y)
    new_var = Runge_Kutta(len(y))
    y.append(new_var)
    x.append(x[-1] + dx)
    diff.append(f(x[-1], y[-1]))

while x[-1] < xmax:
    x.append(x[-1] + dx)
    subres_y = y[-1] + h / 24 * (55 * diff[-1] - 59 * diff[-2] + 37 * diff[-3] - 9 * diff[-4])
    y.append(subres_y)

for i in range(0, len(x)):
    print(" {0:4.2f} | {1:9.3f}".format(x[i], y[i]))


import os
import shutil
from distutils.dir_util import copy_tree

if __name__ == '__main__':
    oxford_folder = '/data/datasets/oxford'
    sensor = 'tags'
    src_folder = '/data/datasets/oxford-%s' % (sensor)

    filename_list = [f for f in os.listdir(oxford_folder) if os.path.isdir(os.path.join(oxford_folder, f))]
    filename_list = list(set(filename_list))
    filename_list.sort()

    for traversal in filename_list:
        tags_csv = os.path.join(src_folder, traversal, sensor+'.csv')
        dst_folder = os.path.join(oxford_folder, traversal)
        if not os.path.exists(tags_csv):
            print("not exist:")
            print(tags_csv)
        else:
            shutil.copyfile(tags_csv, os.path.join(dst_folder, sensor+'.csv'))


import requests
from dotenv import load_dotenv
from flask import Flask, request
import os

load_dotenv('/mnt/d/Projects/Personal/tera_chat_gpt/.env')
app = Flask(__name__)

BOT_TOKEN = os.getenv('BOT_TOKEN')
OPEN_AI = os.getenv('OPEN_AI')

def sendmessage(chatid, message):
    headers = {"Content-Type": "application/json",
               "Authorization": f"Bearer {OPEN_AI}"}
    info = {
        # The model used (you can use gpt-4 if you have access to it)
        "model": "gpt-3.5-turbo",
        "messages": [{"role": "user", "content": message}],
        # Randomness of the result
        "temperature": 0.7,
        "max_tokens": 1024
    }
    post_request = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=info)

    response_api = post_request.json()["choices"][0]["message"]["content"]
    url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
    payload = {
        "text": response_api,
        "chat_id": chatid
    }
    requests.post(url, json=payload)  # This line is added to send the response back to Telegram

@app.route("/", methods=["POST", "GET"])
def index():
    if (request.method == "POST"):
        resp = request.get_json()
        print(resp)
        # We get the content of the message
        msgtext = resp["message"]["text"]
        # We get the id of the chat
        chatid = resp["message"]["chat"]["id"]
        # The message is sent back
        sendmessage(chatid, msgtext)
        return "Done"
    else:
        return "Hello World!"

if __name__ == "__main__":
    port = 5000
    app.run(debug=True, host='0.0.0.0', port=port)

    # send a start-up message
    chat_id = '<your_chat_id>'
    start_message = "Hello, I'm online!"
    sendmessage(chat_id, start_message)


import random as rand
from sgoal.util import permutation
from sgoal.core import pick
from sgoal.core import MAXIMIZE
from sgoal.core import evaluate
from sgoal.binary import flip
from sgoal.binary import complement

############ GABO: Gene Analysis Bitstring Optimization #############
# Gene information
contribution = []
intron = []
separable = []
coding = []

# Initializes the gene information
# D: Bitstring's length (number of genes)
def init(D):
  global intron, coding, separable, contribution
  separable = [True for k in range(D)]
  contribution = [[] for k in range(D)]
  intron = [k for k in range(D)]
  coding = []

# Computes contribution information (relative to a value 1), i.e., some change
# in the f value
# x: A candidate solution
# y: The candidate solution with the k-th bit flipped
# fx: f value of x
# fy: f value of y
# k: Gene's locus
def C(x, y, fx, fy, k):
  global contribution
  if( MAXIMIZE ): c = fx-fy
  else: c = fy-fx
  if(x[k]==0): c = -c
  contribution[k].append(c)
  return c

# Computes the coding complement of a genome.
# The coding complement flips each gene that is considered coding and maintains other genes the same
# x: Genome to be complemented in the coding-like genes
def coding_complement(x):
  global coding
  N = len(coding)
  if(N>0):
    y = x.copy()
    for i in coding:
      y[i] = 1-y[i]
  else:
    y = complement(x)
  return y

# Checks all the information about the gene's contribution to get the higher one,
# determines the best allele (0, 1, or None) for the gene
# k: Locus (gene's position)
# b: Current value of the gene (allele)
def best_allele(k, b):
  global contribution
  a, c = b, 0
  for ci in contribution[k]:
    if(ci>c): a, c = 1, ci
    elif(-ci>c): a, c =  0, -ci
  return a

# Creates a genome with its best genes according to gene contribution and return the best between it and the original genome
# f: Function to be optimized
# evals: Maximum number of fitness evaluations
# x: current geneme, used for completing intron-like genes
# fx: Fitness value of the current genome
def genome_best_gene_contribution(f, evals, x, fx):
  if(evals>0):
    y = [best_allele(k, x[k]) for k in range(len(x))]
    fy = evaluate(f,y)
    x, y, fx, fy = pick(x, y, fx, fy)
    evals -= 1
  return x, fx, evals

# Initializes global variables and does an initial gene analysis
# f: Function to be optimized
# evals: Maximum number of fitness evaluations
# x: Current geneme
# fx: Fitness value of the current genome
def ICSplit(f, evals, x, fx):
  global intron, coding, separable, contribution
  P = permutation(len(x))
  for k in P:
    if(evals==0): return x, fx, evals
    y = flip(x,k)
    fy = evaluate(f,y)
    evals -= 1
    x, y, fx, fy = pick(x, y, fx, fy)
    if( C(x, y, fx, fy, k) != 0 ):
      intron.remove(k)
      coding.append(k)
  return genome_best_gene_contribution(f, evals, x, fx)

# Introns only search algorithm
# f: Function to be optimized
# evals: Maximum number of fitness evaluations
# x: initial point
# fx: f value in the x point
def IOSA( f, evals, x, fx):
  global intron
  N = len(intron)
  for i in range(N):
    if(evals==0): return x, fx, evals
    a = rand.randint(0,N-1)
    k = intron[a] # Picks and analyzes one intron-like locus
    y = flip(x,k)
    fy = evaluate(f,y)
    evals -= 1
    x, y, fx, fy = pick(x, y, fx, fy)
    if( C(x, y, fx, fy, k) != 0 ):
      intron.pop(a)
      N-=1
  return x, fx, evals

# Gene characterization algorithm
# genome: An array with each gene information, see Gene class
# f: Function to be optimized
# x: initial point
# fx: f value at point x (if provided)
# evals: Maximum number of fitness evaluations
def COSA( f, evals, x, fx ):
  global coding, separable
  N = len(coding)
  if(N==0 or evals==0): return x, fx, evals

  xc = coding_complement(x)
  fxc = evaluate(f,xc)
  evals -= 1
  x, xc, fx, fxc = pick(x, xc, fx, fxc)

  # Considers locus by locus in a random fashion
  perm = permutation(N)
  for i in perm:
    k = coding[i]
    if(evals<2): return x, fx, evals
    y = flip(x,k)
    fy = evaluate(f,y)
    yc = coding_complement(y)
    fyc = evaluate(f,yc)
    evals -= 2
    cx = C(x, y, fx, fy, k)
    cxc = C(xc, yc, fxc, fyc, k)
    separable[k] = separable[k] and (cx==cxc)
    w = x
    y, yc, fy, fyc = pick( y, yc, fy, fyc )
    x, y, fx, fy = pick( x, y, fx, fy )
    if(w!=x): xc, fxc = yc, fyc
  x, fx, evals = genome_best_gene_contribution(f, evals, x, fx)
  return x, fx, evals

# Gabo's stop condition
def stop():
  global coding, intron, separable
  for k in coding:
    if(not separable[k]): return False
  return len(intron)==0

# f: Function to be optimized
# x: initial point
# evals: Maximum number of fitness evaluations
# fx: f value at point x (if provided)
def GABO( f, evals, x, fx=None):
  init(len(x))
  if(evals>0 and not fx):
    fx = evaluate(f,x)
    evals -= 1
  x, fx, evals = ICSplit(f, evals, x, fx)
  flag = True
  while(evals>0 and flag):
    x, fx, evals = IOSA(f, evals, x, fx)
    x, fx, evals = COSA(f, evals, x, fx)
    flag = not stop()
  return x, fx


# -*- coding: utf-8 -*-
import click
import json
import os
from pathlib import Path
from dotenv import find_dotenv, load_dotenv

from ..logging import logger
from ..utils import save_json
from ..paths import model_path, trained_model_path
from .train import train_model, save_model
from ..data.datasets import available_datasets
from .algorithms import available_algorithms

@click.command()
@click.argument('model_list')
@click.option('--output_file', '-o', nargs=1, type=str,
              default='trained_models.json')
@click.option('--hash-type', '-H', type=click.Choice(['md5', 'sha1']),
              default='sha1')
def main(model_list, *, output_file, hash_type):
    """Trains models speficied in the supplied `model_list` file

    output is a dictionary of trained model metadata keyed by
    model_key := {algorithm}_{dataset}_{run_number}, where:

    dataset:
        name of dataset to use
    algorithm:
        name of algorithm (estimator) to run on the dataset
    run_number:
        Arbitrary integer.

    The combination of these 3 things must be unique.

    trained models are written to `trained_model_path`.

    For every model, we write:

    {model_key}.model:
        the trained model
    {model_key}.metadata:
        Metadata for this model

    Parameters
    ----------
    model_list: filename
        json file specifying list of options dictionaries to be passed to
        `train_model`
    output_file: str
        name of json file to write metadata to
    hash_name: {'sha1', 'md5'}
        type of hash to use for caching of python objects

    """
    logger.info(f'Building models from {model_list}')

    os.makedirs(trained_model_path, exist_ok=True)

    with open(model_path / model_list) as f:
        training_dicts = json.load(f)

    dataset_list = available_datasets()
    algorithm_list = available_algorithms()

    metadata_dict = {}  # Used to ensure uniqueness of keys
    for td in training_dicts:
        ds_name = td.get('dataset', None)
        assert ds_name in dataset_list, f'Unknown Dataset: {ds_name}'

        alg_name = td.get('algorithm', None)
        assert alg_name in algorithm_list, f'Unknown Algorithm: {alg_name}'

        run_number = td.get('run_number', 0)
        model_key = f"{td['algorithm']}_{td['dataset']}_{run_number}"
        if model_key in metadata_dict:
            raise Exception("{id_base} already exists. Give a unique " +
                            "`run_number` to avoid collisions.")
        else:
            td['run_number'] = run_number
            metadata_dict[model_key] = td

        saved_meta = {}
        for model_key, td in metadata_dict.items():
            logger.debug(f'Creating model for {model_key}')
            trained_model, added_metadata = train_model(hash_type=hash_type,
                                                        **td)
            # replace specified params with full set of params used
            # td['algorithm_params'] = dict(trained_model.get_params())
            new_metdata = {**td, **added_metadata}
            saved_meta[model_key] = save_model(model_name=model_key,
                                               model=trained_model,
                                               metadata=new_metdata)

    logger.debug(f"output dir: {model_path}")
    logger.debug(f"output filename: {output_file}")
    save_json(model_path / output_file, saved_meta)
    logger.info("Training complete! Saved metdata to " +
                f"{model_path / output_file}")

if __name__ == '__main__':

    # not used in this stub but often useful for finding various files
    project_dir = Path(__file__).resolve().parents[2]

    # find .env automagically by walking up directories until it's found, then
    # load up the .env entries as environment variables
    load_dotenv(find_dotenv())

    main()


from __future__ import absolute_import, division, unicode_literals

import os
import shutil
import subprocess
import platform

def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError:
        pass

def symlink(src, dest):
    src = os.path.abspath(src)
    dest = os.path.abspath(dest)

    if platform.system() == 'Windows':
        if os.path.isdir(src):
            subprocess.check_output('mklink /j "{}" "{}"'.format(dest, src),
                                    shell=True)
        else:
            subprocess.check_output('mklink /h "{}" "{}"'.format(dest, src),
                                    shell=True)
    else:
        os.symlink(src, dest)

def cp_r(src, dest):
    if os.path.isdir(src):
        shutil.copytree(src, dest)
    else:
        shutil.copy(src, dest)


"""
source: own
author: https://github.com/MarkShawn2020
create: Nov 08, 2022, 15:10
"""
import os
from typing import List

from PIL import Image
from pdf2image import convert_from_path

from src.settings import PDF_PPI, PDF_IMAGES_RAW_DIR, PDF_PATH

def pdf2images(fp: str, ppi=PDF_PPI):
    print(f'converting file://{fp}, ppi={ppi}')
    pages: List[Image] = convert_from_path(
        fp,
        thread_count=12,
        dpi=ppi,
        fmt='jpeg',
    )
    n = len(pages)
    for i in range(n):
        page = pages[i]  # type: Image
        print(f'saving [{i + 1}/{n}]')
        page.save(os.path.join(PDF_IMAGES_RAW_DIR, f'{i + 1}.jpg'), 'JPEG')

if __name__ == '__main__':
    pdf2images(PDF_PATH)


from flask import Flask, render_template, request

import config
import os
import json
import ee
import time
import calendar
import datetime
import threading

import logging, logging.config, yaml

from pymemcache.client.hash import Client
#from google.appengine.api import memcache as mc

##################################################################################################
# CONSTANT DEFINITIONS
##################################################################################################

EE_CREDENTIALS = ee.ServiceAccountCredentials(config.EE_ACCOUNT, config.EE_PRIVATE_KEY_FILE)

HIGH_COLLECTION_ID = 'srtm90_v4'
LIGHTS_COLLECTION_ID = 'NOAA/DMSP-OLS/NIGHTTIME_LIGHTS'
TEMPERATURE_COLLECTION_ID = 'MODIS/MOD11A2'

REDUCTION_SCALE_METERS = 20000

COUNTRIES_FILE = 'static/countries.txt'
COUNTRIES_PATH = 'static/countries/'
DETAILS_PATH = 'static/details/'

CACHE = 0 # When use memcache
SAVE = 0 # When we save data to precompute it in details folder
INITIAL_MAP = '5'

#logging
#LOGGER_TYPE = 'file'
LOGGER_TYPE = 'console'
logging.config.dictConfig(yaml.load(open('logging.conf')))
logger = logging.getLogger(LOGGER_TYPE)

##################################################################################################
# FUNCTIONS
##################################################################################################
def json_serializer(key, value):
  if type(value) == str:
     return value, 1
  return json.dumps(value), 2

def json_deserializer(key, value, flags):
  if flags == 1:
      return value
  if flags == 2:
      return json.loads(value)
  raise Exception('Unknown serialization format')

mc = Client(('localhost', 11211), serializer = json_serializer, deserializer = json_deserializer)

def createCountries(filename):
  file  = open(filename, 'r')
  return  file.read().splitlines()

COUNTRIES_ID = createCountries(COUNTRIES_FILE)

def change_dict(dct):
  if 'features' in dct:
    return dct['features'][0]
  return dct

# Add a band containing image date as years since 1991.
def CreateTimeBand(img):
  year = ee.Date(img.get('system:time_start')).get('year').subtract(1991)
  return ee.Image(year).byte().addBands(img)

def CreateTimeBandTemp(img):
  year = ee.Date(img.get('system:time_start')).get('year').subtract(2013)
  return ee.Image(year).byte().addBands(img)

def GetFeature(country_id):
  """Returns an ee.Feature for the country with the given ID."""
  if CACHE:
    try:
      geojson = mc.get('geojson_' + country_id)
      if geojson is not None:
        return ee.Feature(geojson)
    except Exception as e:
      logger.debug('Error GetFeature cache: '  + str(e))

  # Note: The country IDs are read from the filesystem in the initialization
  path = COUNTRIES_PATH + country_id + '.geo.json'
  path = os.path.join(os.path.split(__file__)[0], path)
  try:
    with open(path, 'r') as f:
      t = f.read()
      elem = json.loads(t, object_hook = change_dict)
      if CACHE:
        mc.set('geojson_' + country_id, elem)
      f.close()
      return ee.Feature(elem)
  except Exception as e:
    logger.debug('Error GetFeature reading file ' + path)

def coordsToFeature(coords):
  feature = json.loads(coords, object_hook = change_dict)
  return ee.Feature(feature)

def GetMapFromId(id):
  if id == '0':
    return GetHighMap()
  elif id == '1':
    return GetLightsMap()
  elif id == '2':
    return GetTemperatureMap()
  elif id == '3':
    return GetWaterOccurrenceMap()
  elif id == '4':
    return GetWaterChangeMap()
  elif id == '5':
    return GetForestChangeMap()
  elif id == '6':
    return GetVegetationMap()
  else:
    raise Exception("Map does not exists")

##################################################################################################
# HIGH MAP
##################################################################################################

def GetHighMap():
  return ee.Image(HIGH_COLLECTION_ID).getMapId({
    'min': '0',
    'max': '1000',
    'palette': '0000ff, 008000, ff0000'
  })

def ComputeCountryTimeSeriesHigh(country_id, feature = None, zoom = 1):
  """Returns mean elevation for the country."""
  img = ee.Image(HIGH_COLLECTION_ID)
  img = img.select('elevation')

  scale = 50000
  if feature is None:
    feature = GetFeature(country_id)
  else:
    scale = scale / zoom

  reduction = img.reduceRegion(ee.Reducer.mean(), feature.geometry(), scale)

  feature = ee.Feature(None, {
    'elevation': reduction.get('elevation')
  })
  chart_data = feature.getInfo()

  return chart_data['properties']

##################################################################################################
# LIGHTS MAP
##################################################################################################

def GetLightsMap():
  """Returns the MapID for the night-time lights trend map."""
  collection = ee.ImageCollection(LIGHTS_COLLECTION_ID)

  collection = collection.select('stable_lights').map(CreateTimeBand)
  # Fit a linear trend to the nighttime lights collection.
  fit = collection.reduce(ee.Reducer.linearFit())

  return fit.getMapId({
      'min': '0',
      'max': '0.18,20,-0.18',
      'bands': 'scale,offset,scale',
  })

def ComputeCountryTimeSeriesLights(country_id, feature = None, zoom = 1):
  """Returns a series of brightness over time for the country."""
  collection = ee.ImageCollection(LIGHTS_COLLECTION_ID)
  collection = collection.select('stable_lights').sort('system:time_start')

  scale = REDUCTION_SCALE_METERS
  if feature is None:
    feature = GetFeature(country_id)
  else:
    scale = scale / zoom

  # Compute the mean brightness in the region in each image.
  def ComputeMeanLights(img):
    reduction = img.reduceRegion(ee.Reducer.mean(), feature.geometry(), scale)
    return ee.Feature(None, {
        'stable_lights': reduction.get('stable_lights'),
        'system:time_start': img.get('system:time_start')
    })

  chart_data = collection.map(ComputeMeanLights).getInfo()

  # Extract the results as a list of lists.
  def ExtractMeanLights(feature):
    if 'stable_lights' in feature['properties'] and feature['properties']['stable_lights'] is not None:
      return [
          feature['properties']['system:time_start'],
          feature['properties']['stable_lights']
      ]

  return map(ExtractMeanLights, chart_data['features'])

##################################################################################################
# TEMPERATURE MAP
##################################################################################################

def GetTemperatureMap():
  """Returns the MapID for the temperature map"""
  collection = ee.ImageCollection(TEMPERATURE_COLLECTION_ID)
  collection = collection.select('LST_Day_1km')#.map(CreateTimeBand)

  fit = collection.median().toFloat().multiply(ee.Image(0.02)).subtract(ee.Image(273.15))

  return fit.getMapId({
    'min': '0',
    'max': '40',
    'palette':'0000ff,32cd32,ffff00,ff8c00,ff0000'
  })

def ComputeCountryTimeSeriesTemp(country_id, feature = None, zoom = 1):
  """Returns a series of surface temperature over time for the country."""
  collection = ee.ImageCollection(TEMPERATURE_COLLECTION_ID)
  collection = collection.select('LST_Day_1km')

  scale = 30000
  if feature is None:
    feature = GetFeature(country_id)
  else:
    scale = scale / zoom
  # Compute the mean temperature in the region in each image.
  def ComputeMeanTemp(img):
    reduction = img.reduceRegion(ee.Reducer.mean(),feature.geometry(), scale)
    return ee.Feature(None, {
        'temperature': reduction.get('LST_Day_1km'),
        'system:time_start': img.get('system:time_start')
    })

  chart_data = collection.map(ComputeMeanTemp).getInfo()

  def toCelsius(kelvin):
    scale = 0.02
    return kelvin * scale - 273.15

  # Extract the results as a list of lists.
  def ExtractMeanTemp(feature):
    if 'temperature' in feature['properties'] and feature['properties']['temperature'] is not None:
      tempInCelsius = toCelsius(feature['properties']['temperature'])
      return [
        feature['properties']['system:time_start'],
        tempInCelsius
      ]

  return map(ExtractMeanTemp, chart_data['features'])

##################################################################################################
# WATER OCCURRENCE MAP
##################################################################################################

def GetWaterOccurrenceMap():
  img = ee.Image('JRC/GSW1_0/GlobalSurfaceWater')
  img = img.select('occurrence')
  return img.getMapId({
    'min': '0',
    'max': '100',
    'palette': 'ff0000,0000ff'
  })

def ComputeCountryTimeSeriesWaterOccurence(country_id, feature = None, zoom = 1):
  """Returns a series of water occurrence over time for the country."""
  image = ee.Image('JRC/GSW1_0/GlobalSurfaceWater')
  image = image.select('change_abs')

  scale = REDUCTION_SCALE_METERS
  if feature is None:
    feature = GetFeature(country_id)
  else:
    scale = scale / zoom

  # Compute the mean temperature in the region in each image.
  def ComputeMeanWaterOccurence(img):
    reduction = img.reduceRegion(ee.Reducer.histogram(), feature.geometry(), scale)

    return ee.Feature(None, {
        'system:time_start' : img.get('system:time_start'),
        'water': reduction.get('change_abs')
    })

  chart_data = ComputeMeanWaterOccurence(image).getInfo()

  return chart_data['properties']['water']

##################################################################################################
# WATER CHANGE MAP
##################################################################################################

def GetWaterChangeMap():
  img = ee.Image('JRC/GSW1_0/GlobalSurfaceWater')
  img = img.select('change_abs')
  return img.getMapId({
    'min': '-50',
    'max': '50',
    'palette': 'ff0000,000000,00ff00'
  })
def ComputeCountryTimeSeriesWaterChange(country_id, feature = None, zoom = 1):
  """Returns a series of water change over time for the country."""
  collection = ee.ImageCollection('JRC/GSW1_0/YearlyHistory')
  collection = collection.select('waterClass')

  scale = REDUCTION_SCALE_METERS
  if feature is None:
    feature = GetFeature(country_id)
  else:
    scale = scale / zoom
  # Compute the mean temperature in the region in each image.
  def ComputeMeanWaterChange(img):
    reduction = img.reduceRegion(ee.Reducer.mean(), feature.geometry(), scale)

    return ee.Feature(None, {
        'system:time_start' : img.get('system:time_start'),
        'water': reduction.get('waterClass')
    })

  chart_data = collection.map(ComputeMeanWaterChange).getInfo()

  # Extract the results as a list of lists.
  def ExtractMeanWaterChange(feature):
    if 'water' in feature['properties'] and feature['properties']['water'] is not None:
      return [
        feature['properties']['system:time_start'],
        feature['properties']['water']
      ]

  return map(ExtractMeanWaterChange, chart_data['features'])

##################################################################################################
# FOREST CHANGE MAP
##################################################################################################

def GetForestChangeMap():
  img = ee.Image('UMD/hansen/global_forest_change_2015')
  return img.getMapId({
    'bands': 'loss, treecover2000, gain',
    'max': '1, 255, 1'
  })

def ComputeCountryTimeSeriesForestChange(country_id, feature = None, zoom = 1):
  """Returns country forest change."""
  collection = ee.Image('UMD/hansen/global_forest_change_2015')

  scale = 14000
  if feature is None:
    feature = GetFeature(country_id)
  else:
    scale = scale / zoom
  # Compute the mean temperature in the region in each image.
  def ComputeMeanForestChange(img):
    reduction = img.reduceRegion(ee.Reducer.mean(), feature.geometry(), scale)

    return ee.Feature(None, {
        'treecover2000' : reduction.get('treecover2000'),
        'loss': reduction.get('loss'),
        'gain': reduction.get('gain')
    })

  chart_data = ComputeMeanForestChange(collection).getInfo()

  # Extract the results as a list of lists.
  def ExtractMeanForestChange(feature):
    if 'loss' in feature['properties'] and feature['properties']['loss'] is not None:
      return [
        feature['properties']['treecover2000'],
        feature['properties']['gain'],
        feature['properties']['loss']
      ]

  return ExtractMeanForestChange(chart_data)

##################################################################################################
# VEGETATION INDEX MAP
##################################################################################################

def GetVegetationMap():
  img = ee.Image(ee.ImageCollection('MODIS/MCD43A4_NDVI').mean())
  return img.getMapId({
    'min': '0',
    'max': '1',
    'palette' : 'FFFFFF,CC9966,CC9900,996600,33CC00,009900,006600,000000'
  })

def ComputeCountryTimeSeriesVegetation(country_id, feature = None, zoom = 1):
  """Returns a series of vegetation over time for the country."""
  collection = ee.ImageCollection('MODIS/MCD43A4_NDVI')
  collection = collection.select('NDVI')

  scale = REDUCTION_SCALE_METERS
  if feature is None:
    feature = GetFeature(country_id)
  else:
    scale = scale / zoom

  # Compute the mean temperature in the region in each image.
  def ComputeMeanVegetation(img):
    reduction = img.reduceRegion(ee.Reducer.mean(), feature.geometry(), scale)

    return ee.Feature(None, {
        'system:time_start' : img.get('system:time_start'),
        'NDVI': reduction.get('NDVI')
    })

  chart_data = collection.map(ComputeMeanVegetation).getInfo()

  # Extract the results as a list of lists.
  def ExtractMeanVegetation(feature):
    if 'NDVI' in feature['properties'] and feature['properties']['NDVI'] is not None:
      return [
        feature['properties']['system:time_start'],
        feature['properties']['NDVI']
      ]

  return map(ExtractMeanVegetation, chart_data['features'])

def ComputeCountryTimeSeries(map_id, country_id, feature = None, zoom = 1):
  """Returns a series of the specific map over time for the country."""
  if map_id == '0':
    return ComputeCountryTimeSeriesHigh(country_id, feature, zoom)
  elif map_id == '1':
    return ComputeCountryTimeSeriesLights(country_id, feature, zoom)
  elif map_id == '2':
    return ComputeCountryTimeSeriesTemp(country_id, feature, zoom)
  elif map_id == '3':
    return ComputeCountryTimeSeriesWaterOccurence(country_id, feature, zoom)
  elif map_id == '4':
    return ComputeCountryTimeSeriesWaterChange(country_id, feature, zoom)
  elif map_id == '5':
    return ComputeCountryTimeSeriesForestChange(country_id, feature, zoom)
  elif map_id == '6':
    return ComputeCountryTimeSeriesVegetation(country_id, feature, zoom)
  else:
    raise Exception("Map type does not exists")

##################################################################################################
# APP ROUTES
##################################################################################################

# API
app = Flask(__name__)

app.jinja_env.auto_reload = True
app.config.update(
  DEBUG=False,
  TEMPLATES_AUTO_RELOAD=False
)

@app.before_request
def before_request():
  # When you import jinja2 macros, they get cached which is annoying for local
  # development, so wipe the cache every request.
  #app.jinja_env.cache = dict()
  # Initialize Earth Engine
  ee.Initialize(EE_CREDENTIALS)
  #ee.Initialize()

# Define root route
@app.route('/')
def main():
  mapid = GetMapFromId(INITIAL_MAP)

  # Add variables to the template
  template_values = {
    'map': INITIAL_MAP,
    'mapid': mapid['mapid'],
    'token': mapid['token'],
    'API_KEY': config.API_KEY,
    'countries' : json.dumps(COUNTRIES_ID)
  }

  # Render the template index.html
  return render_template('index.html', values = template_values)

@app.route('/map/<id>')
def get(id):
  mapid = GetMapFromId(id)
  # Add variables to the template
  template_values = {
    'map' : id,
    'mapid': mapid['mapid'],
    'token': mapid['token'],
    'API_KEY': config.API_KEY,
    'countries' : json.dumps(COUNTRIES_ID)
  }
  # Render the template reload.html
  return render_template('reload.html', values = template_values)

@app.route('/save/<map_id>')
def saveCountryTimeSeries(map_id):
  error = 0
  message = ''
  if CACHE:
    elems = dict()
    if SAVE:
      path = DETAILS_PATH + 'mapid_' + map_id + '.json'
      details_file = open(path, 'w')
    else:
      thread = threading.Thread()
      thread.start()
    for country_id in COUNTRIES_ID:
      key = 'details' + '_'+ map_id + '_' + country_id
      details = dict()
      try:
        if map_id == '0' or map_id == '3':
          details = ComputeCountryTimeSeries(map_id, country_id)
          if details is not None:
            mc.set(key, json.dumps(details))
        elif map_id == '5':
          details['forestChange'] = ComputeCountryTimeSeries(map_id, country_id)
          if details['forestChange'] is not None:
            mc.set(key, json.dumps(details))
        else:
          details['timeSeries'] = list(ComputeCountryTimeSeries(map_id, country_id))
          if details['timeSeries'] is not None:
            mc.set(key, json.dumps(details))
        elems[country_id] = details
      except Exception as e:
        error = 1
        message = str(e)
        logger.debug('Error saveCountryTimeSeries: ' + message)
    if SAVE and not error:
      json.dump(elems, details_file , separators = (',', ':'))
      details_file.close()
  return json.dumps({'status' : error, 'message' : message})

@app.route('/static/<map_id>')
def staticCountryTimeSeries(map_id):
  error = 0
  message = ''
  if SAVE:
    elems = dict()
    path = DETAILS_PATH + 'mapid_' + map_id + '.json'
    details_file = open(path, 'w')
    for country_id in COUNTRIES_ID:
      key = 'details' + '_'+ map_id + '_' + country_id
      details = dict()
      try:
        if map_id == '0' or map_id == '3':
          details = ComputeCountryTimeSeries(map_id, country_id)
          if details is not None:
            elems[country_id] = details
        elif map_id == '5':
          details['forestChange'] = ComputeCountryTimeSeries(map_id, country_id)
          if details['forestChange'] is not None:
            elems[country_id] = details
        else:
          details['timeSeries'] = list(ComputeCountryTimeSeries(map_id, country_id))
          if details['timeSeries'] is not None:
            elems[country_id] = details
      except Exception as e:
        error = 1
        message = str(e)
        logger.debug('Error saveCountryTimeSeries: ' + message)
    if not error:
      json.dump(elems, details_file , separators = (',', ':'))
      details_file.close()
  return json.dumps({'status' : error, 'message' : message})

@app.route('/details/<map_id>/<country_id>')
def GetCountryTimeSeries(map_id, country_id):
  if CACHE:
    try:
      key = 'details' + '_'+ map_id + '_' + country_id
      details = mc.get(key)
      if details is not None:
        return details
    except Exception as e:
      logger.debug('Error cache GetCountryTimeSeries: ' + str(e))

  details = dict()
  try:
    if map_id == '0' or map_id == '3':
      details = ComputeCountryTimeSeries(map_id, country_id)
      if CACHE and details is not None:
        mc.set(key, json.dumps(details))
    elif map_id == '5':
      details['forestChange'] = ComputeCountryTimeSeries(map_id, country_id)
      if CACHE and details['forestChange'] is not None:
        mc.set(key, json.dumps(details))
    else:
      details['timeSeries'] = list(ComputeCountryTimeSeries(map_id, country_id))
      if CACHE and details['timeSeries'] is not None:
        mc.set(key, json.dumps(details))

  except ee.EEException as e:
    # Handle exceptions from the EE client library.
    details['error'] = str(e)
    logger.debug('Error GetCountryTimeSeries: ' + details['error'])
  # Send the results to the browser.
  return json.dumps(details)

@app.route('/details/<map_id>')
def GetAllCountriesDetails(map_id):
  if CACHE:
    try:
     key = 'details' + '_' + map_id
     countries = mc.get(key)
     if countries is not None:
       return countries
    except Exception as e:
      logger.debug('Error cache GetAllCountriesDetails' + str(e))
    countries = list()
    for country_id in COUNTRIES_ID:
      try:
        key = 'details' + '_'+ map_id + '_' + country_id
        country = mc.get(key)
      except Exception as e:
        logger.debug('Error cache GetAllCountriesDetails: ' + country_id)
      try:
        if country is None:
          elem = {'name' : getCountryName(country_id), 'data' : ComputeCountryTimeSeries(map_id, country_id) }
        else:
          elem = {'name' : getCountryName(country_id), 'data' : country }
        countries.append(json.dumps(elem))
      except Exception as e:
        logger.debug('Error GetAllCountriesDetails, country: ' + country_id + ' : ' + str(e))
    key = 'details' + '_'+ map_id
    mc.set(key, json.dumps(countries))
  else:
    countries = dict()
    countries['error'] = 'Not implemented yet'
  return json.dumps(countries)

@app.route('/custom/<map_id>/<zoom>', methods = ['POST'])
def GetCustomSeries(map_id, zoom):
  """Get time series from a custom polygon"""
  key = list(request.form.keys())[0]
  details = dict()
  try:
    feature = coordsToFeature(key)
    if feature is not None:
      try:
        zoom = int(zoom)
        if map_id == '0' or map_id == '3':
          details = ComputeCountryTimeSeries(map_id, None, feature, zoom)
        elif map_id == '5':
          details['forestChange'] = ComputeCountryTimeSeries(map_id, None, feature, zoom)
        else:
          details['timeSeries'] = list(ComputeCountryTimeSeries(map_id, None, feature, zoom))
      except ee.EEException as e:
        # Handle exceptions from the EE client library.
        details['error'] = str(e)
        logger.debug('Error GetCustomSeries: ' + details['error'])
  except Exception as e:
    details['error'] = str(e)
    logger.debug('Error GetCustomSeries: ' + details['error'])
  # Send the results to the browser.
  return json.dumps(details)

@app.route('/country/<country_id>')
def getCountryName(country_id):
  """Get country name from country id"""
  if CACHE:
    try:
      key = 'name_' + country_id
      name = mc.get(key)
      if name is not None:
        return name
    except Exception as e:
      logger.debug('Error cache getCountryName:' + str(e))
  path = COUNTRIES_PATH + country_id + '.geo.json'
  path = os.path.join(os.path.split(__file__)[0], path)
  try:
    with open(path, 'r') as f:
      t = f.read()
      elem = json.loads(t, object_hook = change_dict)
      name = elem['properties']['name']
      if CACHE and name is not None:
        mc.set(key, name)
      f.close()
      return name
  except Exception as e:
    logger.debug('Error getCountryName reading file ' + path + ' : ' + str(e))

# Run application in selected port
if __name__ == '__main__':
  app.run('0.0.0.0', 8080, threaded=True)


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

class RadialBarrierObstacle():
    def __init__(self, cx, cy, weight = 1e-7, radius = 0):
        self.center = np.array([cx, cy])
        self.weight = weight
        self.radius = radius

    '''
    This function evaluates the obstacle cost function at a given set of coords
    Input:
        coords  - (*, 2) array of coordinates
    Output:
        (*,) array of coordinates
    '''
    def cost(self, coords):
        # coords of shape (*, 2)
        shape = coords.shape
        pos = self.center
        radius = self.radius
        # Pad the center to achieve same shape (*, 2)
        for _ in range(len(shape) - 1):
            pos = np.expand_dims(pos, axis = 0)

        return self.weight / (np.sum(np.square(coords - pos), axis = -1) - radius)

    '''
    This function integrates the cost in a straight line from two provided
    endpoints.
    Input:
        start   - (N x 2) array
        end     - (N x 2) array
        jacobian - whether to return L jacobian or not

    Output:
        (N, ) array
        (N, 4) array L (optional): dL/d[x2 y2 x1 y1]
    '''
    def integral(self, start, end, jacobian = False, debug = False):
        delta = end - start #  N x 2
        to_center = start - self.center # N x 2, 2 -> N x 2
        a = delta[:, :1] # x distance from start to end point, N x 1
        c = delta[:, 1:] # y distance from start to end point, N x 1

        b = to_center[:, :1] # x distance from start point to the center
        d = to_center[:, 1:] # y distance from start point to the center
        # print(f"dx: {a}, dy: {c}, dcx: {b}, dcy: {d}")

        e = a ** 2 + c ** 2 # N x 1
        f = 2* (a * b + c * d) # N x 1
        g = b ** 2 + d ** 2 # N x 1
        if jacobian and debug:
            print(f"de numerical: {(e[1:,0] - e[0,0]) / 1e-7}")
            print(f"df numerical: {(f[1:,0] - f[0,0]) / 1e-7}")
            print(f"dg numerical: {(g[1:,0] - g[0,0]) / 1e-7}")

        sqrt_e = np.sqrt(e) # N x 1
        determinant = 4 * e * g - f ** 2 # N x 1
        B = np.sqrt(determinant) # N x 1
        C = (2 * e + f) / B # N x 1
        D = f / B

        if jacobian and debug:
            print(f"dB numerical: {(B[1:,0] - B[0,0]) / 1e-7}")
            print(f"dC numerical: {(C[1:,0] - C[0,0]) / 1e-7}")
            print(f"dD numerical: {(D[1:,0] - D[0,0]) / 1e-7}")
        arctanC = np.arctan(C)
        arctanD = np.arctan(D)

        integral1 = 2 * arctanC / B
        integral0 = 2 * arctanD / B
        def_integral = np.linalg.norm(delta, axis = -1, keepdims = True) * (integral1 - integral0)

        if jacobian:
            # return the Jacobian of the integral
            de = np.concatenate([a, c, -a, -c], axis = 1) * 2 # N x 4
            dg = np.concatenate([np.zeros(b.shape), np.zeros(b.shape), b, d], axis = 1) * 2
            df = np.concatenate([b, d, a - b, c - d], axis = 1) * 2
            if debug:
                print(f"de analytical: {de[0]}")
                print(f"df analytical: {df[0]}")
                print(f"dg analytical: {dg[0]}")

            dB = (2 * (e * dg + g * de) - f * df) / B # N x 1, N x 4 -> N x 4
            dC = (B * (2 * de + df) - (2 * e + f) * dB) / determinant
            dD = (B * df - f* dB) / determinant
            if debug:
                print(f"dB analytical: {dB[0]}")
                print(f"dC analytical: {dC[0]}")
                print(f"dD analytical: {dD[0]}")

            L = ((2 * sqrt_e * (dC / (1 + C ** 2) - dD / (1 + D ** 2)) + (arctanC - arctanD) * de / sqrt_e)/ B) - \
                (2 * sqrt_e * (arctanC - arctanD) * dB) / determinant
            return def_integral * self.weight, L * self.weight

        return def_integral * self.weight

def length(start, end, jacobian = False):
    length = np.linalg.norm(start - end)
    delta = end - start
    if jacobian:
        C = np.concatenate((delta, -delta), axis = 1) / length
        return length, C

    return length


import streamlit as st
from PIL import Image

st.set_page_config(
    page_title="Home",
    page_icon="ðŸˆ³"
)

image = Image.open( 'logo.jpg' )
st.sidebar.image( image, width=120 )

st.sidebar.markdown('# Curry Company')
st.sidebar.markdown('## Fastest Delivery in Town')
st.sidebar.markdown("""---""")

st.write( '# Curry Company Growth Dashboard' )

st.markdown(
    """
    Growth Dashboard foi construido para acompanhar as metricas de crescimento dos
    entregadores e restaurantes.
    ### Como utilizar esse Growth Dashboard?
    - Visao da Empresa:
      - Visao Gerencial: Metricas gerais de comportamento;
      - Visao Tatica: Indicadores semanais de crescimento;
      - Visao Geografica: Insights de geolocalizacao.
    - Visao dos Entregadores:
      - Acompanhamento dos indicadores semanais de crescimento.
    - Visao dos Restaurantes:
      - Indicadores semanais de crescimento dos restaurantes.
    ### Ask for Help
      - Time de Data Science no Discord
    """ )


#!/usr/bin/python

import numpy as np
import json
import collections,random,sys
from keras.models import model_from_json
from keras.optimizers import Adam
import rospy
from environment import Environment

class Agent(object):
    def __init__(self, env, model, weight):
        self.alpha = 0.001
        self.env = env
        self.ntrials = 6
        self.nstates = env.observation_space.get_size()
        self.model = self.load_model(model)
        self.weight = weight
        self.configure = {}

    def load_model(self,filename):
        json_file = open(filename,'r')
        model = model_from_json(json_file.read())
        json_file.close()
        return model

    def epsilon_greedy(self,state):
        if np.random.rand() < self.epsilon:
            return self.env.action_space.sample()
        else:
            Q = self.model.predict(state)
            return np.argmax(Q[0])

    def train(self):
        self.model.load_weights(self.weight)
        self.model.compile(loss='mse', optimizer=Adam(lr=self.alpha))
        self.epsilon = 0.1
        for trial in range(self.ntrials):
            s = self.env.reset(test=trial+1)
            s = np.reshape(s,[1,self.nstates])
            treward = 0
            while True:
                a = self.epsilon_greedy(s)
                s2, r, done = self.env.step(a)
                s = np.reshape(s2, [1,self.nstates])
                treward += r
                if done:
                    rospy.loginfo('test: ' + str(trial+1) + ' reward: ' + str(treward))
                    break

if __name__ == '__main__':
    if not len(sys.argv) > 2:
        assert False, 'missing model and/or weight'
    rospy.init_node('ddqn_test')
    rospy.loginfo('start testing')
    env = Environment()
    agent = Agent(env, str(sys.argv[1]),str(sys.argv[2]))
    agent.train()
    env.reset()
    rospy.loginfo('COMPLETE TESTING')
    rospy.spin()


import sqlite3
import pandas as pd
conn = sqlite3.connect('my_database.sqlite')
cursor = conn.cursor()
sales = pd.read_csv(r"/Users/aravind/Downloads/100 Sales Records.csv")
print(sales)

# cursor.execute('''CREATE TABLE SCHOOL
#          (ID INT PRIMARY KEY     NOT NULL,
#          NAME           TEXT    NOT NULL,
#          AGE            INT     NOT NULL,
#          ADDRESS        CHAR(50),
#          MARKS          INT);''')
#
# cursor.execute("INSERT INTO SCHOOL (ID,NAME,AGE,ADDRESS,MARKS) \
#       VALUES (1, 'Rohan', 14, 'Delhi', 200)");
# cursor.execute("INSERT INTO SCHOOL (ID,NAME,AGE,ADDRESS,MARKS) \
#       VALUES (2, 'Allen', 14, 'Bangalore', 150 )");
# cursor.execute("INSERT INTO SCHOOL (ID,NAME,AGE,ADDRESS,MARKS) \
#       VALUES (3, 'Martha', 15, 'Hyderabad', 200 )");
# cursor.execute("INSERT INTO SCHOOL (ID,NAME,AGE,ADDRESS,MARKS) \
#       VALUES (4, 'Palak', 15, 'Kolkata', 650)");
#
# for row in cursor.execute("SELECT id, name, marks from SCHOOL"):
#     print("ID = ", row[0])
#     print("NAME = ", row[1])
#     print("MARKS = ", row[2], "\n")

print("Opened database successfully")