import copy

from .common.codegen import CodeGen, VulkanWrapperGenerator
from .common.vulkantypes import \
        VulkanAPI, makeVulkanTypeSimple, iterateVulkanType

from .marshaling import VulkanMarshalingCodegen
from .reservedmarshaling import VulkanReservedMarshalingCodegen
from .counting import VulkanCountingCodegen
from .handlemap import HandleMapCodegen
from .deepcopy import DeepcopyCodegen
from .transform import TransformCodegen, genTransformsForVulkanType

from .wrapperdefs import API_PREFIX_RESERVEDMARSHAL
from .wrapperdefs import API_PREFIX_MARSHAL
from .wrapperdefs import API_PREFIX_UNMARSHAL
from .wrapperdefs import ROOT_TYPE_DEFAULT_VALUE
from .wrapperdefs import VULKAN_STREAM_TYPE_GUEST

encoder_decl_preamble = """
class VkEncoder {
public:
    VkEncoder(IOStream* stream);
    ~VkEncoder();

#include "VkEncoder.h.inl"
"""

encoder_decl_postamble = """
private:
    class Impl;
    std::unique_ptr<Impl> mImpl;
};
"""

encoder_impl_preamble ="""

using namespace goldfish_vk;

using android::aligned_buf_alloc;
using android::aligned_buf_free;
using android::base::guest::AutoLock;
using android::base::guest::Lock;
using android::base::BumpPool;

#include "VkEncoder.cpp.inl"

#define VALIDATE_RET(retType, success, validate) \\
    retType goldfish_vk_validateResult = validate; \\
    if (goldfish_vk_validateResult != success) return goldfish_vk_validateResult; \\

#define VALIDATE_VOID(validate) \\
    VkResult goldfish_vk_validateResult = validate; \\
    if (goldfish_vk_validateResult != VK_SUCCESS) return; \\

"""

STREAM = "stream"
RESOURCES = "sResourceTracker"
POOL = "pool"

ENCODER_PREVALIDATED_APIS = [
    "vkFlushMappedMemoryRanges",
    "vkInvalidateMappedMemoryRanges",
]

ENCODER_CUSTOM_RESOURCE_PREPROCESS = [
    "vkMapMemoryIntoAddressSpaceGOOGLE",
    "vkDestroyDevice",
]

ENCODER_CUSTOM_RESOURCE_POSTPROCESS = [
    "vkCreateInstance",
    "vkCreateDevice",
    "vkMapMemoryIntoAddressSpaceGOOGLE",
    "vkGetPhysicalDeviceProperties",
    "vkGetPhysicalDeviceProperties2",
    "vkGetPhysicalDeviceProperties2KHR",
    "vkGetPhysicalDeviceMemoryProperties",
    "vkGetPhysicalDeviceMemoryProperties2",
    "vkGetPhysicalDeviceMemoryProperties2KHR",
    "vkCreateDescriptorUpdateTemplate",
    "vkCreateDescriptorUpdateTemplateKHR",
    "vkGetPhysicalDeviceExternalSemaphoreProperties",
    "vkGetPhysicalDeviceExternalSemaphorePropertiesKHR",
]

ENCODER_EXPLICIT_FLUSHED_APIS = [
    "vkEndCommandBufferAsyncGOOGLE",
    "vkQueueSubmitAsyncGOOGLE",
    "vkQueueBindSparseAsyncGOOGLE",
    "vkQueueWaitIdleAsyncGOOGLE",
    "vkQueueSignalReleaseImageANDROID",
    "vkDestroyDevice",
]

SUCCESS_RET_TYPES = {
    "VkResult" : "VK_SUCCESS",
    "void" : None,
    # TODO: Put up success results for other return types here.
}

ENCODER_THIS_PARAM = makeVulkanTypeSimple(False, "VkEncoder", 1, "this")

# Common components of encoding a Vulkan API call
def make_event_handler_call(
    handler_access,
    api,
    context_param,
    input_result_param,
    cgen,
    suffix=""):
    extraParams = [context_param.paramName]
    if input_result_param:
        extraParams.append(input_result_param)
    return cgen.makeCallExpr( \
               "%s->on_%s%s" % (handler_access, api.name, suffix),
               extraParams + \
                       [p.paramName for p in api.parameters[:-1]])

def emit_custom_pre_validate(typeInfo, api, cgen):
    if api.name in ENCODER_PREVALIDATED_APIS:
        callExpr = \
            make_event_handler_call( \
                "mImpl->validation()", api,
                ENCODER_THIS_PARAM,
                SUCCESS_RET_TYPES[api.getRetTypeExpr()],
                cgen)

        if api.getRetTypeExpr() == "void":
            cgen.stmt("VALIDATE_VOID(%s)" % callExpr)
        else:
            cgen.stmt("VALIDATE_RET(%s, %s, %s)" % \
                (api.getRetTypeExpr(),
                 SUCCESS_RET_TYPES[api.getRetTypeExpr()],
                 callExpr))

def emit_custom_resource_preprocess(typeInfo, api, cgen):
    if api.name in ENCODER_CUSTOM_RESOURCE_PREPROCESS:
        cgen.stmt( \
            make_event_handler_call( \
                "sResourceTracker", api,
                ENCODER_THIS_PARAM,
                SUCCESS_RET_TYPES[api.getRetTypeExpr()],
                cgen, suffix="_pre"))

def emit_custom_resource_postprocess(typeInfo, api, cgen):
    if api.name in ENCODER_CUSTOM_RESOURCE_POSTPROCESS:
        cgen.stmt(make_event_handler_call( \
            "sResourceTracker",
            api,
            ENCODER_THIS_PARAM,
            api.getRetVarExpr(),
            cgen))

def emit_count_marshal(typeInfo, param, cgen):
    res = \
        iterateVulkanType(
            typeInfo, param,
            VulkanCountingCodegen( \
                cgen, "sFeatureBits", param.paramName, "countPtr", ROOT_TYPE_DEFAULT_VALUE,
               "count_"))
    if not res:
        cgen.stmt("(void)%s" % param.paramName)

def emit_marshal(typeInfo, param, cgen):
    forOutput = param.isHandleType() and ("out" in param.inout)
    if forOutput:
        cgen.stmt("/* is handle, possibly out */")

    res = \
        iterateVulkanType(
            typeInfo, param,
            VulkanReservedMarshalingCodegen( \
                cgen, STREAM, ROOT_TYPE_DEFAULT_VALUE, param.paramName, "streamPtrPtr",
               API_PREFIX_RESERVEDMARSHAL,
               "" if forOutput else "get_host_u64_",
               direction="write"))
    if not res:
        cgen.stmt("(void)%s" % param.paramName)

    if forOutput:
        cgen.stmt("/* is handle, possibly out */")

def emit_unmarshal(typeInfo, param, cgen):
    iterateVulkanType(
        typeInfo, param,
        VulkanMarshalingCodegen( \
            cgen, STREAM, ROOT_TYPE_DEFAULT_VALUE, param.paramName,
           API_PREFIX_UNMARSHAL, direction="read"))

def emit_deepcopy(typeInfo, param, cgen):
    res = \
        iterateVulkanType(typeInfo, param, DeepcopyCodegen(
            cgen, [param.paramName, "local_" + param.paramName], "pool", ROOT_TYPE_DEFAULT_VALUE, "deepcopy_"))
    if not res:
        cgen.stmt("(void)%s" % param.paramName)

def emit_transform(typeInfo, param, cgen, variant="tohost"):
    res = \
        iterateVulkanType(typeInfo, param, TransformCodegen( \
            cgen, param.paramName, "sResourceTracker", "transform_%s_" % variant, variant))
    if not res:
        cgen.stmt("(void)%s" % param.paramName)

def emit_handlemap_create(typeInfo, param, cgen):
    iterateVulkanType(typeInfo, param, HandleMapCodegen(
        cgen, None, "sResourceTracker", "handlemap_",
        lambda vtype: typeInfo.isHandleType(vtype.typeName)
    ))

def custom_encoder_args(api):
    params = ["this"]
    if api.getRetVarExpr() is not None:
        params.append(api.getRetVarExpr())
    return params

def emit_handlemap_destroy(typeInfo, param, cgen):
    iterateVulkanType(typeInfo, param, HandleMapCodegen(
        cgen, None, "sResourceTracker->destroyMapping()", "handlemap_",
        lambda vtype: typeInfo.isHandleType(vtype.typeName)
    ))

class EncodingParameters(object):
    def __init__(self, api):
        self.localCopied = []
        self.toWrite = []
        self.toRead = []
        self.toCreate = []
        self.toDestroy = []

        for param in api.parameters:
            param.action = None
            param.inout = "in"

            if param.paramName == "doLock":
                continue

            if param.possiblyOutput():
                param.inout += "out"
                self.toWrite.append(param)
                self.toRead.append(param)
                if param.isCreatedBy(api):
                    self.toCreate.append(param)
                    param.action = "create"
            else:

                if param.paramName == "doLock":
                    continue

                if param.isDestroyedBy(api):
                    self.toDestroy.append(param)
                    param.action = "destroy"
                localCopyParam = \
                    param.getForNonConstAccess().withModifiedName( \
                        "local_" + param.paramName)
                self.localCopied.append((param, localCopyParam))
                self.toWrite.append(localCopyParam)

def emit_parameter_encode_preamble_write(typeInfo, api, cgen):
    emit_custom_pre_validate(typeInfo, api, cgen);
    emit_custom_resource_preprocess(typeInfo, api, cgen);

    cgen.stmt("auto %s = mImpl->stream()" % STREAM)
    cgen.stmt("auto %s = mImpl->pool()" % POOL)
    # cgen.stmt("%s->setHandleMapping(%s->unwrapMapping())" % (STREAM, RESOURCES))

    encodingParams = EncodingParameters(api)
    for (_, localCopyParam) in encodingParams.localCopied:
        cgen.stmt(cgen.makeRichCTypeDecl(localCopyParam))

def emit_parameter_encode_copy_unwrap_count(typeInfo, api, cgen, customUnwrap=None):
    encodingParams = EncodingParameters(api)

    for (origParam, localCopyParam) in encodingParams.localCopied:
        shouldCustomCopy = \
            customUnwrap and \
            origParam.paramName in customUnwrap and \
            "copyOp" in customUnwrap[origParam.paramName]

        shouldCustomMap = \
            customUnwrap and \
            origParam.paramName in customUnwrap and \
            "mapOp" in customUnwrap[origParam.paramName]

        if shouldCustomCopy:
            customUnwrap[origParam.paramName]["copyOp"](cgen, origParam, localCopyParam)
        else:
            # if this is a pointer type and we don't do custom copy nor unwrap,
            # and the transform doesn't end up doing anything,
            # don't deepcopy, just cast it.

            avoidDeepcopy = False

            if origParam.pointerIndirectionLevels > 0:
                testCgen = CodeGen()
                genTransformsForVulkanType("sResourceTracker", origParam, lambda p: testCgen.generalAccess(p, parentVarName = None, asPtr = True), lambda p: testCgen.generalLengthAccess(p, parentVarName = None), testCgen)
                emit_transform(typeInfo, origParam, testCgen, variant="tohost")
                if "" == testCgen.swapCode():
                    avoidDeepcopy = True
            if avoidDeepcopy:
                cgen.line("// Avoiding deepcopy for %s" % origParam.paramName)
                cgen.stmt("%s = (%s%s)%s" % (localCopyParam.paramName, localCopyParam.typeName, "*" * origParam.pointerIndirectionLevels, origParam.paramName))
            else:
                emit_deepcopy(typeInfo, origParam, cgen)

    for (origParam, localCopyParam) in encodingParams.localCopied:
        shouldCustomMap = \
            customUnwrap and \
            origParam.paramName in customUnwrap and \
            "mapOp" in customUnwrap[origParam.paramName]

        if shouldCustomMap:
            customUnwrap[origParam.paramName]["mapOp"](cgen, origParam, localCopyParam)
        else:
            if localCopyParam.typeName == "VkAllocationCallbacks":
                cgen.stmt("%s = nullptr" % localCopyParam.paramName)

    apiForTransform = \
        api.withCustomParameters( \
            map(lambda p: p[1], \
                encodingParams.localCopied))

    # Apply transforms if applicable.
    # Apply transform to API itself:
    genTransformsForVulkanType(
        "sResourceTracker",
        apiForTransform,
        lambda p: cgen.generalAccess(p, parentVarName = None, asPtr = True),
        lambda p: cgen.generalLengthAccess(p, parentVarName = None),
        cgen)

    # For all local copied parameters, run the transforms
    for localParam in apiForTransform.parameters:
        if "doLock" in localParam.paramName:
            continue
        emit_transform(typeInfo, localParam, cgen, variant="tohost")

    cgen.stmt("size_t count = 0")
    cgen.stmt("size_t* countPtr = &count")
    cgen.beginBlock()

    # Use counting stream to calculate the packet size.
    for p in encodingParams.toWrite:
        emit_count_marshal(typeInfo, p, cgen)

    cgen.endBlock()

def is_cmdbuf_dispatch(api):
    return "VkCommandBuffer" == api.parameters[0].typeName

def emit_parameter_encode_write_packet_info(typeInfo, api, cgen):
    # Seqno and skipping dispatch serialize are for use with VULKAN_STREAM_FEATURE_QUEUE_SUBMIT_WITH_COMMANDS_BIT
    doSeqno = True
    doDispatchSerialize = True

    if is_cmdbuf_dispatch(api):
        doSeqno = False
        doDispatchSerialize = False

    if doSeqno:
        cgen.stmt("uint32_t packetSize_%s = 4 + 4 + (queueSubmitWithCommandsEnabled ? 4 : 0) + count" % (api.name))
    else:
        cgen.stmt("uint32_t packetSize_%s = 4 + 4 + count" % (api.name))

    if not doDispatchSerialize:
        cgen.stmt("if (queueSubmitWithCommandsEnabled) packetSize_%s -= 8" % api.name)

    cgen.stmt("uint8_t* streamPtr = %s->reserve(packetSize_%s)" % (STREAM, api.name))
    cgen.stmt("uint8_t** streamPtrPtr = &streamPtr")
    cgen.stmt("uint32_t opcode_%s = OP_%s" % (api.name, api.name))

    if doSeqno:
        cgen.stmt("uint32_t seqno; if (queueSubmitWithCommandsEnabled) seqno = ResourceTracker::nextSeqno()")

    cgen.stmt("memcpy(streamPtr, &opcode_%s, sizeof(uint32_t)); streamPtr += sizeof(uint32_t)" % api.name)
    cgen.stmt("memcpy(streamPtr, &packetSize_%s, sizeof(uint32_t)); streamPtr += sizeof(uint32_t)" % api.name)

    if doSeqno:
        cgen.line("if (queueSubmitWithCommandsEnabled) { memcpy(streamPtr, &seqno, sizeof(uint32_t)); streamPtr += sizeof(uint32_t); }")

def emit_parameter_encode_do_parameter_write(typeInfo, api, cgen):
    encodingParams = EncodingParameters(api)

    dispatchDone = False

    for p in encodingParams.toWrite:
        if is_cmdbuf_dispatch(api) and not dispatchDone:
            cgen.beginIf("!queueSubmitWithCommandsEnabled")
            emit_marshal(typeInfo, p, cgen)
            cgen.endIf()
        else:
            emit_marshal(typeInfo, p, cgen)

        dispatchDone = True

def emit_parameter_encode_read(typeInfo, api, cgen):
    encodingParams = EncodingParameters(api)

    for p in encodingParams.toRead:
        if p.action == "create":
            cgen.stmt(
                "%s->setHandleMapping(%s->createMapping())" % \
                (STREAM, RESOURCES))
        emit_unmarshal(typeInfo, p, cgen)
        if p.action == "create":
            cgen.stmt(
                "%s->unsetHandleMapping()" % STREAM)
        emit_transform(typeInfo, p, cgen, variant="fromhost")

def emit_post(typeInfo, api, cgen):
    encodingParams = EncodingParameters(api)

    emit_custom_resource_postprocess(typeInfo, api, cgen)

    for p in encodingParams.toDestroy:
        emit_handlemap_destroy(typeInfo, p, cgen)

    doSeqno = True
    if is_cmdbuf_dispatch(api):
        doSeqno = False

    retType = api.getRetTypeExpr()

    if api.name in ENCODER_EXPLICIT_FLUSHED_APIS:
        cgen.stmt("stream->flush()");
        return

    if doSeqno:
        if retType == "void":
            encodingParams = EncodingParameters(api)
            if 0 == len(encodingParams.toRead):
                cgen.stmt("stream->flush()");

def emit_pool_free(cgen):
    cgen.stmt("++encodeCount;")
    cgen.beginIf("0 == encodeCount % POOL_CLEAR_INTERVAL")
    cgen.stmt("pool->freeAll()")
    cgen.stmt("%s->clearPool()" % STREAM)
    cgen.endIf()

def emit_return_unmarshal(typeInfo, api, cgen):

    retType = api.getRetTypeExpr()

    if retType == "void":
        return

    retVar = api.getRetVarExpr()
    cgen.stmt("%s %s = (%s)0" % (retType, retVar, retType))
    cgen.stmt("%s->read(&%s, %s)" % \
              (STREAM, retVar, cgen.sizeofExpr(api.retType)))

def emit_return(typeInfo, api, cgen):
    if api.getRetTypeExpr() == "void":
        return

    retVar = api.getRetVarExpr()
    cgen.stmt("return %s" % retVar)

def emit_lock(cgen):
    cgen.stmt("(void)doLock");
    cgen.stmt("bool queueSubmitWithCommandsEnabled = sFeatureBits & VULKAN_STREAM_FEATURE_QUEUE_SUBMIT_WITH_COMMANDS_BIT")
    cgen.stmt("if (!queueSubmitWithCommandsEnabled && doLock) this->lock()")

def emit_unlock(cgen):
    cgen.stmt("if (!queueSubmitWithCommandsEnabled && doLock) this->unlock()")

def emit_default_encoding(typeInfo, api, cgen):
    emit_lock(cgen)
    emit_parameter_encode_preamble_write(typeInfo, api, cgen)
    emit_parameter_encode_copy_unwrap_count(typeInfo, api, cgen)
    emit_parameter_encode_write_packet_info(typeInfo, api, cgen)
    emit_parameter_encode_do_parameter_write(typeInfo, api, cgen)
    emit_parameter_encode_read(typeInfo, api, cgen)
    emit_return_unmarshal(typeInfo, api, cgen)
    emit_post(typeInfo, api, cgen)
    emit_pool_free(cgen)
    emit_unlock(cgen)
    emit_return(typeInfo, api, cgen)

## Custom encoding definitions##################################################

def emit_only_goldfish_custom(typeInfo, api, cgen):
    emit_lock(cgen)
    cgen.vkApiCall( \
        api,
        customPrefix="sResourceTracker->on_",
        customParameters=custom_encoder_args(api) + \
                [p.paramName for p in api.parameters[:-1]])
    emit_unlock(cgen)
    emit_return(typeInfo, api, cgen)

def emit_only_resource_event(typeInfo, api, cgen):
    cgen.stmt("(void)doLock");
    input_result = None
    retExpr = api.getRetVarExpr()

    if retExpr:
        retType = api.getRetTypeExpr()
        input_result = SUCCESS_RET_TYPES[retType]
        cgen.stmt("%s %s = (%s)0" % (retType, retExpr, retType))

    cgen.stmt(
        (("%s = " % retExpr) if retExpr else "") +
        make_event_handler_call(
            "sResourceTracker",
            api,
            ENCODER_THIS_PARAM,
            input_result, cgen))

    if retExpr:
        emit_return(typeInfo, api, cgen)

def emit_with_custom_unwrap(custom):
    def call(typeInfo, api, cgen):
        emit_lock(cgen)
        emit_parameter_encode_preamble_write(typeInfo, api, cgen)
        emit_parameter_encode_copy_unwrap_count(
            typeInfo, api, cgen, customUnwrap=custom)
        emit_parameter_encode_write_packet_info(typeInfo, api, cgen)
        emit_parameter_encode_do_parameter_write(typeInfo, api, cgen)
        emit_parameter_encode_read(typeInfo, api, cgen)
        emit_return_unmarshal(typeInfo, api, cgen)
        emit_pool_free(cgen)
        emit_unlock(cgen)
        emit_return(typeInfo, api, cgen)
    return call

def encode_vkFlushMappedMemoryRanges(typeInfo, api, cgen):
    emit_lock(cgen)
    emit_parameter_encode_preamble_write(typeInfo, api, cgen)
    emit_parameter_encode_copy_unwrap_count(typeInfo, api, cgen)

    def emit_flush_ranges(streamVar):
        cgen.beginIf("!sResourceTracker->usingDirectMapping()")
        cgen.beginFor("uint32_t i = 0", "i < memoryRangeCount", "++i")
        cgen.stmt("auto range = pMemoryRanges[i]")
        cgen.stmt("auto memory = pMemoryRanges[i].memory")
        cgen.stmt("auto size = pMemoryRanges[i].size")
        cgen.stmt("auto offset = pMemoryRanges[i].offset")
        cgen.stmt("uint64_t streamSize = 0")
        cgen.stmt("if (!memory) { %s->write(&streamSize, sizeof(uint64_t)); continue; }" % streamVar)
        cgen.stmt("auto hostPtr = sResourceTracker->getMappedPointer(memory)")
        cgen.stmt("auto actualSize = size == VK_WHOLE_SIZE ? sResourceTracker->getMappedSize(memory) : size")
        cgen.stmt("if (!hostPtr) { %s->write(&streamSize, sizeof(uint64_t)); continue; }" % streamVar)
        cgen.stmt("streamSize = actualSize")
        cgen.stmt("%s->write(&streamSize, sizeof(uint64_t))" % streamVar)
        cgen.stmt("uint8_t* targetRange = hostPtr + offset")
        cgen.stmt("%s->write(targetRange, actualSize)" % streamVar)
        cgen.endFor()
        cgen.endIf()

    emit_parameter_encode_write_packet_info(typeInfo, api, cgen)
    emit_parameter_encode_do_parameter_write(typeInfo, api, cgen)

    emit_flush_ranges(STREAM)

    emit_parameter_encode_read(typeInfo, api, cgen)
    emit_return_unmarshal(typeInfo, api, cgen)
    emit_pool_free(cgen)
    emit_unlock(cgen)
    emit_return(typeInfo, api, cgen)

def encode_vkInvalidateMappedMemoryRanges(typeInfo, api, cgen):
    emit_lock(cgen)
    emit_parameter_encode_preamble_write(typeInfo, api, cgen)
    emit_parameter_encode_copy_unwrap_count(typeInfo, api, cgen)
    emit_parameter_encode_write_packet_info(typeInfo, api, cgen)
    emit_parameter_encode_do_parameter_write(typeInfo, api, cgen)
    emit_parameter_encode_read(typeInfo, api, cgen)
    emit_return_unmarshal(typeInfo, api, cgen)

    def emit_invalidate_ranges(streamVar):
        cgen.beginIf("!sResourceTracker->usingDirectMapping()")
        cgen.beginFor("uint32_t i = 0", "i < memoryRangeCount", "++i")
        cgen.stmt("auto range = pMemoryRanges[i]")
        cgen.stmt("auto memory = pMemoryRanges[i].memory")
        cgen.stmt("auto size = pMemoryRanges[i].size")
        cgen.stmt("auto offset = pMemoryRanges[i].offset")
        cgen.stmt("uint64_t streamSize = 0")
        cgen.stmt("if (!memory) { %s->read(&streamSize, sizeof(uint64_t)); continue; }" % streamVar)
        cgen.stmt("auto hostPtr = sResourceTracker->getMappedPointer(memory)")
        cgen.stmt("auto actualSize = size == VK_WHOLE_SIZE ? sResourceTracker->getMappedSize(memory) : size")
        cgen.stmt("if (!hostPtr) { %s->read(&streamSize, sizeof(uint64_t)); continue; }" % streamVar)
        cgen.stmt("streamSize = actualSize")
        cgen.stmt("%s->read(&streamSize, sizeof(uint64_t))" % streamVar)
        cgen.stmt("uint8_t* targetRange = hostPtr + offset")
        cgen.stmt("%s->read(targetRange, actualSize)" % streamVar)
        cgen.endFor()
        cgen.endIf()

    emit_invalidate_ranges(STREAM)
    emit_pool_free(cgen)
    emit_unlock(cgen)
    emit_return(typeInfo, api, cgen)

def emit_manual_inline(typeInfo, api, cgen):
    cgen.line("#include \"%s_encode_impl.cpp.inl\"" % api.name)

def unwrap_VkNativeBufferANDROID():
    def mapOp(cgen, orig, local):
        cgen.stmt("sResourceTracker->unwrap_VkNativeBufferANDROID(%s, %s)" %
                  (orig.paramName, local.paramName))
    return { "pCreateInfo" : { "mapOp" : mapOp } }

def unwrap_vkAcquireImageANDROID_nativeFenceFd():
    def mapOp(cgen, orig, local):
        cgen.stmt("sResourceTracker->unwrap_vkAcquireImageANDROID_nativeFenceFd(%s, &%s)" %
                  (orig.paramName, local.paramName))
    return { "nativeFenceFd" : { "mapOp" : mapOp } }

custom_encodes = {
    "vkMapMemory" : emit_only_resource_event,
    "vkUnmapMemory" : emit_only_resource_event,
    "vkFlushMappedMemoryRanges" : encode_vkFlushMappedMemoryRanges,
    "vkInvalidateMappedMemoryRanges" : encode_vkInvalidateMappedMemoryRanges,
    "vkCreateImage" : emit_with_custom_unwrap(unwrap_VkNativeBufferANDROID()),
    "vkCreateImageWithRequirementsGOOGLE" : emit_with_custom_unwrap(unwrap_VkNativeBufferANDROID()),
    "vkAcquireImageANDROID" : emit_with_custom_unwrap(unwrap_vkAcquireImageANDROID_nativeFenceFd()),
    "vkQueueFlushCommandsGOOGLE" : emit_manual_inline,
}

class VulkanEncoder(VulkanWrapperGenerator):
    def __init__(self, module, typeInfo):
        VulkanWrapperGenerator.__init__(self, module, typeInfo)

        self.typeInfo = typeInfo

        self.cgenHeader = CodeGen()
        self.cgenHeader.incrIndent()

        self.cgenImpl = CodeGen()

    def onBegin(self,):
        self.module.appendHeader(encoder_decl_preamble)
        self.module.appendImpl(encoder_impl_preamble)

    def onGenCmd(self, cmdinfo, name, alias):
        VulkanWrapperGenerator.onGenCmd(self, cmdinfo, name, alias)

        api = copy.deepcopy(self.typeInfo.apis[name])
        api.parameters.append(makeVulkanTypeSimple(False, "uint32_t", 0, "doLock"))

        self.cgenHeader.stmt(self.cgenHeader.makeFuncProto(api))
        apiImpl = api.withModifiedName("VkEncoder::" + api.name)

        self.module.appendHeader(self.cgenHeader.swapCode())

        if api.name in custom_encodes.keys():
            self.module.appendImpl(self.cgenImpl.makeFuncImpl(
                apiImpl, lambda cgen: custom_encodes[api.name](self.typeInfo, api, cgen)))
        else:
            self.module.appendImpl(self.cgenImpl.makeFuncImpl(apiImpl,
                lambda cgen: emit_default_encoding(self.typeInfo, api, cgen)))

    def onEnd(self,):
        self.module.appendHeader(encoder_decl_postamble)
        self.cgenHeader.decrIndent()


import streamlit as st
import numpy as np
import seaborn as sns
import pandas as pd
import random
import matplotlib.pyplot as plt

st.set_page_config(layout="wide")
st.title("Laboratorio 2")

capital_inicial = 20000
años = [i for i in range(1,18)]

def rendimiento_anual(rendimiento):
    return capital_inicial * (1 + rendimiento)

def cumsum(array):
    cumsum_values=[]
    for index, val in enumerate(array):
        cumsum_values[index] = cumsum_values[index] + val
    return cumsum_values

rendimiento_promedio = st.number_input("Tasa de rendimiento promedio (%)")
desviacion = st.number_input("Desviacion estandar (%)")
rendimientos = []
montos_finales = []
dataset_simulacion_rendimiento = pd.DataFrame(columns=años)
dataset_simulacion_monto = pd.DataFrame(columns=años)

numero_simulaciones = st.number_input("Cantidad de simulaciones")

for i in range(0, int(numero_simulaciones)):
    rendimientos_actuales = np.random.normal(rendimiento_promedio / 100, desviacion/100, 17)
    capital_final = [rendimiento_anual(x) for x in rendimientos_actuales]
    rendimiento_promedio_actual = np.mean(rendimientos_actuales)
    rendimientos.append(rendimiento_promedio_actual)
    monto_final = np.sum(capital_final)
    montos_finales.append(monto_final)
    dataset_simulacion_rendimiento.loc[len(dataset_simulacion_rendimiento)] = rendimientos_actuales
    dataset_simulacion_monto.loc[len(dataset_simulacion_monto)] = capital_final

if len(rendimientos) > 0:
    rendimientos_promedio_por_año = (list(dataset_simulacion_rendimiento.mean(axis=0)))
    monto_promedio_por_año = (list(dataset_simulacion_monto.mean(axis=0)))
    suma_por_iteracion = list(dataset_simulacion_monto.sum(axis=1))
    mejores_rendimientos = dataset_simulacion_rendimiento.iloc[np.argmax(suma_por_iteracion), :]
    peores_rendimientos = dataset_simulacion_rendimiento.iloc[np.argmin(suma_por_iteracion), :]
    montos_acumulados = np.cumsum(monto_promedio_por_año)
    rendimiento_promedio_simulacion = np.mean(rendimientos)
    monto_promedio_simulacion = np.mean(montos_finales)

    '''### Rendimiento promedio total al finalizar los 17 años.'''
    st.write(f'''{round(rendimiento_promedio_simulacion, 2) * 100}%''')
    '''### Monto promedio acumulado al finalizar los 17 años.'''
    st.write(f'''{round(monto_promedio_simulacion, 2)}''')
    '''### Escenario de ahorro pesimista y optimista.'''
    st.write(f'''El mejor escenario es {np.argmax(suma_por_iteracion)} con un monto de  {round(np.max(suma_por_iteracion),2)}''')
    st.table(np.array(mejores_rendimientos))
    st.write(f'''El peor escenario es {np.argmin(suma_por_iteracion)} con un monto de  {round(np.min(suma_por_iteracion),2)}''')
    st.table(np.array(peores_rendimientos))

    '''### Gráfica de los rendimientos obtenidos por cada año.'''
    plot = sns.barplot(x=años, y=rendimientos_promedio_por_año)
    plt.title('Rendimiento Promedio por Año')
    plt.xlabel("Año")
    plt.ylabel("Rendimiento")
    st.pyplot(plot.get_figure())
    '''### Grafica del monto ahorrado por cada año.'''
    plot = sns.barplot(x=años, y=monto_promedio_por_año)
    plt.title('Monto Promedio por Año')
    plt.xlabel("Año")
    plt.ylabel("Ahorro Promedio")
    st.pyplot(plot.get_figure())
    '''###  Grafica del monto acumulado por cada año dentro de los 17 años.'''
    plot = sns.barplot(x=años, y=montos_acumulados)
    plt.title('Montos Acumulados')
    plt.xlabel("Año")
    plt.ylabel("Ahorro Anual")
    st.pyplot(plot.get_figure())


import random
from math import sqrt
from matplotlib import pyplot as plt
from DT.data_manager import Dataset
from DT.data_manager import estimate
from DT.data_manager import make_dataset
from DT.decision_tree import DecisionTree
import numpy as np

TREES_IN_FOREST = 50
MAX_DEPTH = 100
BINARY_TREE = 2
DATASET = 2

def make_tree(general, tree):
    features_sub_amount = int(sqrt(general.features_amount))
    selected_samples = [random.randint(0, general.obj_amount - 1) for _ in range(general.obj_amount)]
    selected_features = set()
    while len(selected_features) != features_sub_amount:
        selected_features.add(random.randint(0, general.features_amount - 1))
    features = np.take(general.features, selected_samples, axis=0)
    targets = np.take(general.targets, selected_samples)
    cut_features = np.take(features, list(selected_features), axis=1)
    tree_dataset = Dataset(np.concatenate((cut_features, targets[:, None]), axis=1))
    print("Building tree #%s" % tree)
    return DecisionTree(tree_dataset, MAX_DEPTH, BINARY_TREE), selected_features

def vote(single_predictions):
    amount = len(single_predictions[0])
    cooperative_predictions = np.empty(amount, dtype=int)
    for obj in range(amount):
        targets, votes = np.unique(single_predictions[:, obj], return_counts=True)
        major = targets[np.argmax(votes)]
        cooperative_predictions[obj] = major
    return cooperative_predictions

def draw_plot(test, train):
    x = np.arange(1, TREES_IN_FOREST + 1)
    plt.title("Influence of forest size on accuracy")
    plt.xlabel("Trees in forest")
    plt.ylabel("Accuracy")
    plt.grid(True)
    plt.plot(x, train, 'b', label="train")
    plt.plot(x, test, 'r', label="test")
    plt.legend()
    plt.show()

test_quality, train_quality = list(), list()
general_train, general_test = make_dataset(str(DATASET))
forest = list()
for forest_size in range(1, TREES_IN_FOREST + 1):
    forest.append(make_tree(general_train, forest_size))
    test_predictions = np.empty((forest_size, general_test.obj_amount))
    train_predictions = np.empty((forest_size, general_test.obj_amount))
    for tree in range(forest_size):
        test_features = np.take(general_test.features, list(forest[tree][1]), axis=1)
        train_features = np.take(general_train.features, list(forest[tree][1]), axis=1)
        test_predictions[tree] = forest[tree][0].predict(test_features)
        train_predictions[tree] = forest[tree][0].predict(train_features)
    test_quality.append(estimate(vote(test_predictions), general_test.targets))
    train_quality.append(estimate(vote(train_predictions), general_train.targets))
draw_plot(test_quality, train_quality)


""" App initialization module."""
import os
from flask import Flask
from backend import config, exercise, training
from backend.extension import api, socketio, mongo, jwt
from backend.config import Struct

def create_app(configs: Struct = None):
    """
    Create and configure the Flask app
    """
    app = Flask("backend")

    # load configuration
    if not configs:
        configs = os.getenv("CONFIG")
        configs = config.load_config_as_object(additional_config_files=configs)

    app.config.from_object(configs)

    register_extensions(app)
    register_blueprints(app)

    app.logger.info("App ready!!")  # pylint: disable=no-member

    return app

def register_extensions(app):
    """ Initialize App extensions."""
    jwt.init_app(app)
    app.logger.debug("jwt.init_app successfully processed.")

    mongo.init_app(app)
    app.logger.debug("mongo.init_app successfully processed.")

    socketio.init_app(app)
    app.logger.debug("socketio.init_app successfully processed.")

def register_blueprints(app):
    """ Store App APIs blueprints."""
    api.init_app(
        app,
        spec_kwargs={
            "info": {"description": "The `Backend` OpenAPI 3.0 specification."},
            "components": {
                "securitySchemes": {
                    "bearerAuth": {
                        "type": "http",
                        "scheme": "bearer",
                        "bearerFormat": "JWT",
                    }
                }
            },
        },
    )

    # register bluprints
    api.register_blueprint(exercise.blueprint.bp)
    api.register_blueprint(training.blueprint.bp)

if __name__ == "__main__":
    socketio.run(create_app(), debug=True, use_reloader=False)


# -*-coding: utf-8 -*-
# author: yangkuii@outlook.com

from tornado.web import url
from handlers import ToshortenHandler, TolongHandler, RedirectLinkHandler

router_list = [
    url(r'/link/shorten', ToshortenHandler, name='get_short'),
    url(r'/link/expend', TolongHandler, name='get_lang'),
    url(r'/(\w*)', RedirectLinkHandler, name='link_redirect')
]


#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Cemre ALPSOY <cemre.alpsoy@agem.com.tr>

import json
import subprocess
from base.plugin.abstract_plugin import AbstractPlugin

class ServiceList(object):
    def __init__(self):
        self.service_list = []

class ServiceListItem:
    def __init__(self, service_name, status, auto):
        self.serviceName = service_name
        self.serviceStatus = status
        self.startAuto = auto

def encode_service_object(obj):
    if isinstance(obj, ServiceListItem):
        return obj.__dict__
    return obj

class GetServices(AbstractPlugin):
    def __init__(self, data, context):
        super(AbstractPlugin, self).__init__()
        self.data = data
        self.context = context
        self.logger = self.get_logger()
        self.message_code = self.get_message_code()

        self.temp_file_name = str(self.generate_uuid())
        self.file_path = '{0}{1}'.format(str(self.Ahenk.received_dir_path()), self.temp_file_name)
        self.service_status = 'systemctl status {}'
        self.isRecordExist = 0

    def handle_task(self):
        try:
            self.logger.debug('Executing command for service list.')
            self.get_service_status()

            self.logger.debug('Command executed.')

            if self.is_exist(self.file_path):
                data = {}
                self.logger.debug(str(self.file_path))
                md5sum = self.get_md5_file(str(self.file_path))
                self.logger.debug('{0} renaming to {1}'.format(self.temp_file_name, md5sum))
                self.rename_file(self.file_path, self.Ahenk.received_dir_path() + '/' + md5sum)
                self.logger.debug('Renamed.' + self.Ahenk.received_dir_path() + '/' + md5sum)
                data['md5'] = md5sum
                self.context.create_response(code=self.message_code.TASK_PROCESSED.value,
                                             message='Servis listesi başarıyla okundu.',
                                             data=json.dumps(data),
                                             content_type=self.get_content_type().TEXT_PLAIN.value)
                self.logger.debug("Execution Info fetched succesfully. ")
                self.logger.debug("Execution Info has sent")
            else:
                self.context.create_response(code=self.message_code.TASK_ERROR.value,
                                             message='Servis listesi getirilemedi')
            self.logger.debug('Service list created successfully')
        except Exception as e:
            self.logger.error(str(e))
            self.context.create_response(code=self.message_code.TASK_ERROR.value,
                                         message='Servis listesi oluşturulurken hata oluştu: ' + str(e))

    def add_file(self, name, status, auto_start):
        if self.isRecordExist == 0:
            self.execute('echo { \\"agent\\" : \\"'+ self.Ahenk.dn() + '\\", \\"service_list\\" :[ >> ' + self.file_path)
            self.isRecordExist = 1
        t_command = 'echo "{ \\"serviceName\\": \\"' + name + '\\", \\"serviceStatus\\": \\"' + status + '\\", \\"startAuto\\":\\"' + auto_start + '\\"}" >> ' + self.file_path
        self.execute(t_command)
        self.execute('echo , >> ' + self.file_path)

    def add_agentDnToFile(self):
        t_command = 'echo "{ \\"agent\\": \\"' + self.Ahenk.dn() +'\\"}" >> ' + self.file_path
        self.execute(t_command)
        self.execute('echo , >> ' + self.file_path)

    def get_service_status(self):
        try:
            (result_code, p_out, p_err) = self.execute("systemctl list-units --type service --all | grep loaded")
            self.create_file(self.file_path)
            # service_list = ServiceList()
            lines = p_out.split('\n')
            for line in lines:
                line_split = line.split(' ')
                service=[]
                for word in line_split:
                    if word != '' :
                        service.append(word)
                if len(service)>0 and '.service' not in service[0]:
                    del service[0]

                if len(service)>0 and '.service' in service[0]: # service[0] = service name, service[1] is loaded, service[2] active or not,
                    result, out, err = self.execute(self.service_status.format(service[0])) # check service is enable or not on auto start
                    auto='INACTIVE'
                    if 'disabled' in out:
                        auto='INACTIVE'
                    elif 'enabled' in out:
                        auto='ACTIVE'

                    if service[2] == 'active':
                        self.add_file(service[0], "ACTIVE", auto)
                    else:
                        self.add_file(service[0], 'INACTIVE',auto)

                    print(service)

            if self.isRecordExist == 1:
                self.execute("sed -i '$ d' " + self.file_path)
                self.execute('echo "]}" >> ' + self.file_path)

        except Exception as e:
            print(str(e))
            self.logger.error(str(e))

def handle_task(task, context):
    plugin = GetServices(task, context)
    plugin.handle_task()


from app.util.str_helper import StringHelper
from app.config.models import Account
import json
import enum
import datetime
from typing import List
import abc

class DevicePaTblRow:
    """ payment agent garage tb的資料 """

    def __init__(self, row_data):
        self.id = row_data.device_pa_args_id
        self.garageId = row_data.garage_id
        self.deviceType = row_data.device_type
        self.deviceUserCode = row_data.device_user_code
        self.deviceName = row_data.device_name
        self.updateUser = row_data.update_user
        self.updateTime = row_data.update_time
        self._parsing(row_data)

    def _parsing(self, row_data):
        pass

class PaDeviceConfApiReq:
    """ pa_device API config request 格式的parser跟轉換成 garage_pa_args table 的資料 """

    def __init__(self, json_data, account: Account):
        self.accountId = int(account.account_id)
        self.gId = int(json_data['garage_id'])

        self.id = json_data['id'] if (type(json_data.get('id', None)) is int) is True else None

        self.deviceType = int(json_data['order_device_type'])
        self.deviceUserCode = json_data['device_user_code']
        self.deviceName = json_data['device_name']

    def gen_pa_device_tbl_data(self):
        """ 產生可以直接寫入device_pa_args table的資料 """
        row_data = {}

        row_data['garage_id'] = self.gId
        row_data['device_type'] = self.deviceType
        row_data['device_user_code'] = self.deviceUserCode
        row_data['device_name'] = self.deviceName
        row_data['update_time'] = datetime.datetime.utcnow()
        row_data['update_user'] = self.accountId

        return row_data

class PaGetDevByTypeApiReq:
    """ get pay_agent devices by device type request 回复的資料 """

    def gen_resp(self, rows_data: List[DevicePaTblRow]):
        """ 產生Api回复資料 """
        resp_list = []
        for row_data in rows_data:
            row = {}
            row['id'] = row_data.id
            row['device_name'] = row_data.deviceName
            row['device_user_code'] = row_data.deviceUserCode
            row['order_device_type'] = row_data.deviceType
            resp_list.append(row)

        return resp_list


import pyttsx3
import datetime
import pygame

# Inicializa a engine de texto para fala
texto_fala = pyttsx3.init()

# Inicializa o mixer do pygame
pygame.mixer.init()

def falar(audio):
    # Configurações da voz
    texto_fala.setProperty("rate", 170)  # Alterar a velocidade da fala
    voz = texto_fala.getProperty('voices')[2]  # Seleciona uma voz (ajuste conforme necessário)
    texto_fala.setProperty('voice', voz.id)
    texto_fala.say(audio)
    texto_fala.runAndWait()

def cumprimento():
    hora = datetime.datetime.now().hour
    if 6 <= hora < 12:
        return "bom dia"
    elif 12 <= hora < 18:
        return "boa tarde"
    elif 18 <= hora <= 24:
        return "boa noite"
    else:
        return "boa madrugada"

def bem_vindo():
    falar("Olá J.T., " + cumprimento() + "!")
    agora = datetime.datetime.now()
    falar("Agora são " + agora.strftime("%H:%M") + " horas, do dia " + agora.strftime("%d de %B de %Y"))
    falar("Jarvis está à sua disposição. Como posso te ajudar?")

def reproduzir_musica(musica):
    pygame.mixer.music.load(musica)
    pygame.mixer.music.play()

if __name__ == "__main__":
    bem_vindo()

    # Exemplo de reprodução de música
    musica = "caminho/para/sua/musica.mp3"
    reproduzir_musica(musica)


"""
Simple chat to interact with the chatbot through terminal.
"""

import numpy as np
import pickle
import json

from tensorflow import keras
from tensorflow.keras.preprocessing.sequence import pad_sequences

# Importing the trained saved model
model = keras.models.load_model('chatbot_trained_model')

# Load the tokenizer from disk
with open('tokenizer.pkl', 'rb') as handle:
    tokenizer = pickle.load(handle)

# Load the label encoder from disk
with open('encoder.pkl', 'rb') as handle:
    label_encoder = pickle.load(handle)

with open("intents.json") as file:
    data = json.load(file)

max_length = 20

# Chat function
while True:

    print("You:")
    text = input()

    if text == 'quit':
        break

    input_data = pad_sequences(tokenizer.texts_to_sequences([text]), truncating='post', maxlen=max_length)

    prediction = model.predict(input_data, verbose=0)

    tag = label_encoder.inverse_transform([np.argmax(prediction)])

    for i in data['intents']:
        if i['tag'] == tag:
            print("Chatbot: " + i['responses'][0])

    print()


import os
import logging
from logging.handlers import RotatingFileHandler
from CirrusCore import cirrus_config

def init_logger():

    debug_level = cirrus_config.Config.get("Log", "DebugLevel", str).upper()
    if debug_level == "INFO":
        debug_level = logging.INFO
    elif debug_level == "WARN":
        debug_level = logging.WARN
    elif debug_level == "ERROR":
        debug_level = logging.ERROR
    elif debug_level == "CRITICAL":
        debug_level = logging.CRITICAL
    else:
        debug_level = logging.DEBUG

    max_mb = cirrus_config.Config.get("Log", "LogMaxSizeMb", int)
    backup_count = cirrus_config.Config.get("Log", "LogBackupCount", int)
    log_filepath = cirrus_config.Config.get("Log", "LogFilePath", str)
    if log_filepath == "default":
        logFile = os.environ["HOME"] + os.sep + 'awsv.log'
    else:
        logFile = log_filepath
        assert os.path.exists(log_filepath), "CONFIG ERROR: invalid path: " + log_filepath

    log_formatter = logging.Formatter(('%(asctime)s [%(levelname)s]'
                                       '[%(module)s:%(funcName)s(%(lineno)d)] %(message)s'))

    handler = RotatingFileHandler(logFile, mode='a', maxBytes=max_mb*1024*1024,
                                  backupCount=backup_count, encoding=None)
    handler.setFormatter(log_formatter)
    handler.setLevel(debug_level)

    app_log = logging.getLogger('root')
    app_log.setLevel(debug_level)
    app_log.addHandler(handler)

    return app_log

class Logger():

    Log = init_logger()

    @classmethod
    def delete_log(cls):
        log_filepath = cirrus_config.Config.get("Log", "LogFilePath", str)
        if log_filepath == "default":
            logFile = os.environ["HOME"] + os.sep + 'awsv.log'
        else:
            logFile = log_filepath

        try:
            os.remove(logFile)
        except IOError:
            pass


import logging
from os import makedirs, path as pth
from typing import Optional

import numpy as np
from openmdao import api as om

from fastoad.model_base import FlightPoint
from fastoad.model_base.propulsion import IOMPropulsionWrapper
from fastoad.module_management.service_registry import RegisterPropulsion
from .base import BaseMissionComp
from ..polar import Polar
from ..segments.registered.cruise import BreguetCruiseSegment

_LOGGER = logging.getLogger(__name__)  # Logger for this module

class MissionComp(om.ExplicitComponent, BaseMissionComp):
    """
    Computes a mission as specified in mission input file.
    """

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.flight_points = None
        self._input_weight_variable_name = ""
        self._engine_wrapper = None

    def initialize(self):
        super().initialize()
        self.options.declare(
            "out_file",
            default="",
            types=str,
            desc="if provided, a csv file will be written at provided path with "
            "all computed flight points.",
        )

    def setup(self):
        super().setup()

        self._engine_wrapper = self.get_engine_wrapper()
        self._engine_wrapper.setup(self)

        self._mission_wrapper.setup(self)

        self._input_weight_variable_name = self._mission_wrapper.get_input_weight_variable_name(
            self.mission_name
        )

        try:
            self.add_input(self.options["reference_area_variable"], np.nan, units="m**2")
        except ValueError:
            pass

        # Global mission outputs
        self.add_output(
            self.name_provider.NEEDED_BLOCK_FUEL.value,
            units="kg",
            desc=f'Needed fuel to complete mission "{self.mission_name}", including reserve fuel',
        )
        self.add_output(
            self.name_provider.CONSUMED_FUEL_BEFORE_INPUT_WEIGHT.value,
            units="kg",
            desc=f'consumed fuel quantity before target mass defined for "{self.mission_name}",'
            f" if any (e.g. TakeOff Weight)",
        )

    def setup_partials(self):
        self.declare_partials(["*"], ["*"], method="fd")

    def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None):
        propulsion_model = self._engine_wrapper.get_model(inputs)
        reference_area = inputs[self.options["reference_area_variable"]]

        self._mission_wrapper.propulsion = propulsion_model
        self._mission_wrapper.reference_area = reference_area

        # This is the default start point, that can be overridden by using the "start"
        # segment in the mission definition.
        start_flight_point = FlightPoint(
            altitude=0.0, mass=inputs[self._input_weight_variable_name], true_airspeed=0.0
        )

        self.flight_points = self._mission_wrapper.compute(start_flight_point, inputs, outputs)

        self._compute_outputs(outputs, self.flight_points)

        self._postprocess_flight_points(self.flight_points)

    def _postprocess_flight_points(self, flight_points):
        def as_scalar(value):
            if isinstance(value, np.ndarray):
                return value.item()
            return value

        flight_points = flight_points.applymap(as_scalar)
        rename_dict = {
            field_name: f"{field_name} [{unit}]"
            for field_name, unit in FlightPoint.get_units().items()
        }
        flight_points.rename(columns=rename_dict, inplace=True)
        if self.options["out_file"]:
            makedirs(pth.dirname(self.options["out_file"]), exist_ok=True)
            flight_points.to_csv(self.options["out_file"])

        return flight_points

    def _compute_outputs(self, outputs, flight_points):
        # Final ================================================================
        start_of_mission = FlightPoint.create(flight_points.iloc[0])
        end_of_mission = FlightPoint.create(flight_points.iloc[-1])
        outputs[self.name_provider.NEEDED_BLOCK_FUEL.value] = (
            start_of_mission.mass - end_of_mission.mass
        )
        reserve_var_name = self._mission_wrapper.get_reserve_variable_name()
        if reserve_var_name in outputs:
            outputs[self.name_provider.NEEDED_BLOCK_FUEL.value] += outputs[
                self._mission_wrapper.get_reserve_variable_name()
            ]
        outputs[
            self.name_provider.CONSUMED_FUEL_BEFORE_INPUT_WEIGHT.value
        ] = self._mission_wrapper.consumed_fuel_before_input_weight

    def get_engine_wrapper(self) -> Optional[IOMPropulsionWrapper]:
        """
        Overloading this method allows to define the engine without relying on the propulsion
        option.

        (useful for tests)

        :return: the engine wrapper instance
        """
        if self.options["propulsion_id"]:
            return RegisterPropulsion.get_provider(self.options["propulsion_id"])

        return None

class AdvancedMissionComp(MissionComp):
    """
    Computes a mission as specified in mission input file.

    Compared to :class:`MissionComp`, it allows:
        - to use an initializer iteration (simple Breguet) at first call.
        - to use the mission as the design mission for the sizing process.
    """

    def initialize(self):
        super().initialize()
        self.options.declare("use_initializer_iteration", default=True, types=bool)
        self.options.declare("is_sizing", default=False, types=bool)

    def setup(self):
        super().setup()

        if self.options["is_sizing"]:
            self.add_output("data:weight:aircraft:sizing_block_fuel", units="kg")
            self.add_output("data:weight:aircraft:sizing_onboard_fuel_at_input_weight", units="kg")

    def compute(self, inputs, outputs, discrete_inputs=None, discrete_outputs=None):
        iter_count = self.iter_count_without_approx
        message_prefix = f"Mission computation - iteration {iter_count:d} : "
        if iter_count == 0 and self.options["use_initializer_iteration"]:
            _LOGGER.info(
                "%sUsing initializer computation. OTHER ITERATIONS NEEDED.", message_prefix
            )
            self._compute_breguet(inputs, outputs)
        else:
            _LOGGER.info("%sUsing mission definition.", message_prefix)
            super().compute(inputs, outputs, discrete_inputs, discrete_outputs)
            if self.options["is_sizing"]:
                outputs["data:weight:aircraft:sizing_block_fuel"] = outputs[
                    self.name_provider.NEEDED_BLOCK_FUEL.value
                ]
                outputs["data:weight:aircraft:sizing_onboard_fuel_at_input_weight"] = (
                    outputs[self.name_provider.NEEDED_BLOCK_FUEL.value]
                    - self._mission_wrapper.consumed_fuel_before_input_weight
                )

    def _compute_breguet(self, inputs, outputs):
        """
        Computes mission using simple Breguet formula at altitude==100m and Mach 0.1
        (but max L/D ratio is assumed anyway)

        Useful only for initiating the computation.

        :param inputs: OpenMDAO input vector
        :param outputs: OpenMDAO output vector
        """
        propulsion_model = self._engine_wrapper.get_model(inputs)

        high_speed_polar = self._get_initial_polar(inputs)
        distance = np.sum(self._mission_wrapper.get_route_ranges(inputs)).item()

        altitude = 100.0
        cruise_mach = 0.1

        breguet = BreguetCruiseSegment(
            target=FlightPoint(ground_distance=distance),
            propulsion=propulsion_model,
            polar=high_speed_polar,
            use_max_lift_drag_ratio=True,
        )
        start_point = FlightPoint(
            mass=inputs[self._input_weight_variable_name],
            altitude=altitude,
            mach=cruise_mach,
        )
        flight_points = breguet.compute_from(start_point)
        end_point = FlightPoint.create(flight_points.iloc[-1])
        outputs[self.name_provider.NEEDED_BLOCK_FUEL.value] = start_point.mass - end_point.mass

    @staticmethod
    def _get_initial_polar(inputs) -> Polar:
        """
        At computation start, polar may be irrelevant and give a very low lift/drag ratio.

        In that case, this method returns a fake polar that has 10.0 as max lift drag ratio.
        Otherwise, the actual cruise polar is returned.
        """
        high_speed_polar = Polar(
            inputs["data:aerodynamics:aircraft:cruise:CL"],
            inputs["data:aerodynamics:aircraft:cruise:CD"],
        )
        use_minimum_l_d_ratio = False
        try:
            if (
                high_speed_polar.optimal_cl / high_speed_polar.cd(high_speed_polar.optimal_cl)
                < 10.0
            ):
                use_minimum_l_d_ratio = True
        except ZeroDivisionError:
            use_minimum_l_d_ratio = True
        if use_minimum_l_d_ratio:
            # We replace by a polar that has at least 10.0 as max L/D ratio
            high_speed_polar = Polar(np.array([0.0, 0.5, 1.0]), np.array([0.1, 0.05, 1.0]))

        return high_speed_polar


import time
from pageObjects import Locators
from selenium.webdriver.common.by import By
from utilities.PageScroll import PageScroll
from Listeners.logger_settings import ui_logger
from utilities.WebDriver_Wait import WebElementWait

class Actions:
    __e_event_actions_xpath = Locators.ACTIONS['actions_click']
    __e_event_candidates_id = Locators.ACTIONS['view_candidates']
    __e_event_slot_id = Locators.ACTIONS['slot_config']
    __e_event_lobby_id = Locators.ACTIONS['lobby']
    __e_event_interview_lobby = Locators.ACTIONS['panel']

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

        self.wait = WebElementWait(self.driver)
        self.scroll = PageScroll(self.driver)

    def event_actions_click(self):
        try:
            self.scroll.up(0, 100)
            self.wait.web_element_wait_click(By.XPATH, self.__e_event_actions_xpath, 'Event_actions_click')
            print('Event Actions - Clicked')
            return True
        except Exception as error:
            ui_logger.error(error)

    def event_view_candidates(self):
        try:
            self.wait.web_element_wait_click(By.ID, self.__e_event_candidates_id, 'Event_candidates_action')
            self.wait.loading()
            print('Event View Applicant - Screen')
            return True
        except Exception as error:
            ui_logger.error(error)

    def event_slot_configuration(self):
        try:
            self.wait.web_element_wait_click(By.ID, self.__e_event_slot_id, 'Event_slot_config_action')
            self.wait.loading()
            print('Event slot configuration - Screen')
            return True
        except Exception as error:
            ui_logger.error(error)

    def event_lobby(self):
        try:
            self.wait.web_element_wait_click(By.ID, self.__e_event_lobby_id, 'View_Event_Lobby')
            self.wait.loading()
            print('View Event Lobby - Screen')
            return True
        except Exception as error:
            ui_logger.error(error)

    def interview_lobby_panel(self):
        try:
            self.wait.web_element_wait_click(By.ID, self.__e_event_interview_lobby, 'Interviewer_Lobby_panel')
            self.wait.loading()
            print('Event_interviewer_lobby - Screen')
            time.sleep(5)
            print('Event_interviewer_lobby - whiteScreen')
            return True
        except Exception as error:
            ui_logger.error(error)


"""
Dominance map plotting functions.
"""

__author__ = "Fabian Neumann (KIT)"
__copyright__ = "Copyright 2019-2020 Fabian Neumann (KIT), GNU GPL 3"

import matplotlib.pyplot as plt
import geopandas as gpd
import numpy as np

from .utils import load_config

opts = load_config()

def subplot_dominance(n, ax, shapes=None, attr="energy", threshold=None, title=""):

    if shapes is None:
        shapes = gpd.read_file(snakemake.input.shapes)

    tech_colors = opts["tech_colors"]

    if attr == "energy":
        n.generators[attr] = n.generators_t.p.multiply(
            n.snapshot_weightings, axis=0
        ).sum(axis=0)

    df = n.generators.groupby(["bus", "carrier"])[attr].max().unstack()

    alpha = df.divide(df.sum(axis=1), axis=0).max(axis=1)
    carrier = df.idxmax(axis=1)

    if threshold is not None:
        carrier.loc[df.max(axis=1) <= threshold] = "none"

    shapes["alpha"] = alpha.values
    shapes["carrier"] = carrier.values

    for c in shapes.carrier.unique():
        shapes.loc[shapes.carrier == c].plot(color=tech_colors[c], ax=ax)

    ax.axis("off")

    ax.set_title(f"$\epsilon$ = {float(title)*100}%", fontsize=18)

def plot_dominance(
    n, n_tmin1, n_tmin5, n_tmin10, attr="energy", threshold=None, shapes=None, fn=None
):

    if threshold is None:
        # MWh for energy, MW for capacity
        threshold = 10e6 if attr == "energy" else 5e3

    if shapes is None:
        shapes = gpd.read_file(snakemake.input.shapes)

    tech_colors = opts["tech_colors"]
    nice_names = opts["nice_names"]

    fig, ax = plt.subplots(1, 4, figsize=(26, 6))

    kwargs = {"attr": attr, "threshold": threshold, "shapes": shapes}
    subplot_dominance(n, ax[0], title="0.0", **kwargs)
    subplot_dominance(n_tmin1, ax[1], title="0.01", **kwargs)
    subplot_dominance(n_tmin5, ax[2], title="0.05", **kwargs)
    subplot_dominance(n_tmin10, ax[3], title="0.1", **kwargs)

    handles = []
    labels = []
    for t in np.sort(n.generators.carrier.unique()):
        handles.append(
            plt.Line2D(
                [0], [0], color=tech_colors[t], marker="o", markersize=8, linewidth=0
            )
        )
        labels.append(nice_names[t])

    handles.append(
        plt.Line2D([0], [0], color="gray", marker="o", markersize=8, linewidth=0)
    )
    if attr == "energy":
        labels.append(f"Energy Generated < {threshold/1e6} TWh")
    else:
        labels.append(f"Total Capacity < {threshold/1e3} GW")

    legend_ax = ax[3]
    legend = legend_ax.legend(
        handles,
        labels,
        loc="upper center",
        bbox_to_anchor=(0.4, 1),
        handletextpad=0.0,
        columnspacing=0.5,
        ncol=2,
        fontsize=13,
        framealpha=0.5,
    )
    legend_ax.add_artist(legend)

    plt.subplots_adjust(hspace=-0.1, wspace=-0.1)

    if fn is not None:
        plt.savefig(fn, bbox_inches="tight")


from django.conf.urls import url
from django.contrib import admin
admin.autodiscover()

from oth import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^display/$', views.display , name='display'),
    url(r'^answer/$', views.answer , name='answer'),
    url(r'^lboard/$', views.lboard , name='lboard'),
    url(r'^rules/$', views.rules , name='rules'),
    url(r'^notif/$', views.getNotif, name='getNotif'),
    # url(r'^correct/$', views.correct, name='correct'),

]


import ccxt,config
import pandas as pd
from ta.trend import EMAIndicator
from ta.trend import MACD
import time
import send_msg as tele
import pandas_ta as ta
import functions as func
import key
from binance.client import Client
import gspread

kesisimmacdsayac =0
kesisimmovaverage =0
longgiris =0
shortgiris =0
sayici_giris_control = 0
sheetsymbolx =0
sheetssymboly =0
macdlast = 0

class Macdema():

    def __init__(self,symbol,timeframe,quantity,buyvalue,sellvalue):
        self.symbol=symbol
        self.kesisimmovaverage=kesisimmovaverage
        self.kesisimmacdsayac=kesisimmacdsayac
        self.longgiris=longgiris
        self.shortgiris=shortgiris
        self.timeframe=timeframe
        self.sayici_giris_control=sayici_giris_control
        self.macdlast=macdlast
        self.quantity=quantity
        self.buyvalue=buyvalue
        self.sellvalue=sellvalue

    def addspread(self, sheetsymbolx, sheetsymboly, movkesx, movkesy,
                  macdkesx, macdkesy, shortgirisx, shortgirisy, longirisx,
                  longgirisy, sayicikontx, sayicikonty):
        gc = gspread.service_account(filename='credentials.json')

        sh = gc.open_by_key('1jRT7SlWoqaEscBFEz9835rsyrh9m1TNR_HfnGpItTHU')
        worksheet = sh.sheet1
        worksheet.update_cell(sheetsymbolx, sheetsymboly, self.symbol)
        worksheet.update_cell(movkesx, movkesy, self.kesisimmovaverage)
        worksheet.update_cell(macdkesx, macdkesy, self.kesisimmacdsayac)
        worksheet.update_cell(shortgirisx, shortgirisy, self.shortgiris)
        worksheet.update_cell(longirisx, longgirisy, self.longgiris)
        worksheet.update_cell(sayicikontx, sayicikonty, self.sayici_giris_control)

    def dfall(self,symbol,timeframe):

        exchange = ccxt.binance({
            "apiKey": config.apiKey,
            "secret": config.secretKey,

            'options': {
                'defaultType': 'future'
            },
            'enableRateLimit': True,
            'adjustForTimeDifference': True
        })
        order_approve = func.open_order_number(self.symbol)

        try:
            if self.shortgiris==1 or self.longgiris==1 or order_approve == 0:#alıs satıstan sonra 100 cycledan sonra tekrar işleme açma
                self.sayici_giris_control += 1
                if self.sayici_giris_control ==15:
                    print(symbol,timeframe,self.sayici_giris_control)
                    self.longgiris=0
                    self.shortgiris=0
                    self.sayici_giris_control=0

            else:
                bars = exchange.fetch_ohlcv(symbol, timeframe=timeframe, since=None, limit=40)#son 40 price cek pd yap
                df = pd.DataFrame(bars, columns=["timestamp", "open", "high", "low", "close", "volume"])

                macddf = df.ta.macd(close='close', fast=12, slow=26, signal=9, append=True)
                client = Client(api_key=key.Pkey, api_secret=key.Skey)
                result = client.futures_account_balance(asset='USDT')  # bir listeden asset cektik
                balance = float(result[6]['withdrawAvailable'])  # with drawal codu ile aldık

                x = (macddf.iloc[:, 1]) #pd 1. colonu al
                self.macdlast = (x.iloc[-1]) #pd 1. kolon son item

                df["slow macd"] = macddf.iloc[:, 0]

                macd = MACD(df["close"])

                df["macd"] = macd.macd_signal()
                # LOAD SLOW EMA
                slowEma = EMAIndicator(df["close"], float(12))

                df["Slow Ema"] = slowEma.ema_indicator()

                # LOAD FAST EMA
                FastEma = EMAIndicator(df["close"], float(26))
                df["Fast Ema"] = FastEma.ema_indicator()

                print (symbol,self.kesisimmacdsayac,self.timeframe)

                if self.shortgiris!=1 and self.longgiris!=1:
                    if self.kesisimmacdsayac == 0:
                        if (df["macd"][len(df.index) - 2] < df["slow macd"][len(df.index) - 2] and df["macd"][
                            len(df.index) - 1] > df["slow macd"][len(df.index) - 1]) or (
                                df["macd"][len(df.index) - 2] > df["slow macd"][len(df.index) - 2] and df["macd"][
                            len(df.index) - 1] < df["slow macd"][len(df.index) - 1]):
                            self.kesisimmacdsayac += 1
                            macdkesisim = "macdkesisim"" "+ self.symbol+" "+ self.timeframe
                            tele.telegram_bot(macdkesisim)
                            print(df["macd"])
                            print(df["slow macd"])
                            print(symbol, "macdkesisim",self.kesisimmacdsayac)
                if self.shortgiris != 1 and self.longgiris != 1:

                    if self.kesisimmovaverage == 0:

                        if (df["Fast Ema"][len(df.index) - 2] < df["Slow Ema"][len(df.index) - 2] and df["Fast Ema"][
                            len(df.index) - 1] > df["Slow Ema"][len(df.index) - 1]) or (
                                df["Fast Ema"][len(df.index) - 2] > df["Slow Ema"][len(df.index) - 2] and df["Fast Ema"][
                            len(df.index) - 1] < df["Slow Ema"][len(df.index) - 1]):
                            self.kesisimmovaverage += 1
                            movkesisim = "movkesisim"+" "+ self.symbol+" "+self.timeframe
                            tele.telegram_bot(movkesisim)
                            print(df["Slow Ema"])
                            print(df["Fast Ema"])
                            print(symbol,"movkesisim",self.kesisimmovaverage)
                    try:
                        price = client.futures_symbol_ticker(symbol=self.symbol, recvWindow=25000)

                        tp_price = func.price_sell_buy(price,self.buyvalue,self.sellvalue)
                        price_sell_new = tp_price[0]
                        price_buy_new = tp_price[1]
                        print(price_buy_new)
                        print(price_sell_new)
                        order_approve = func.open_order_number(self.symbol)
                        print("order approve", order_approve)
                        print("quantity",self.quantity)

                        if balance > 200:
                            if self.kesisimmovaverage == 1 and self.kesisimmacdsayac == 1:
                                if order_approve == 1:
                                    if self.macdlast > 0:
                                        print('long gir')
                                        tele.telegram_bot('long gir-macdmov_strategy')
                                        tele.telegram_bot(symbol)
                                        func.long_position(self.symbol, self.quantity,
                                                           price_sell_new)  # alıs olusturma fonk
                                        self.kesisimmovaverage = 0
                                        self.kesisimmacdsayac = 0
                                        self.longgiris += 1
                                        print(symbol, longgiris, "alis_sonrasi")
                                        time.sleep(10)
                                    else:
                                        print("short_gir")

                                        tele.telegram_bot("short_gir-macdmov_strategy")
                                        tele.telegram_bot(symbol)
                                        func.short_position(self.symbol, self.quantity,
                                                            price_buy_new)  # satıs olusturma fonk
                                        self.kesisimmovaverage = 0
                                        self.kesisimmacdsayac = 0
                                        self.shortgiris += 1
                                        print(symbol, shortgiris, "alis_sonrasi")

                                else:
                                    islemfazla="islem sayisi 5 den fazlastrtegy2"+" "+ self.symbol+" "+self.timeframe
                                    tele.telegram_bot(islemfazla)
                        else:
                            print("balance 200 altında")

                    except:
                          tele.telegram_bot('fiyat alamadı')
        except ccxt.BaseError as Error:
            print("[ERROR] ", Error)

coin2=Macdema('ETHUSDT',"1h",0.015,1.01,0.991)
coin1=Macdema('BTCUSDT',"1h",0.001,1.01,0.991)
coin3=Macdema('ATOMUSDT',"1h",2,1.01,0.991)
coin4=Macdema('EOSUSDT',"1h",20,1.01,0.991)
coin5=Macdema('LITUSDT',"1h",40,1.01,0.991)
coin6=Macdema('BNBUSDT',"1h",0.1,1.01,0.991)

coin7=Macdema('CRVUSDT',"1h",22,1.01,0.991)
coin8=Macdema('THETAUSDT',"1h",20,1.01,0.991)
coin9=Macdema('XRPUSDT',"1h",60,1.01,0.991)
coin10=Macdema('RUNEUSDT',"1h",10,1.01,0.991)
coin11=Macdema('ARUSDT',"1h",2,1.01,0.991)
coin12=Macdema('DOTUSDT',"1h",3,1.01,0.991)
coin13=Macdema('ETCUSDT',"1h",1.5,1.01,0.991)
coin14=Macdema('ALGOUSDT',"1h",80,1.01,0.991)
coin15=Macdema('TRXUSDT',"1h",200,1.01,0.991)
coin16=Macdema('LRCUSDT',"1h",50,1.01,0.991)
coin17=Macdema('SANDUSDT',"1h",25,1.01,0.991)
coin18=Macdema('AVAXUSDT',"1h",1,1.01,0.991)
coin19=Macdema('COTIUSDT',"1h",220,1.01,0.991)
coin20=Macdema('LINKUSDT',"1h",4,1.01,0.991)
coin21=Macdema('NEARUSDT',"1h",9,1.01,0.991)

coin24=Macdema('MATICUSDT',"1h",40,1.01,0.991)
coin25=Macdema('BELUSDT',"1h",30,1.01,0.991)
coin26=Macdema('KNCUSDT',"1h",20,1.01,0.991)
coin27=Macdema('BLZUSDT',"1h",200,1.01,0.991)
coin28=Macdema('KAVAUSDT',"1h",15,1.01,0.991)
coin29=Macdema('CHZUSDT',"1h",250,1.01,0.991)
coin30=Macdema('DASHUSDT',"1h",1,1.01,0.991)
coin31=Macdema('QTUMUSDT',"1h",8,1.01,0.991)
coin32=Macdema('CHRUSDT',"1h",150,1.01,0.991)
coin33=Macdema('OCEANUSDT',"1h",100,1.01,0.991)
coin34=Macdema('ALPHAUSDT',"1h",150,1.01,0.991)

coin2a=Macdema('ETHUSDT',"15m",0.015,1.007,0.993)
coin1a=Macdema('BTCUSDT',"15m",0.001,1.007,0.993)
coin3a=Macdema('ATOMUSDT',"15m",2,1.007,0.993)
coin4a=Macdema('EOSUSDT',"15m",20,1.007,0.993)
coin5a=Macdema('LITUSDT',"15m",40,1.007,0.993)
coin6a=Macdema('BNBUSDT',"15m",0.1,1.007,0.9993)

coin7a=Macdema('CRVUSDT',"15m",22,1.007,0.993)
coin8a=Macdema('THETAUSDT',"15m",20,1.007,0.993)
coin9a=Macdema('XRPUSDT',"15m",60,1.007,0.993)
coin10a=Macdema('RUNEUSDT',"15m",10,1.007,0.993)
coin11a=Macdema('ARUSDT',"15m",2,1.007,0.993)
coin12a=Macdema('DOTUSDT',"15m",3,1.007,0.993)
coin13a=Macdema('ETCUSDT',"15m",1.5,1.007,0.993)
coin14a=Macdema('ALGOUSDT',"15m",80,1.007,0.993)
coin15a=Macdema('TRXUSDT',"15m",200,1.007,0.993)
coin16a=Macdema('LRCUSDT',"15m",50,1.007,0.993)
coin17a=Macdema('SANDUSDT',"15m",25,1.007,0.993)
coin18a=Macdema('AVAXUSDT',"15m",1,1.007,0.993)

coin19a=Macdema('COTIUSDT',"15m",220,1.007,0.993)
coin20a=Macdema('LINKUSDT',"15m",4,1.007,0.993)
coin21a=Macdema('NEARUSDT',"15m",9,1.007,0.993)

coin24a=Macdema('MATICUSDT',"15m",40,1.007,0.993)
coin25a=Macdema('BELUSDT',"15m",30,1.007,0.993)
coin26a=Macdema('KNCUSDT',"15m",20,1.007,0.993)
coin27a=Macdema('BLZUSDT',"15m",200,1.007,0.993)
coin28a=Macdema('KAVAUSDT',"15m",15,1.007,0.993)
coin29a=Macdema('CHZUSDT',"15m",250,1.007,0.993)
coin30a=Macdema('DASHUSDT',"15m",1,1.007,0.993)
coin31a=Macdema('QTUMUSDT',"15m",8,1.007,0.993)
coin32a=Macdema('CHRUSDT',"15m",150,1.007,0.993)
coin33a=Macdema('OCEANUSDT',"15m",100,1.007,0.993)
coin34a=Macdema('ALPHAUSDT',"15m",150,1.007,0.993)

while True:

    coin2.dfall('ETHUSDT',"1h")
    time.sleep(10)
    coin1.dfall('BTCUSDT',"1h")
    time.sleep(10)
    coin3.dfall('ATOMUSDT',"1h")
    time.sleep(10)
    coin4.dfall('EOSUSDT',"1h")
    time.sleep(10)
    coin5.dfall('LITUSDT',"1h")
    time.sleep(10)
    coin6.dfall('BNBUSDT', "1h")
    time.sleep(10)
    coin7.dfall('CRVUSDT',"1h")
    time.sleep(10)
    coin8.dfall('THETAUSDT',"1h")
    time.sleep(10)
    coin9.dfall('XRPUSDT',"1h")
    time.sleep(10)
    coin10.dfall('RUNEUSDT',"1h")
    time.sleep(10)
    coin11.dfall('ARUSDT',"1h")
    time.sleep(10)
    coin12.dfall('DOTUSDT',"1h")
    time.sleep(10)
    coin13.dfall('ETCUSDT',"1h")
    time.sleep(10)
    coin14.dfall('ALGOUSDT',"1h")
    time.sleep(10)
    coin15.dfall('TRXUSDT',"1h")
    time.sleep(10)
    coin16.dfall('LRCUSDT',"1h")
    time.sleep(10)
    coin17.dfall('SANDUSDT',"1h")
    time.sleep(10)
    coin18.dfall('AVAXUSDT', "1h")
    time.sleep(10)
    coin19.dfall('COTIUSDT', "1h")
    time.sleep(10)
    coin20.dfall('LINKUSDT', "1h")
    time.sleep(10)
    coin21.dfall('NEARUSDT', "1h")
    time.sleep(10)

    coin24.dfall('MATICUSDT', "1h")
    time.sleep(10)
    coin25.dfall('BELUSDT', "1h")
    time.sleep(10)
    coin26.dfall('KNCUSDT', "1h")
    time.sleep(10)
    coin27.dfall('BLZUSDT', "1h")
    time.sleep(10)
    coin28.dfall('KAVAUSDT', "1h")
    time.sleep(10)
    coin29.dfall('CHZUSDT', "1h")
    time.sleep(10)
    coin30.dfall('DASHUSDT', "1h")
    time.sleep(10)
    coin31.dfall('QTUMUSDT', "1h")
    time.sleep(10)
    coin32.dfall('CHRUSDT', "1h")
    time.sleep(10)
    coin33.dfall('OCEANUSDT', "1h")
    time.sleep(10)
    coin34.dfall('ALPHAUSDT', "1h")
    time.sleep(10)

    coin2a.dfall('ETHUSDT', "15m")
    time.sleep(10)
    coin1a.dfall('BTCUSDT', "15m")
    time.sleep(10)
    coin3a.dfall('ATOMUSDT', "15m")
    time.sleep(10)
    coin4a.dfall('EOSUSDT', "15m")
    time.sleep(10)
    coin5a.dfall('LITUSDT', "15m")
    time.sleep(10)
    coin6a.dfall('BNBUSDT', "15m")
    time.sleep(10)
    coin7a.dfall('CRVUSDT', "15m")
    time.sleep(10)
    coin8a.dfall('THETAUSDT', "15m")
    time.sleep(10)
    coin9a.dfall('XRPUSDT', "15m")
    time.sleep(10)
    coin10a.dfall('RUNEUSDT', "15m")
    time.sleep(10)
    coin11a.dfall('ARUSDT', "15m")
    time.sleep(10)
    coin12a.dfall('DOTUSDT', "15m")
    time.sleep(10)
    coin13a.dfall('ETCUSDT', "15m")
    time.sleep(10)
    coin14a.dfall('ALGOUSDT', "15m")
    time.sleep(10)
    coin15a.dfall('TRXUSDT',"15m")
    time.sleep(10)
    coin16a.dfall('LRCUSDT', "15m")
    time.sleep(10)
    coin17a.dfall('SANDUSDT', "15m")
    time.sleep(10)
    coin18a.dfall('AVAXUSDT', "15m")
    time.sleep(10)
    coin19a.dfall('COTIUSDT', "15m")
    time.sleep(10)
    coin20a.dfall('LINKUSDT', "15m")
    time.sleep(10)
    coin21a.dfall('NEARUSDT', "15m")
    time.sleep(10)

    coin24a.dfall('MATICUSDT', "15m")
    time.sleep(10)
    coin25a.dfall('BELUSDT', "15m")
    time.sleep(10)
    coin26a.dfall('KNCUSDT', "15m")
    time.sleep(10)
    coin27a.dfall('BLZUSDT', "15m")
    time.sleep(10)
    coin28a.dfall('KAVAUSDT', "15m")
    time.sleep(10)
    coin29a.dfall('CHZUSDT', "15m")
    time.sleep(10)
    coin30a.dfall('DASHUSDT', "15m")
    time.sleep(10)
    coin31a.dfall('QTUMUSDT', "15m")
    time.sleep(10)
    coin32a.dfall('CHRUSDT', "15m")
    time.sleep(10)
    coin33a.dfall('OCEANUSDT', "15m")
    time.sleep(10)
    coin34a.dfall('ALPHAUSDT', "15m")
    time.sleep(10)

    coin2a.addspread(1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6)
    time.sleep(10)
    coin1a.addspread(2, 1, 2, 2, 2, 3, 2, 4, 2, 5, 2, 6)
    time.sleep(10)

    coin3a.addspread(3, 1, 3, 2, 3, 3, 3, 4, 3, 5, 3, 6)
    time.sleep(10)

    coin4a.addspread(4, 1, 4, 2, 4, 3, 4, 4, 4, 5, 4, 6)
    time.sleep(10)

    coin5a.addspread(5, 1, 5, 2, 5, 3, 5, 4, 5, 5, 5, 6)
    time.sleep(10)

    coin6a.addspread(6, 1, 6, 2, 6, 3, 6, 4, 6, 5, 6, 6)
    time.sleep(10)

    coin7a.addspread(7, 1, 7, 2, 7, 3, 7, 4, 7, 5, 7, 6)
    time.sleep(10)

    coin8a.addspread(8, 1, 8, 2, 8, 3, 8, 4, 8, 5, 8, 6)
    time.sleep(10)

    coin9a.addspread(9, 1, 9, 2, 9, 3, 9, 4, 9, 5, 9, 6)
    time.sleep(10)

    coin10a.addspread(10, 1, 10, 2, 10, 3, 10, 4, 10, 5, 10, 6)
    time.sleep(10)

    coin11a.addspread(11, 1, 11, 2, 11, 3, 11, 4, 11, 5, 11, 6)
    time.sleep(10)

    coin12a.addspread(12, 1, 12, 2, 12, 3, 12, 4, 12, 5, 12, 6)
    time.sleep(10)
    coin13a.addspread(13, 1, 13, 2, 13, 3, 13, 4, 13, 5, 13, 6)
    time.sleep(10)
    coin14a.addspread(14, 1, 14, 2, 14, 3, 14, 4, 14, 5, 14, 6)
    time.sleep(10)
    coin15a.addspread(15, 1, 15, 2, 15, 3, 15, 4, 15, 5, 15, 6)
    time.sleep(10)
    coin16a.addspread(16, 1, 16, 2, 16, 3, 16, 4, 16, 5, 16, 6)
    time.sleep(10)
    coin17a.addspread(17, 1, 17, 2, 17, 3, 17, 4, 17, 5, 17, 6)
    time.sleep(10)
    coin18a.addspread(18, 1, 18, 2, 18, 3, 18, 4, 18, 5, 18, 6)
    time.sleep(10)
    coin19a.addspread(19, 1, 19, 2, 19, 3, 19, 4, 19, 5, 19, 6)
    time.sleep(10)
    coin20a.addspread(20, 1, 20, 2, 20, 3, 20, 4, 20, 5, 20, 6)
    time.sleep(10)
    coin21a.addspread(21, 1, 21, 2, 21, 3, 21, 4, 21, 5, 21, 6)
    time.sleep(10)

    coin24a.addspread(24, 1, 24, 2, 24, 3, 24, 4, 24, 5, 24, 6)
    time.sleep(10)
    coin25a.addspread(25, 1, 25, 2, 25, 3, 25, 4, 25, 5, 25, 6)
    time.sleep(10)
    coin26a.addspread(26, 1, 26, 2, 26, 3, 26, 4, 26, 5, 26, 6)
    time.sleep(10)
    coin27a.addspread(27, 1, 27, 2, 27, 3, 27, 4, 27, 5, 27, 6)
    time.sleep(10)
    coin28a.addspread(28, 1, 28, 2, 28, 3, 28, 4, 28, 5, 28, 6)
    time.sleep(10)
    coin29a.addspread(29, 1, 29, 2, 29, 3, 29, 4, 29, 5, 29, 6)
    time.sleep(10)
    coin30a.addspread(30, 1, 30, 2, 30, 3, 30, 4, 30, 5, 30, 6)
    time.sleep(10)
    coin31a.addspread(31, 1, 31, 2, 31, 3, 31, 4, 31, 5, 31, 6)
    time.sleep(10)
    coin32a.addspread(32, 1, 32, 2, 32, 3, 32, 4, 32, 5, 32, 6)
    time.sleep(10)
    coin33a.addspread(33, 1, 33, 2, 33, 3, 33, 4, 33, 5, 33, 6)
    time.sleep(10)
    coin34a.addspread(34, 1, 34, 2, 34, 3, 34, 4, 34, 5, 34, 6)
    time.sleep(10)
    tele.telegram_bot('server online2')

    time.sleep(300)


from flask import Flask, request, redirect, render_template, session, flash
from mysqlconnection import MySQLConnector
app = Flask(__name__)
mysql = MySQLConnector(app,'friendsdb')
@app.route('/')
def index():
    query = "SELECT * FROM friends"                           # define your query
    friends = mysql.query_db(query)                           # run query with query_db()
    return render_template('friends.html', all_friends=friends) # pass data to our template

@app.route('/friends', methods=['POST'])
def create():
    lname= request.form.get('last_name')
    fname= request.form.get('first_name')
    occup=request.form.get('occupation')

    print(mysql.query_db("INSERT INTO friends VALUES (DEFAULT,'%s','%s','%s',default,Default)"%(lname,fname,occup)))

    return redirect('/')
app.run(debug=True,host='0.0.0.0',port=9001)


import pandas as pd
import ccxt, config

import time

import firebase_admin
from firebase_admin import credentials, firestore
from tradingview_ta import TA_Handler, Interval, Exchange
import calendar

longgiris = 0
shortgiris = 0
sayici_giris_control = 0
sheetsymbolx = 0
sheetssymboly = 0
macdlast = 0
engulfing = 0
buysignallast = 0
sellsignallast = 0
coipricefloat = 0
sellsignallast1 = 0
sellsignallast2 = 0
str_sellsignallast1 = 0
str_sellsignallast2 = 0
kimlik = credentials.Certificate("ema_class.json")

app = firebase_admin.initialize_app(kimlik)

class Macdema():

    def __init__(self, symbol, timeframe, quantity, buyvalue, sellvalue):
        self.symbol = symbol
        self.longgiris = longgiris
        self.shortgiris = shortgiris
        self.timeframe = timeframe
        self.sayici_giris_control = sayici_giris_control
        self.quantity = quantity
        self.buyvalue = buyvalue
        self.sellvalue = sellvalue
        self.buysignallast = buysignallast
        self.sellsignallast = sellsignallast
        self.sellsignallast1 = sellsignallast1
        self.sellsignallast2 = sellsignallast2
        self.str_sellsignallast1 = str_sellsignallast1
        self.str_sellsignallast2 = str_sellsignallast2

        self.coipricefloat = coipricefloat

    def dfall(self, symbol, timeframe):

        try:
            handler = TA_Handler(
                symbol=symbol,
                exchange="BINANCE",
                screener="crypto",
                interval=timeframe,
                timeout=None,
                proxies={'http': '47.242.84.173:3128', 'http': '181.205.20.195:999', 'http': '192.111.135.17:18302',
                         'http': '103.108.228.185:7497'}
            )

            analysis = handler.get_analysis().summary

            analysis_str = str(analysis)

            symbolrec = analysis['RECOMMENDATION']
            dt = time.gmtime()
            ts = calendar.timegm(dt)
            ts_str = str(ts)

            x = self.symbol + self.timeframe + ts_str

            db = firestore.client()  # db e baglantı

            docs = db.collection (self.symbol + self.timeframe).get()

            for doc in docs:
                key = doc.id
                db.collection(self.symbol + self.timeframe).document(key).delete()
                print("silindi" + self.symbol + self.timeframe)

            document = db.collection(self.symbol + self.timeframe).document(x)
            docId = document.id
            document.set({
                "id": ts_str,

                "position": symbolrec,

            })

        except :
            print("silindi2")

coin2 = Macdema('API3USDT', "1h", 15, 1.007, 0.993)
coin1 = Macdema('WOOUSDT', "1h", 100, 1.007, 0.993)
coin3 = Macdema('CELOUSDT', "1h", 30, 1.007, 0.993)
coin4 = Macdema('ARPAUSDT', "1h", 600, 1.007, 0.993)
coin5 = Macdema('LPTUSDT', "1h", 3, 1.007, 0.993)
coin6 = Macdema('KLAYUSDT', "1h", 3, 1.007, 0.993)

coin7 = Macdema('OMGUSDT', "1h", 15, 1.007, 0.993)
coin8 = Macdema('OPUSDT', "1h", 40, 1.007, 0.993)
coin9 = Macdema('UNFIUSDT', "1h", 6, 1.007, 0.993)

coin11 = Macdema('ARUSDT', "1h", 2, 1.007, 0.993)
coin12 = Macdema('DOTUSDT', "1h", 3, 1.007, 0.993)
coin13 = Macdema('ETCUSDT', "1h", 1.5, 1.007, 0.993)
coin14 = Macdema('ALGOUSDT', "1h", 80, 1.007, 0.993)
coin15 = Macdema('TRXUSDT', "1h", 200, 1.007, 0.993)
coin16 = Macdema('LRCUSDT', "1h", 50, 1.007, 0.993)
coin17 = Macdema('SANDUSDT', "1h", 25, 1.007, 0.993)

coin18 = Macdema('YFIUSDT', "1h", 0.005, 1.007, 0.993)
coin19 = Macdema('MASKUSDT', "1h", 3, 1.007, 0.993)
coin20 = Macdema('SUSHIUSDT', "1h", 30, 1.007, 0.993)

coin21 = Macdema('NEARUSDT', "1h", 9, 1.007, 0.993)
coin24 = Macdema('MATICUSDT', "1h", 40, 1.007, 0.993)
coin25 = Macdema('BELUSDT', "1h", 30, 1.007, 0.993)
coin26 = Macdema('DOGEUSDT', "1h", 20, 1.007, 0.993)
coin27 = Macdema('BLZUSDT', "1h", 200, 1.007, 0.993)
coin28 = Macdema('KAVAUSDT', "1h", 15, 1.007, 0.993)
coin29 = Macdema('CHZUSDT', "1h", 250, 1.007, 0.993)

coin31 = Macdema('QTUMUSDT', "1h", 8, 1.007, 0.993)
coin32 = Macdema('CHRUSDT', "1h", 150, 1.007, 0.993)
coin33 = Macdema('OCEANUSDT', "1h", 100, 1.007, 0.993)
coin34 = Macdema('ALPHAUSDT', "1h", 150, 1.007, 0.993)
coin35 = Macdema('XRPUSDT', "1h", 100, 1.006, 0.994)
coin36 =  Macdema('BNBUSDT', "1h", 0.13, 1.006, 0.994)
coin37 = Macdema('ATOMUSDT', "1h", 4, 1.006, 0.994)

coin2a = Macdema('API3USDT', "2h", 20, 1.007, 0.993)
coin1a = Macdema('WOOUSDT', "2h", 125, 1.007, 0.993)
coin3a = Macdema('CELOUSDT', "2h", 40, 1.007, 0.993)
coin4a = Macdema('ARPAUSDT', "2h", 700, 1.007, 0.993)
coin5a = Macdema('LPTUSDT', "2h", 4, 1.007, 0.993)
coin6a = Macdema('KLAYUSDT', "2h", 3, 1.007, 0.993)

coin7a = Macdema('OMGUSDT', "2h", 20, 1.007, 0.993)
coin8a = Macdema('OPUSDT', "2h", 55, 1.007, 0.993)
coin9a = Macdema('UNFIUSDT', "2h", 8, 1.007, 0.993)

coin11a = Macdema('ARUSDT', "2h", 3, 1.007, 0.993)
coin12a = Macdema('DOTUSDT', "2h", 4, 1.007, 0.993)
coin13a = Macdema('ETCUSDT', "2h", 1.8, 1.007, 0.993)
coin14a = Macdema('ALGOUSDT', "2h", 100, 1.007, 0.993)
coin15a = Macdema('TRXUSDT', "2h", 240, 1.007, 0.993)
coin16a = Macdema('LRCUSDT', "2h", 70, 1.007, 0.993)
coin17a = Macdema('SANDUSDT', "2h", 30, 1.007, 0.993)

coin18a = Macdema('YFIUSDT', "2h", 0.005, 1.007, 0.993)
coin19a = Macdema('MASKUSDT', "2h", 3, 1.007, 0.993)
coin20a = Macdema('SUSHIUSDT', "2h", 30, 1.007, 0.993)
coin21a = Macdema('NEARUSDT', "2h", 12, 1.007, 0.993)
coin24a = Macdema('MATICUSDT', "2h", 45, 1.007, 0.993)
coin25a = Macdema('BELUSDT', "2h", 55, 1.007, 0.993)
coin26a = Macdema('DOGEUSDT', "2h", 66,1.007, 0.993)
coin27a = Macdema('BLZUSDT', "2h", 77, 1.007, 0.993)
coin28a = Macdema('KAVAUSDT', "2h", 20, 1.007, 0.993)
coin29a = Macdema('CHZUSDT', "2h", 280, 1.007, 0.993)

coin31a = Macdema('QTUMUSDT', "2h", 10, 1.007, 0.993)
coin32a = Macdema('CHRUSDT', "2h", 180, 1.007, 0.993)
coin33a = Macdema('OCEANUSDT', "2h", 90, 1.007, 0.993)
coin34a = Macdema('ALPHAUSDT', "2h", 170, 1.007, 0.993)
coin35a = Macdema('XRPUSDT', "2h", 100, 1.006, 0.994)

coin36a = Macdema('BNBUSDT', "2h", 0.13, 1.006, 0.994)
coin37a = Macdema('ATOMUSDT', "2h", 4, 1.006, 0.994)

while True:
    coin2.dfall('API3USDT', "1h")
    time.sleep(2)
    coin1.dfall('WOOUSDT', "1h")
    time.sleep(2)
    coin3.dfall('CELOUSDT', "1h")
    time.sleep(2)
    coin4.dfall('ARPAUSDT', "1h")
    time.sleep(2)
    coin5.dfall('LPTUSDT', "1h")
    time.sleep(2)
    coin6.dfall('KLAYUSDT', "1h")
    time.sleep(2)

    coin7.dfall('OMGUSDT', "1h")
    time.sleep(2)
    coin8.dfall('OPUSDT', "1h")
    time.sleep(2)
    coin9.dfall('UNFIUSDT', "1h")
    time.sleep(2)
    coin11.dfall('ARUSDT', "1h")
    time.sleep(2)
    coin12.dfall('DOTUSDT', "1h")
    time.sleep(2)
    coin13.dfall('ETCUSDT', "1h")
    time.sleep(2)
    coin14.dfall('ALGOUSDT', "1h")
    time.sleep(2)
    coin15.dfall('TRXUSDT', "1h")
    time.sleep(2)
    coin16.dfall('LRCUSDT', "1h")
    time.sleep(2)
    coin17.dfall('SANDUSDT', "1h")
    time.sleep(2)

    coin18.dfall('YFIUSDT', "1h")
    time.sleep(30)
    coin19.dfall('MASKUSDT', "1h")
    time.sleep(30)

    coin20.dfall('SUSHIUSDT', "1h")
    time.sleep(30)

    coin21.dfall('NEARUSDT', "1h")
    time.sleep(2)

    coin24.dfall('MATICUSDT', "1h")
    time.sleep(2)
    coin25.dfall('BELUSDT', "1h")
    time.sleep(2)
    coin26.dfall('DOGEUSDT', "1h")
    time.sleep(2)
    coin27.dfall('BLZUSDT', "1h")
    time.sleep(2)
    coin28.dfall('KAVAUSDT', "1h")
    time.sleep(2)
    coin29.dfall('CHZUSDT', "1h")
    time.sleep(2)

    coin31.dfall('QTUMUSDT', "1h")
    time.sleep(2)
    coin32.dfall('CHRUSDT', "1h")
    time.sleep(2)
    coin33.dfall('OCEANUSDT', "1h")
    time.sleep(2)
    coin34.dfall('ALPHAUSDT', "1h")
    time.sleep(2)
    coin35.dfall('XRPUSDT', "1h")
    time.sleep(2)
    coin36.dfall('BNBUSDT', "1h")
    time.sleep(2)
    coin37.dfall('ATOMUSDT', "1h")
    time.sleep(2)

    coin2a.dfall('API3USDT', "2h")
    time.sleep(2)
    coin1a.dfall('WOOUSDT', "2h")
    time.sleep(2)
    coin3a.dfall('CELOUSDT', "2h")
    time.sleep(2)
    coin4a.dfall('ARPAUSDT', "2h")
    time.sleep(2)
    coin5a.dfall('LPTUSDT', "2h")
    time.sleep(2)
    coin6a.dfall('KLAYUSDT', "2h")
    time.sleep(2)

    coin7a.dfall('OMGUSDT', "2h")
    time.sleep(2)
    coin8a.dfall('OPUSDT', "2h")
    time.sleep(2)
    coin9a.dfall('UNFIUSDT', "2h")
    time.sleep(2)
    coin11a.dfall('ARUSDT', "2h")
    time.sleep(2)
    coin12a.dfall('DOTUSDT', "2h")
    time.sleep(2)
    coin13a.dfall('ETCUSDT', "2h")
    time.sleep(2)
    coin14a.dfall('ALGOUSDT', "2h")
    time.sleep(2)
    coin15a.dfall('TRXUSDT', "2h")
    time.sleep(2)
    coin16a.dfall('LRCUSDT', "2h")
    time.sleep(2)
    coin17a.dfall('SANDUSDT', "2h")
    time.sleep(2)

    coin18a.dfall('YFIUSDT', "2h")
    time.sleep(30)
    coin19a.dfall('MASKUSDT', "2h")
    time.sleep(30)

    coin20a.dfall('SUSHIUSDT', "2h")
    time.sleep(30)
    coin21a.dfall('NEARUSDT', "2h")
    time.sleep(2)

    coin24a.dfall('MATICUSDT', "2h")
    time.sleep(2)
    coin25a.dfall('BELUSDT', "2h")
    time.sleep(2)
    coin26a.dfall('DOGEUSDT', "2h")
    time.sleep(2)
    coin27a.dfall('BLZUSDT', "2h")
    time.sleep(2)
    coin28a.dfall('KAVAUSDT', "2h")
    time.sleep(2)
    coin29a.dfall('CHZUSDT', "2h")
    time.sleep(2)

    coin31a.dfall('QTUMUSDT', "2h")
    time.sleep(2)
    coin32a.dfall('CHRUSDT', "2h")
    time.sleep(2)
    coin33a.dfall('OCEANUSDT', "2h")
    time.sleep(2)
    coin34a.dfall('ALPHAUSDT', "2h")
    time.sleep(2)
    coin35a.dfall('XRPUSDT', "2h")
    time.sleep(2)
    coin36a.dfall('BNBUSDT', "2h")
    time.sleep(2)
    coin37a.dfall('ATOMUSDT', "2h")
    time.sleep(2)

    time.sleep(3600)