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

"""
# File       : fingetprint_scan.py
# Time       ：2022/03/10
# version    ：python 3
# Description：

# Author：bywalks
# Blog：http://www.bywalks.com
# Github：https://github.com/bywalks
"""

import os
import sys
import time
import json

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from vcommon.ESHelper import ESHelper
from vconfig.config import *
from vconfig.log import logger

CUR_DIR = os.path.dirname(os.path.abspath(__file__))

class FingerprintScan(object):
    def __init__(self):
        self.fingerprint_path = CUR_DIR + "/tools/whatweb/whatweb"
        self.fingerprint_cmd = f"{self.fingerprint_path} -a 3 --follow-redirect never -U 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36'"
        self.fingerprint_resultDir = CUR_DIR + "/results/fingerprint"
        self.urls_resultDir = CUR_DIR + "/results/urls"
        self.es_helper = ESHelper(ES_HOSTS, ES_USER, ES_PASSWD)
        self.scanner_name = "fingerprint_scan"
        self.program_index = "program-assets-1"
        self.domain_index = "domain-assets-1"

    def searchallprogramdomain(self):
        logger.log('INFOR', "[+]Start search all program domains.")
        query = {'query': {'match_all': {}}}
        res = self.es_helper.query_domains_by_dsl(self.program_index,dsl=query)
        pdomain_list = []
        if res:
            for each in res:
                pdomain_list.append(each['_source']['domain'].lower())
        return pdomain_list

    def read_new_url_list_by_pdomain(self, begin_time=None, pdomain=None):
        '''根据筛选条件读取url的list'''
        if begin_time == None:
            begin_time = "2010-01-01T12:10:30Z"
        dsl = {
            "query": {
                "bool": {
                    "must":
                        {"match_phrase": {"pdomain": pdomain}},
                    "filter": [
                        {
                            "range": {
                                "update_time": {
                                    "gte": begin_time,
                                    "lt": "2028-01-01T12:10:30Z"
                                }
                            }
                        }
                    ]
                }
            },
            "_source": ["url", "subdomain"]
        }
        new_url_list = self.es_helper.query_domains_by_dsl(self.domain_index, dsl)
        return new_url_list

    def read_new_url_list_by_time(self, gt=None, lt=None):
        '''根据筛选条件读取url的list'''
        if gt == None:
            gt = "2010-01-01T12:10:30Z"
        if lt == None:
            lt = "2028-01-01T12:10:30Z"
        dsl = {
            "query": {
                "bool": {
                    "filter": [
                        {
                            "range": {
                                "update_time": {
                                    "gte": gt,
                                    "lt": lt
                                }
                            }
                        }
                    ]
                }
            },
            "_source": ["url"]
        }
        new_url_list = self.es_helper.query_domains_by_dsl(self.domain_index, dsl)
        return new_url_list

    def read_url_list_by_time(self, gt=None, lt=None):
        '''根据筛选条件读取url的list'''
        if gt == None:
            gt = "2010-01-01T12:10:30Z"
        if lt == None:
            lt = "2028-01-01T12:10:30Z"
        dsl = {
            "query": {
                "bool": {
                    "filter": [
                        {
                            "range": {
                                "launched_at": {
                                    "gte": gt,
                                    "lt": lt
                                }
                            }
                        }
                    ]
                }
            },
            "_source": ["url"]
        }
        new_url_list = self.es_helper.query_domains_by_dsl(self.domain_index, dsl)
        return new_url_list

    def read_url_list(self, program=None, pdomain=None, subdomain=None):
        '''根据筛选条件读取url的list'''
        if subdomain != None:
            dsl = {
                "query": {
                    "bool": {
                        "must": [
                            {"match_phrase": {"subdomain": str(subdomain)}}
                        ]
                    }
                },
                "_source": ["url", "subdomain"]
            }
        elif pdomain != None:
            dsl = {
                "query": {
                    "bool": {
                        "must": [
                            {"match_phrase": {"pdomain": str(pdomain)}}
                        ]
                    }
                },
                "_source": ["url", "subdomain"]
            }
        elif program != None:
            dsl = {
                "query": {
                    "bool": {
                        "must": [
                            {"match_phrase": {"program": str(program)}}
                        ]
                    }
                },
                "_source": ["url", "subdomain"]
            }
        else:
            dsl = {
                "query": {"match_all": {}},
                "_source": ["url", "subdomain"]
            }
        url_list = self.es_helper.query_domains_by_dsl(self.domain_index, dsl)
        return url_list

    def deal_url_list(self, url_list=None):
        '''根据筛选条件读取url的list'''
        return_url_list = []
        for each in url_list:
            each = each["_source"]["url"]
            return_url_list.append(each)
        return return_url_list

    def startFingerprintFileScan(self, program):
        '''
        /root/vuln_scan/vulscan/tools/whatweb/whatweb -a 3 -v --follow-redirect=never -U='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36' -i test.txt --log-json 123.json
        /root/WhatWeb-0.5.5/whatweb -a 3 -v --follow-redirect=never -U 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36' -i test.txt --log-json 123.json
        '''
        logger.log('INFOR', f"[+]Start scan program {program}\'s fingerprint")
        urls_output_txt = f"{self.urls_resultDir}/{program}_urls_output.txt"
        fingerprint_output_file = f"{self.fingerprint_resultDir}/{program}_fingerprint_output.json"
        logger.log('INFOR', urls_output_txt)
        if os.path.exists(fingerprint_output_file):
            os.remove(fingerprint_output_file)
        if os.path.exists(urls_output_txt):
            fingerprint_lines = f"{self.fingerprint_cmd} --log-json {fingerprint_output_file} -i {urls_output_txt}"
            logger.log('INFOR', fingerprint_lines)
            # 开启fingerprint
            os.system(fingerprint_lines)

    def write_url_list(self, program, asset_list):
        urls_output_txt = f"{self.urls_resultDir}/{program}_urls_output.txt"
        if os.path.exists(urls_output_txt):
            os.remove(urls_output_txt)
        with open(urls_output_txt, 'a') as f:
            for asset_info in asset_list:
                asset_info_url = asset_info['_source']['url']
                # asset_info_url = asset_info['url']
                if asset_info_url != None:
                    f.write(asset_info_url + "\n")
        logger.log('INFOR', f'[+]添加-[{program}]-扫描文件成功')

    def write_fingerprint_file_list(self, program):
        fingerprint_file_output_file = f"{self.fingerprint_resultDir}/{program}_fingerprint_output.json"
        if os.path.exists(fingerprint_file_output_file):
            with open(fingerprint_file_output_file, 'r') as f:
                '''
                ADD：plugin
                '''
                f = json.load(f)
                for each in f:
                    plugin = each['plugins']
                    title = "None"
                    if "Title" in plugin:
                        title = plugin['Title']['string'][0]
                        plugin.pop('Title')
                    url = each['target']
                    plugin = str(plugin)
                    self.update_finger(url=url,plugin=plugin,title=title)
                    logger.log('INFOR', f'[+]update finger {url}:{plugin}')

    def update_finger(self, url=None, plugin=None, title=None):
        if url != None and plugin != None:
            dsl = {
                "query": {
                    "bool": {
                        "must": [
                            {
                                "match_phrase": {
                                    "url": str(url)
                                }
                            }
                        ]
                    }
                },
                "script": {
                    "source": "ctx._source.fingerprint=params.fingerprint;ctx._source.title=params.title",
                    "params":{
                        "fingerprint": str(plugin),
                        "title": str(title)
                    },
                    "lang": "painless"
                }
            }
            self.es_helper.update_by_query(index=self.domain_index,dsl=dsl)

    def finger_scan_all(self):
        # 1:read all pdomain
        all_pdomain_list = self.searchallprogramdomain()

        pdomain_len = len(all_pdomain_list)

        # 2:write all pdomain file
        i = 1
        for pdomain in all_pdomain_list:
            logger.log('INFOR',"[Fingerprint] 开始写入父域第" + str(i) + "/" + str(pdomain_len) + "-" + pdomain)
            asset_list = self.read_url_list(pdomain=pdomain)
            if asset_list != None:
                pdomain_name = self.es_helper.remove_http_or_https(pdomain).split("/")[0].replace("*.","").replace("*","")
                self.write_url_list(program=pdomain_name,asset_list=asset_list)
            i = i + 1

        # 3:start scan fingerprint
        i = 1
        for pdomain in all_pdomain_list:
            logger.log('INFOR',"[Fingerprint] 开始扫描第" + str(i) + "/" + str(pdomain_len) + "-" + pdomain)
            pdomain_name = self.es_helper.remove_http_or_https(pdomain).split("/")[0].replace("*.", "").replace("*", "")
            self.startFingerprintFileScan(program=pdomain_name)
            i = i + 1

        # 4:write fingerprint
        i= 1
        for pdomain in all_pdomain_list:
            logger.log('INFOR',"[Fingerprint] 开始写入指纹第" + str(i) + "/" + str(pdomain_len) + "-" + pdomain)
            pdomain_name = self.es_helper.remove_http_or_https(pdomain).split("/")[0].replace("*.", "").replace("*", "")
            try:
                self.write_fingerprint_file_list(program=pdomain_name)
            except Exception as error:
                logger.log('DEBUG', f'{error}')
            i = i + 1

    def finger_scan_by_pdomain(self, pdomain=None):
        logger.log('INFOR',"[Fingerprint] 开始写入 - " + pdomain)
        asset_list = self.read_url_list(pdomain=pdomain)
        if asset_list != None:
            # write pdomain file
            pdomain_name = self.es_helper.remove_http_or_https(pdomain).split("/")[0].replace("*.","").replace("*","")
            self.write_url_list(program=pdomain_name,asset_list=asset_list)

            # start scan fingerprint
            logger.log('INFOR',"[Fingerprint] 开始扫描 - " + pdomain)
            pdomain_name = self.es_helper.remove_http_or_https(pdomain).split("/")[0].replace("*.", "").replace("*", "")
            self.startFingerprintFileScan(program=pdomain_name)

            # write fingerprint
            logger.log('INFOR',"[Fingerprint] 开始写入指纹 - " + pdomain)
            pdomain_name = self.es_helper.remove_http_or_https(pdomain).split("/")[0].replace("*.", "").replace("*", "")
            self.write_fingerprint_file_list(program=pdomain_name)

if __name__ == "__main__":
    #fingerprint_scan = FingerprintScan()
    #fingerprint_scan.finger_scan_all()
    pass
    #fingerprint_scan.write_fingerprint_file_list(program="ponds.com")
    #fingerprint_scan.startFingerprintFileScan(program="program1")
    #fingerprint_scan.write_fingerprint_file_list(program="program1")
    #fingerprint_scan.update_finger(url="http://odr.thomsonreuters.com",plugin="{'Bootstrap': {'version': ['3.1.1', '3.2.0']}, 'Ruby-on-Rails': {}, 'X-Powered-By': {'string': ['Phusion Passenger 4.0.57']}}")


from tkinter import N

"""
0<=k<= (n:=len(a))
1<=i1<=....<=ik<=n => add 1 to these indices
permute a
can a be equal to b?
"""
class Solution():
    def solve(a,b):
        if len(a) != len(b) : return False

        x = [a[i]]


# -*- coding: utf-8 -*-
# @Time    : 2019/6/13 10:09
# @Author  : zhengjiani
# @Software: PyCharm
# @Blog    ：https://zhengjiani.github.io/
"""
题目描述：
给定一棵二叉树的其中一个节点，请找出中序遍历序列的下一个节点。
如果给定的节点是中序遍历序列的最后一个，则返回空节点;
二叉树一定不为空，且给定的节点一定不是空节点；
某结点有右孩子，则该结点在其中序遍历序列下的后继为其右子树最左下的那个结点
若某结点没有右孩子，且它是其父结点的左孩子，则其父结点为其后继
若它是其父结点的右孩子，则一直往上遍历，\
直到找到某结点是其父结点的左孩子或者其父结点为空（访问到了根结点）为止，该结点的父结点便是所求的后继
"""
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
        self.next = None

class Solution(object):
    def inorderSuccessor(self,p_val):
        p = TreeNode(p_val)
        # 该节点有右孩子，则后继为其右子树最左下的那个节点，沿着右孩子一直遍历
        if p is None:
            return
        if p.right:
            p = p.right
            while p.left:
                p = p.left
            return p

        else:
            # 返回父节点
            if p.next is None:
                return
            # 该节点是其父节点的左孩子
            elif p.next.left == p:
                return p.next
            else:
                # 该节点是其父节点的右孩子
                if p.next.next.left == p.next:
                    return p.next.next
                else:
                    return
if __name__ == '__main__':
    solve = Solution()
    inorder = [2, 1, 3, None, None, None, None]
    print(solve.inorderSuccessor(2))


import imp
import pymc3 as pm
imp.reload(pm)

import theano
import theano.tensor as T
import numpy as np
import pickle
import pandas as pd

def create_sel(param,data,coding='deviance'):

    # create broadcast selector for Bk to approate trials in trials X NN
    if coding=='deviance':
        sel=T.ones_like(T.as_tensor_variable(data['irew']))
        if 'rewpain' in param:
            sel*=data['rewpain']
        if 'stabvol' in param:
            sel*=data['stabvol']
        if 'goodbad' in param:
            if ('Bp' in param) or ('Bm' in param) or ('Binv' in param) or ('Rp' in param) or ('Bbase' in param) or ('Bpoverm' in param) or ('Amix' in param):
                sel*=data['goodbad_mag']
            elif 'lr' in param:
                sel*=data['goodbad']
    return(sel)

def create_hyper_prior_group(Nboth,Nrew,Npain,K,rew_slice,pain_slice,mean=0,std=10):

    # hyper priors for group means
    u = pm.Normal('u',mean,std,shape=(K,1))

    # broadcast by person
    u_both_broad = T.transpose(u*T.ones(Nboth)) # Nboth x K
    u_rew_only_broad = T.transpose(u[rew_slice]*T.ones(Nrew)) # Nrew x K
    u_pain_only_broad = T.transpose(u[pain_slice]*T.ones(Npain)) # Npain x K

    # make combined mean (so we can add covariates)
    u_both_total = u_both_broad
    u_rew_only_total = u_rew_only_broad
    u_pain_only_total = u_pain_only_broad
    return(u_both_total,u_rew_only_total,u_pain_only_total)

def add_covariate_to_hyper_prior(u_both_total,
                            u_rew_only_total,
                            u_pain_only_total,rew_slice,pain_slice,K,
                            covariate,C,mean=0,std=1,
                            u_covariate_mask=None,
                            includes_subjs_with_one_task=True):

    ## SINGLE COVARIATE MODELS ##
    stems_single = {"Bi1itemCDM":'Bi1item_w_j_scaled',
             'PSWQresidG': 'PSWQ_scaled_residG',
             'PSWQ': 'PSWQ_scaled',
             'MASQADresidG': 'MASQAD_scaled_residG',
             'MASQAD': 'MASQAD_scaled',
             'MASQAAresidG': 'MASQAA_scaled_residG',
             'MASQAA': 'MASQAA_scaled',
             'STAIanxresidG': 'STAIanx_scaled_residG',
             'STAIanx': 'STAIanx_scaled',
             'STAIdepresidG': 'STAIdep_scaled_residG',
             'STAIdep': 'STAIdep_scaled',
             'STAIresidG': 'STAI_scaled_residG',
             'STAI': 'STAI_scaled',
             }

    if covariate in stems_single.keys():
        stem = stems_single[covariate]

        u_PC1 = pm.Normal('u_PC1',mean,std,shape=(K,1))
        u_PC1 = u_PC1*u_covariate_mask

        # broadcast by person and
        u_both_PC1_broad = T.transpose(u_PC1*T.as_tensor_variable(C[stem+'_both']))
        if includes_subjs_with_one_task:
            u_rew_only_PC1_broad = T.transpose(u_PC1[rew_slice]*T.as_tensor_variable(C[stem+'_rew_only']))
            u_pain_only_PC1_broad = T.transpose(u_PC1[pain_slice]*T.as_tensor_variable(C[stem+'_pain_only']))

        # add to total prior mean
        u_both_total+=u_both_PC1_broad
        if includes_subjs_with_one_task:
            u_rew_only_total+=u_rew_only_PC1_broad
            u_pain_only_total+=u_pain_only_PC1_broad

    ## DOUBLE COVARIATE MODELS ##
    stems_double = {"Bi2itemCDM": ['Bi1item_w_j_scaled','Bi2item_w_j_scaled'],
             }

    if covariate in stems_double.keys():
        stem1 = stems_double[covariate][0]
        stem2 = stems_double[covariate][1]

        u_PC1 = pm.Normal('u_PC1',mean,std,shape=(K,1)) # general
        u_PC2 = pm.Normal('u_PC2',mean,std,shape=(K,1)) # anhedonia

        u_PC1 = u_PC1*u_covariate_mask
        u_PC2 = u_PC2*u_covariate_mask

        # broadcast by person and
        u_both_PC1_broad = T.transpose(u_PC1*T.as_tensor_variable(C[stem1+'_both']))
        if includes_subjs_with_one_task:
            u_rew_only_PC1_broad = T.transpose(u_PC1[rew_slice]*T.as_tensor_variable(C[stem1+'_rew_only']))
            u_pain_only_PC1_broad = T.transpose(u_PC1[pain_slice]*T.as_tensor_variable(C[stem1+'_pain_only']))

        u_both_PC2_broad = T.transpose(u_PC2*T.as_tensor_variable(C[stem2+'_both']))
        if includes_subjs_with_one_task:
            u_rew_only_PC2_broad = T.transpose(u_PC2[rew_slice]*T.as_tensor_variable(C[stem2+'_rew_only']))
            u_pain_only_PC2_broad = T.transpose(u_PC2[pain_slice]*T.as_tensor_variable(C[stem2+'_pain_only']))

        # add to total prior mean
        u_both_total+=u_both_PC1_broad
        if includes_subjs_with_one_task:
            u_rew_only_total+=u_rew_only_PC1_broad
            u_pain_only_total+=u_pain_only_PC1_broad

        u_both_total+=u_both_PC2_broad
        if includes_subjs_with_one_task:
            u_rew_only_total+=u_rew_only_PC2_broad
            u_pain_only_total+=u_pain_only_PC2_broad

    ## TRIPlE COVARIATE MODELS ##
    stems_triple = {"Bi3itemCDM": ['Bi1item_w_j_scaled','Bi2item_w_j_scaled','Bi3item_w_j_scaled'],
                    "Bi3itemCDMsubset": ['Bi1item_subset_scaled','Bi2item_subset_scaled','Bi3item_subset_scaled'],
                    "G_ADrG_PSWQrG": ['Bi1item_w_j_scaled','MASQAD_scaled_residG','PSWQ_scaled_residG'],
                    "G_ADrG_AArG": ['Bi1item_w_j_scaled','MASQAD_scaled_residG','MASQAA_scaled_residG'],
             }
    if covariate in stems_triple.keys():
        stem1 = stems_triple[covariate][0]
        stem2 = stems_triple[covariate][1]
        stem3 = stems_triple[covariate][2]

        # hyper priors for covariates
        u_PC1 = pm.Normal('u_PC1',mean,std,shape=(K,1))
        u_PC2 = pm.Normal('u_PC2',mean,std,shape=(K,1))
        u_PC3 = pm.Normal('u_PC3',mean,std,shape=(K,1))

        u_PC1 = u_PC1*u_covariate_mask
        u_PC2 = u_PC2*u_covariate_mask
        u_PC3 = u_PC3*u_covariate_mask

        # broadcast by person and
        u_both_PC1_broad = T.transpose(u_PC1*T.as_tensor_variable(C[stem1+'_both']))
        if includes_subjs_with_one_task:
            u_rew_only_PC1_broad = T.transpose(u_PC1[rew_slice]*T.as_tensor_variable(C[stem1+'_rew_only']))
            u_pain_only_PC1_broad = T.transpose(u_PC1[pain_slice]*T.as_tensor_variable(C[stem1+'_pain_only']))

        u_both_PC2_broad = T.transpose(u_PC2*T.as_tensor_variable(C[stem2+'_both']))
        if includes_subjs_with_one_task:
            u_rew_only_PC2_broad = T.transpose(u_PC2[rew_slice]*T.as_tensor_variable(C[stem2+'_rew_only']))
            u_pain_only_PC2_broad = T.transpose(u_PC2[pain_slice]*T.as_tensor_variable(C[stem2+'_pain_only']))

        u_both_PC3_broad = T.transpose(u_PC3*T.as_tensor_variable(C[stem3+'_both']))
        if includes_subjs_with_one_task:
            u_rew_only_PC3_broad = T.transpose(u_PC3[rew_slice]*T.as_tensor_variable(C[stem3+'_rew_only']))
            u_pain_only_PC3_broad = T.transpose(u_PC3[pain_slice]*T.as_tensor_variable(C[stem3+'_pain_only']))

        # add to total prior mean
        u_both_total+=u_both_PC1_broad
        if includes_subjs_with_one_task:
            u_rew_only_total+=u_rew_only_PC1_broad
            u_pain_only_total+=u_pain_only_PC1_broad

        u_both_total+=u_both_PC2_broad
        if includes_subjs_with_one_task:
            u_rew_only_total+=u_rew_only_PC2_broad
            u_pain_only_total+=u_pain_only_PC2_broad

        u_both_total+=u_both_PC3_broad
        if includes_subjs_with_one_task:
            u_rew_only_total+=u_rew_only_PC3_broad
            u_pain_only_total+=u_pain_only_PC3_broad

    return(u_both_total,u_rew_only_total,u_pain_only_total)

def create_model_base(X, # observed stuff
                Y, # choices
                C, # covariates 157x1
                K, # number of params
                Konetask, # last index of parameters that don't depend on reward pain
                rew_slice,
                pain_slice,
                params=None,
                split_by_reward=True,
                includes_subjs_with_one_task=True,
                covariate='no_covariates',
                hierarchical=True,
                covv='diag',
                coding='deviance',
                group_mean_hyper_prior_mean=0, # prior belief over group mean, can specify as T.as_tensor_variable(np.array([[0,0,0,1]]).T)
                group_mean_hyper_prior_std=10, # can specify as T.as_tensor_variable(np.array([[1,1,1,2]]).T)
                group_covariate_hyper_prior_mean=0,
                group_covariate_hyper_prior_std=1,
                theta_var_hyper_prior_std=2.5,
                theta_var_hyper_prior_dist='HalfCauchy',
                cov_ind_priors=None, # can specify for independent priors (non hierarchical) T.eye(K)*10
                u_both_total=None,  # same need pm.theanof.set_theano_conf({'compute_test_value': 'raise'})
                one_task_only=False,
                u_covariate_mask=None, # Kx1
               ):
    '''Creates a PyMC model with parameter vector Theta with
    parameters that are hierarcically distributed

    '''

    model = pm.Model()

    with model:

        model.args = {'K':K,
                    'Konetask':Konetask, # last index of parameters that don't depend on reward pain
                    'rew_slice':rew_slice, # parameter slice for rew
                    'pain_slice':pain_slice, # subject slice for pain
                    'split_by_reward':split_by_reward,
                    'covariate':covariate,
                    'hierarchical':hierarchical,
                    'covv':covv,
                    'coding':coding,
                    'params':params,
                    'group_mean_hyper_prior_mean':group_mean_hyper_prior_mean, # prior belief over group mean # be able to pass in a vector
                    'group_mean_hyper_prior_std':group_mean_hyper_prior_std,
                    'group_covariate_hyper_prior_mean':group_covariate_hyper_prior_mean,
                    'group_covariate_hyper_prior_std':group_covariate_hyper_prior_std,
                    'theta_var_hyper_prior_std':theta_var_hyper_prior_std,
                    'cov_ind_priors':cov_ind_priors,
                    'u_both_total':u_both_total,
                    'theta_var_hyper_prior_dist':theta_var_hyper_prior_dist
                    }

        NN = X['NN'] # should equal Nboth*2 + Nrewonly + Npainonly
        Nboth = X['Nboth']
        model.NN=NN
        model.Nboth=Nboth
        if includes_subjs_with_one_task:
            Nrewonly = X['Nrewonly']
            Npainonly = X['Npainonly']
            model.Nrewonly =Nrewonly
            model.Npainonly=Npainonly
        else:
            Nrewonly=0
            Npainonly=0

        if u_covariate_mask is None:
            u_covariate_mask=np.ones((len(params),1))

        if hierarchical:

            if covariate not in ['group4']:

                # Hyper Prior Means (w/ Prior distributions-belief about prior means)
                (u_both_total,
                    u_rew_only_total,
                    u_pain_only_total)=create_hyper_prior_group(Nboth,Nrewonly,Npainonly,
                        K,rew_slice,pain_slice,
                        mean=group_mean_hyper_prior_mean,
                        std=group_mean_hyper_prior_std)

                (u_both_total,u_rew_only_total,u_pain_only_total)=add_covariate_to_hyper_prior(u_both_total,
                                            u_rew_only_total,
                                            u_pain_only_total,rew_slice,pain_slice,K,
                                            covariate,C,
                                            mean=group_covariate_hyper_prior_mean,
                                            std=group_covariate_hyper_prior_std,
                                            u_covariate_mask=u_covariate_mask,
                                            includes_subjs_with_one_task=includes_subjs_with_one_task)
            else:
                (u_both_total,
                    u_rew_only_total,
                    u_pain_only_total)=create_hyper_prior_group4(C,Nboth,Nrewonly,Npainonly,
                        K,rew_slice,pain_slice,
                        mean=group_mean_hyper_prior_mean,
                        std=group_mean_hyper_prior_std)

            if covv=='diag':

                # Hyper Prior Variance
                if theta_var_hyper_prior_dist=='HalfCauchy':
                    sigma = pm.HalfCauchy('sigma',theta_var_hyper_prior_std,shape=(K,1))
                elif theta_var_hyper_prior_dist=='HalfNormal':
                    sigma = pm.HalfNormal('sigma',theta_var_hyper_prior_std,shape=(K,1))
                elif theta_var_hyper_prior_dist=='Fixed':
                    # for generating data from fixed number
                    sigma = pm.Deterministic('sigma',theta_var_hyper_prior_std)

                Sigma = T.eye(K)*(sigma)
                Sigma = pm.Deterministic('Sigma', Sigma)

            # Subject Parameters

            # Shape = N subjects with both X K parameters (usually 71 x K)
            Theta_both = pm.MvNormal('Theta_both',mu=u_both_total,shape=(Nboth,K),cov=Sigma)

            if includes_subjs_with_one_task:
                # Shape = N subjects with just reward K parameters (usually 9 x K)
                Theta_rew_only = pm.MvNormal('Theta_rew_only',mu=u_rew_only_total,shape=(Nrewonly,Konetask),cov=Sigma[rew_slice,rew_slice])

                # Shape = N subjects with just pain K parameters (usually 7 x K)
                Theta_pain_only = pm.MvNormal('Theta_pain_only',mu=u_pain_only_total,shape=(Npainonly,Konetask),cov=Sigma[pain_slice,pain_slice])

        else:
            if cov_ind_priors is None:
                cov_ind_priors = T.eye(K)*10 # Covariance Matrix Identity;
            #make the variance for parameters for non-hierarchical really large

            if u_both_total is None:
                u_both_total = T.zeros((Nboth,K)) # mean 0; shouldn't it be size K?

            Theta_both = pm.MvNormal('Theta_both',mu=u_both_total,shape=(Nboth,K),cov=cov_ind_priors)
            if includes_subjs_with_one_task:
                u_rew_only_total = T.zeros((Nrewonly,Konetask)) # recently changed this to Kone task from 1
                u_pain_only_total = T.zeros((Npainonly,Konetask))
                Theta_rew_only = pm.MvNormal('Theta_rew_only',mu=u_rew_only_total,shape=(Nrewonly,Konetask),cov=cov_ind_priors[rew_slice,rew_slice])
                Theta_pain_only = pm.MvNormal('Theta_pain_only',mu=u_pain_only_total,shape=(Npainonly,Konetask),cov=cov_ind_priors[pain_slice,pain_slice])

        if split_by_reward and includes_subjs_with_one_task:
            # add zeros for parameters for tasks that these subjects don't have
            # if not splitting the single parameter goes to which ever task the subject has
            if coding=='block':
                print('this may not work any more')
                Theta_rew_only = T.concatenate((Theta_rew_only,T.zeros_like(Theta_rew_only)),axis=1)
                Theta_pain_only = T.concatenate((T.zeros_like(Theta_pain_only),Theta_pain_only),axis=1)
            elif coding=='deviance':
                # the relevant regressors are up front for both pain task and reward task
                Theta_rew_only = T.concatenate((Theta_rew_only,T.zeros_like(Theta_rew_only)[:,0:K-Konetask]),axis=1)
                Theta_pain_only = T.concatenate((Theta_pain_only,T.zeros_like(Theta_pain_only)[:,0:K-Konetask]),axis=1)

        # Stack all together and broadcast to Subject_task instead of subjects
        # Subjects with both tasks have two copies of Theta
        # N subject_task (157) x K
        if one_task_only:
            Theta = Theta_both
        else:
            if includes_subjs_with_one_task:
                Theta = T.concatenate((Theta_both,Theta_both,Theta_rew_only,Theta_pain_only),axis=0)
            else:
                # for rew then pain
                Theta = T.concatenate((Theta_both,Theta_both),axis=0)

        Theta = pm.Deterministic('Theta',Theta)

    return(model)


from collections import deque

di = [1, -1, 0, 0]
dj = [0, 0, 1, -1]

t_dir = {1: [0, 1, 2, 3], 2: [0, 1], 3: [2, 3],
         4: [1, 2], 5: [0, 2], 6: [0, 3], 7: [1, 3]
         }

# 하 상 우 좌

def my_bfs(si, sj):
    visited = [[0] * M for _ in range(N)]
    visited[si][sj] = 1
    deq = deque()
    deq.append((si, sj))

    while deq:
        i, j = deq.popleft()
        for d in t_dir[tunnel_info[i][j]]:
            ni, nj = i + di[d], j + dj[d]
            if 0 <= ni < N and 0 <= nj < M and tunnel_info[ni][nj] and not visited[ni][nj]:
                if d == 0:  # 하를 탐색할때는 상이 있으면 연결됨
                    if 1 in t_dir[tunnel_info[ni][nj]]:
                        visited[ni][nj] = visited[i][j] + 1
                        deq.append((ni, nj))
                elif d == 1:  # 상을 탐색할때는 하가 있으면 연결됨
                    if 0 in t_dir[tunnel_info[ni][nj]]:
                        visited[ni][nj] = visited[i][j] + 1
                        deq.append((ni, nj))
                elif d == 2:  # 우를 탐색할때는 좌가 있으면 연결됨
                    if 3 in t_dir[tunnel_info[ni][nj]]:
                        visited[ni][nj] = visited[i][j] + 1
                        deq.append((ni, nj))
                else:  # 좌을 탐색할때는 우가 있으면 연결됨
                    if 2 in t_dir[tunnel_info[ni][nj]]:
                        visited[ni][nj] = visited[i][j] + 1
                        deq.append((ni, nj))

    cnt = 0
    for i in range(N):
        for j in range(M):
            if 0 < visited[i][j] < L + 1:
                cnt += 1
    return cnt

T = int(input())

for tc in range(1, T + 1):
    N, M, R, C, L = map(int, input().split())
    # 지하 터널 지도의 세로 크기 N, 가로 크기 M
    # 맨홀 뚜껑의 세로 위치 R 가로 위치 C
    # 탈출 후 소요된 시간 L
    tunnel_info = [list(map(int, input().split())) for _ in range(N)]

    print(f'#{tc} {my_bfs(R, C)}')

SWEA_모의SW역량테스트_탈주범검거.py


import os

from src.dao.dao import Dao, DirectoryException

class FileDao(Dao):
    directory_exception = DirectoryException

    def __init__(self, directory_path=None):
        Dao.__init__(self)
        self.dao_type = 'file'
        self.path = directory_path

    def set_directory(self, path):
        self.path = path
        return self

    def read(self, name):
        if self.path is None: raise self.directory_exception
        try:
            with open(os.path.join(self.path, name), 'r') as f:
                return ''.join(f.readlines())
        except Exception as e:
            raise Exception("couldn't read file {} because of {}".format(name, e.message))

    def write(self, name, content):
        if self.path is None: raise self.directory_exception
        try:
            self.mkdir_recursive(self.path)
            with open(os.path.join(self.path, name), 'wb') as f:
                f.write(content)
        except Exception as e:
            raise Exception("couldn't read file {} because of {}".format(name, e.message))

    @staticmethod
    def split_path(path_to_split):
        path, folder = os.path.split(path_to_split)
        folders = [folder]
        while 1:
            path, folder = os.path.split(path)

            if folder != "":
                folders.append(folder)
            else:
                if path != "":
                    folders.append(path)

                break

        folders.reverse()
        return folders

    @staticmethod
    def mkdir_recursive(path):
        split = FileDao.split_path(path)
        for i, folder in enumerate(split):
            current = os.path.join(*split[:i + 1])
            if not os.path.exists(current):
                os.mkdir(current)
        return True


import sys
import json
from eVotUM.Cripto import eccblind

initComponents, pRDashComponents = eccblind.initSigner()

def printUsage():
    print("Usage:")
    print("   'python init-app.py' - Para obter pRDashComponents")
    print("   'python init-app.py -init' - Para obter pRDashComponents e initComponents")
    print("   (As componentes serao guardadas no ficheiro 'assinante.json')\n")

def parseArgs():
    if(len(sys.argv) == 1):
        initPrDash()
    elif(len(sys.argv) == 2 and sys.argv[1] == "-init"):
        initComps()
    else:
        printUsage()

def initPrDash():
    print("\npRDashComponents: %s\n" % pRDashComponents)
    saveComponents()

def initComps():
    print("\nInit components: %s \n" % initComponents)
    print("\npRDashComponents: %s\n" % pRDashComponents)
    saveComponents()

def saveComponents():
    with open("assinante.json","r") as f:
        assinante = json.loads(f.read())
    assinante["initComponents"] = initComponents
    assinante["pRDashComponents"] = pRDashComponents

    with open("assinante.json","w") as f:
        f.write(json.dumps(assinante))

if __name__ == "__main__":
    #main()
    parseArgs()


from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import Profile, Friend, Collab
from django.http import JsonResponse
import json
from .encoder import Show_profileEncoder
from django.views.decorators.http import require_http_methods

# Create your views here.
# @login_required
@require_http_methods(["GET", "DELETE", "PUT"])
def show_profile(request):
    if request.method == "GET":
        profile = Profile.objects.get(name="gabby")
        return JsonResponse(
            {
                "profile": profile,
                "paper": profile.paper.import_href.__str__(),
                "picture": profile.picture,
            },
            encoder=Show_profileEncoder,
            safe=False,
        )
    elif request.method == "DELETE":
        count, _ = Profile.objects.filter(name=request.user).delete()
        return JsonResponse({"deleted": count > 0})
    else:
        content = json.loads(request.body)
        Profile.objects.filter(id=id).update(**content)
        posts = Profile.objects.get(id=id)

        return JsonResponse(
            posts,
            encoder=Show_profileEncoder,
            safe=False,
        )

        # profile= Profile.objects.get(name=request.user)
        # friends= Friend.objects.all()
        # collabs=Collab.objects.all()
        # context = {
        #     "profile": profile,
        #     "friends": friends,
        #     "collabs":collabs,
        # }
        # return render(request,"pages/profile.html", context)

# def show_friends(request):
#     if request.method == "GET":
#         friends= Friend.objects.all()
#         context = {
#             "friends": friends,
#         }
#         return render(request,"pages/profile.html", context)


# -*- coding:utf-8 -*-
# Author: MoncozGC
# Date  : 2023/3/22 15:19
# Desc  : 数据匹配
"""
python, 使用我已经有一个clear_dataframe, 有一列字段dis有一条这样的数据 肺脏,脾脏,肾脏 , 这条数据的cid为98. 还有一个dic_dataframe, 里面有这样的数据: aid字段:10, poszn字段:肺脏; aid字段:21,poszn字段:脾脏; aid字段:25, poszn字段:肾脏. 请使用python的pands将数据处理为一个新的dataframe,结构如下: oid字段为:1, aid字段为:10, oid字段为:1, aid字段为21, oid字段为1,aid字段为25. 一一的将两个dataframe字段中的数据匹配出来
"""
if __name__ == '__main__':
    import pandas as pd

    # 假设这是你的 clear_dataframe
    clear_dataframe = pd.DataFrame({'cid': [98], 'dis': ['肺脏,脾脏,肾脏']})

    # 假设这是你的 dic_dataframe
    dic_dataframe = pd.DataFrame({'aid': [10, 21, 25], 'poszn': ['肺脏', '脾脏', '肾脏']})

    # 将 clear_dataframe 中的 'dis' 列拆分为多行
    clear_dataframe = clear_dataframe.assign(dis=clear_dataframe['dis'].str.split(',')).explode('dis')

    # 将 'dis' 列重命名为 'poszn'，以便与 dic_dataframe 进行合并
    clear_dataframe = clear_dataframe.rename(columns={'dis': 'poszn'})

    # 将 clear_dataframe 与 dic_dataframe 合并，并将 'cid' 列重命名为 'oid'
    result_dataframe = clear_dataframe.merge(dic_dataframe, on='poszn').rename(columns={'cid': 'oid'})

    # 选择 'oid' 和 'aid' 列作为最终结果
    result_dataframe = result_dataframe[['oid', 'aid']]

    print(result_dataframe)


class Solution:
    # @param A : list of integers
    # @param B : integer
    # @return an integer
    def solve(self, A, B):
        myDict = {}
        count = 0
        d = (10**9) + 7
        n = len(A)
        for i in range(n):
            b = B-A[i]
            if b in myDict:
                count += myDict[b]
            if A[i] in myDict:
                myDict[A[i]] += 1
            else:
                myDict[A[i]] = 1
        return count % d

Intermediate/16 Intermediate DSA : Hashing - 2 /Homework/Q1. Count Pair Sum/Count Pair Sum.py


from PySide6.QtCore import QObject, Slot, Signal
from PySide6.QtQml import QQmlFile, QmlElement, QQmlComponent
from pathlib import Path

QML_IMPORT_NAME = "io.qt.textproperties"
QML_IMPORT_MAJOR_VERSION = 1

@QmlElement
class MainView(QObject):

    path: Path = Path(__file__).parent.parent.parent / "qml" / "Splash.qml"

    @Slot(str, result=str)
    def getColor(self, s):
        if s.lower() == "red":
            return "#ef9a9a"
        elif s.lower() == "green":
            return "#a5d6a7"
        elif s.lower() == "blue":
            return "#90caf9"
        else:
            return "white"

    @Slot(float, result=int)
    def getSize(self, s):
        size = int(s * 34)
        if size <= 0:
            return 1
        else:
            return size

    @Slot(str, result=bool)
    def getItalic(self, s):
        return s.lower() == "italic"

    @Slot(str, result=bool)
    def getBold(self, s):
        return s.lower() == "bold"

    @Slot(result=str)
    def currentWorkspace(self) -> str:
        return "default"


import numpy as np

class Linear:

    def forward(self, x, w, b):

        out = x @ w + b
        cache = (x, w, b)

        return out, cache

    def backward(self, grad, cache):
        x, w, b = cache

        dw = x.T @ grad
        db = grad.sum(axis=0)
        dx = grad @ w.T

        return dx, dw, db

class ReLU:

    def forward(self, x):
        out = np.clip(x, 0, None)
        cache = x
        return out, cache

    def backward(self, grad, cache):
        x = cache
        dx = (x > 0) * grad

        return dx

class LinearReLU:
    def __init__(self):
        self.linear = Linear()
        self.relu = ReLU()

    def forward(self, x, w, b):

        a, l1_cache = self.linear.forward(x, w, b)
        out, relu_cache = self.relu.forward(a)

        cache = (l1_cache, relu_cache)

        return out, cache

    def backward(self, grad, cache):

        l1_cache, relu_cache = cache

        dx = self.relu.backward(grad, relu_cache)
        dx, dw, db = self.linear.backward(dx, l1_cache)

        return dx, dw, db

def softmax_loss(y, y_pred):

    n_sample = len(y)

    shifted = y_pred - y_pred.max(axis=1, keepdims=True)
    Z = np.exp(shifted).sum(axis=1, keepdims=True)

    log_prob = shifted - np.log(Z)
    prob = np.exp(log_prob)
    loss = -log_prob[np.arange(n_sample), y].sum() / n_sample

    dx = prob.copy()
    dx[np.arange(n_sample), y] -= 1

    dx /= n_sample

    return loss, dx

class TwoLayerNet:

    def __init__(self, in_dim, hidden_dim, n_classes, lr, reg):

        self.lr = lr
        self.reg = reg
        self.params = {}

        self.params['w1'] = np.random.randn(in_dim, hidden_dim) / np.sqrt(2. / in_dim)
        self.params['w2'] = np.random.randn(hidden_dim, n_classes) / np.sqrt(2. / hidden_dim)
        self.params['b1'] = np.zeros(hidden_dim)
        self.params['b2'] = np.zeros(n_classes)

    def loss(self, X, y=None):

        score, grads = 0, {}

        l1 = LinearReLU()
        l2 = Linear()

        l1_out, l1_cache = l1.forward(X, self.params['w1'], self.params['b1'])
        score, l2_cache = l2.forward(l1_out, self.params['w2'], self.params['b2'])

        if y is None:
            return score

        loss, dx = softmax_loss(y, score)
        loss += self.reg * ((self.params['w2'] * self.params['w2']).sum() + (self.params['w1'] * self.params['w1']).sum())

        dx, dw2, db2 = l2.backward(dx, l2_cache)
        dx, dw1, db1 = l1.backward(dx, l1_cache)

        grads['w1'] = dw1 + 2 * self.reg * self.params['w1']
        grads['w2'] = dw2 + 2 * self.reg * self.params['w2']
        grads['b1'] = db1
        grads['b2'] = db2

        return loss, grads


from typing import Dict

from storage import Drive_Path
from reid_blocks import AREAS_REMAP

def ids_old_to_new(session) -> Dict[int, int]:
    remap = {}
    next_ids = {}
    for orig_id, new_id in AREAS_REMAP.items():
        next_ids[(orig_id, 1)] = new_id
        next_ids[(orig_id, 2)] = new_id + 500

    paths = session.query(Drive_Path).order_by(Drive_Path.start_id, Drive_Path.id).all()

    for path in paths:
        remap[path.id] = next_ids[(path.control_area, path.typ)]
        next_ids[(path.control_area, path.typ)] += 1

    return remap


import sys
# import importlib
# importlib.reload(sys)
# sys.setdefaultencoding('utf-8')
import time
time1 = time.time()
from PIL import Image
import pytesseract#ocr字符识别库
import cv2
#二值化算法
def binarizing(img,threshold):
    pixdata = img.load()
    w, h = img.size
    for y in range(h):
        for x in range(w):
            if pixdata[x, y] < threshold:
                pixdata[x, y] = 0
            else:
                pixdata[x, y] = 255
    return img

#去除干扰线算法
def depoint(img):   #input: gray image
    pixdata = img.load()
    w,h = img.size
    for y in range(1,h-1):
        for x in range(1,w-1):
            count = 0
            if pixdata[x,y-1] > 245:
                count = count + 1
            if pixdata[x,y+1] > 245:
                count = count + 1
            if pixdata[x-1,y] > 245:
                count = count + 1
            if pixdata[x+1,y] > 245:
                count = count + 1
            if count > 2:
                pixdata[x,y] = 255
    return img
#身份证号码识别
def identity_OCR(pic_path):
    #身份证号码截图
    img1=Image.open(pic_path)
    w,h=img1.size
    #将身份证放大3倍
    out=img1.resize((w*3,h*3),Image.ANTIALIAS)
    Image._show(out)
    cv2.waitKey(0)
    region = (125*3,200*3,370*3,250*3)
    #裁切身份证号码图片
    cropImg = out.crop(region)
    # print(cropImg)
    # Image._show(cropImg)
    # cv2.waitKey(0)
    # 转化为灰度图
    img= cropImg.convert('L')
    Image._show(img)
    cv2.waitKey(0)
    # 把图片变成二值图像。
    img1=binarizing(img,100)
    img2=depoint(img)
    code = pytesseract.image_to_string(img2)
    print("识别该身份证号码是:"+str(code))

#身份证号码识别
#英文图片识别
def identity_OCR_Nopro(pic_path):
    image = Image.open(pic_path)
    content = pytesseract.image_to_string(image)  # 解析图片
    print(content)
#中文图片识别
#要在pytesseract 库的 image_to_string() 方法里加个参数lang='chi_sim'，
#这个就是引用对应的中文语言包，中文语言包的全名是 chi_sim.traineddata

def identity_OCR_Chine(pic_path):
    from PIL import Image
    import pytesseract
    image = Image.open(pic_path)
    content = pytesseract.image_to_string(image, lang='chi_sim')  # 解析图片
    print(content)

#功能：video recognition
def identity_OCR_Video(pic_path):
    vid = cv2.VideoCapture(pic_path)
    while (1):
        try:
            return_value, frame = vid.read()
            if return_value:
                cv2.imshow("result", frame)
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                code = pytesseract.image_to_string(frame,lang='chi_sim')
                print("识别该身份证号码是:" + str(code))
                cv2.waitKey(100)
            else:
                raise ValueError("No image!")
        except:
            print('异常')
        # time.sleep(2)
if __name__ == '__main__':
    pic_path="./zsx2.jpg"
    # identity_OCR(pic_path)  ##使用图片2 识别证件号
    identity_OCR_Video(0)  #调用摄像头
    # identity_OCR_Chine(pic_path) #中文识别
    # identity_OCR_Nopro(pic_path) #英文识别
    time2 = time.time()
    print(u'总共耗时：' + str(time2 - time1) + 's')


from ursina import *

app = Ursina()
window.color = color.violet
# objects
table = Entity(model='cube', color=color.black, scale=(2, 1, 3), rotation=(90, 0, 0))
ball = Entity(model='sphere', color=color.orange, z=-1, scale=0.1, collider='sphere')
player1 = Entity(model='cube', color=color.cyan, scale=(0.6, 0.1, 1), position=(0, -1.4, -1), collider='box')
player2 = duplicate(player1, y=1.4, color=color.pink)
# variables
speed_x = speed_y = 0.2

# fonctions
def update():
    global speed_x, speed_y
    ball.x += speed_x * time.dt
    ball.y += speed_y * time.dt
    if abs(ball.x) > 0.9:
        speed_x = -speed_x
    if abs(ball.y) > 1.4:
        ball.x = ball.y = 0
        speed_x = speed_y = 0.2

    # collision player1 et table
    if player1.x - player1.scale_x / 2 < table.x - table.scale_x / 2:
        player1.x = table.x - table.scale_x / 2 + player1.scale_x / 2
    elif player1.x + player1.scale_x / 2 > table.x + table.scale_x / 2:
        player1.x = table.x + table.scale_x / 2 - player1.scale_x / 2
    # collision player2 et table
    if player2.x - player2.scale_x / 2 < table.x - table.scale_x / 2:
        player2.x = table.x - table.scale_x / 2 + player2.scale_x / 2
    elif player2.x + player2.scale_x / 2 > table.x + table.scale_x / 2:
        player2.x = table.x + table.scale_x / 2 - player2.scale_x / 2
    player1.x += held_keys['d'] * time.dt
    player1.x -= held_keys['a'] * time.dt
    player2.x += held_keys['right arrow'] * time.dt
    player2.x -= held_keys['left arrow'] * time.dt
    if ball.intersects().hit:
        speed_y = -speed_y
        speed_x *= 1.1
        speed_y *= 1.1

camera.orthographic = True
camera.fov = 4

app.run()


ages = [40, 25, 34, 48, 18]

counter = 0
total = 0

while counter < len(ages):
    total += ages[counter]  #total = total + ages[counter]

    counter += 1

print(total)

average = total / len(ages)

print(average)

# Homework
# find out the highest value in the array and print it
# find out the lowest value in the array and print it

highest = ages[0]
lowest = ages[0]

counter = 0
while counter < len(ages):

    if ages[counter] > highest:
        highest = ages[counter]

    if ages[counter] < lowest:
        lowest = ages[counter]

    counter += 1

print("H: " + str(highest))
print("L: " + str(lowest))


import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
import gym
from torch.autograd import Variable
import random
from collections import namedtuple

from tensorboardX import SummaryWriter

class DQN(nn.Module):
    def __init__(self, dueling=True):
        super().__init__()
        self.dueling = dueling
        self.fc1 = nn.Linear(2, 512)
        self.fc2 = nn.Linear(512, 512)
        self.fc3 = nn.Linear(512, 2)
        if dueling:
            self.v = nn.Linear(512, 1)

    def forward(self, x):
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        if self.dueling:
            v = self.v(x)
            a = self.fc3(x)
            q = v + a
        else:
            q = self.fc3(x)
        return q

def soft_update(target, source, tau):
    for target_param, param in zip(target.parameters(), source.parameters()):
        target_param.data.copy_(target_param.data * (1.0 - tau) + param.data * tau)

def hard_update(target, source):
    for target_param, param in zip(target.parameters(), source.parameters()):
        target_param.data.copy_(param.data)

class Agent(object):
    def __init__(self, gamma=0.8, batch_size=128):
        self.target_Q = DQN()
        self.Q = DQN()
        self.gamma = gamma
        self.batch_size = 128
        hard_update(self.target_Q, self.Q)
        self.optimizer = torch.optim.Adam(self.Q.parameters(), lr=0.00001)

    def act(self, x, epsilon=0.1):
        p = random.uniform(0, 1)

        # Return random action with probability epsilon
        if p < epsilon :
            action = random.randint(0, 1)
            return action

        Q_sa = self.Q(x.data)
        argmax = Q_sa.data.numpy().argmax()
        return argmax

    def backward(self, transitions):
        batch = Transition(*zip(*transitions))

        state = Variable(torch.cat(batch.state))
        action = Variable(torch.from_numpy(np.array(batch.action)))
        next_state = Variable(torch.cat(batch.next_state))
        reward = Variable(torch.cat(batch.reward))
        done = Variable(torch.from_numpy(np.array(batch.done)))

        Q_sa = self.Q(next_state).detach()
        target = self.target_Q(next_state).detach()
        _, argmax = Q_sa.max(dim=1, keepdim=True)
        target = target.gather(1, argmax)

        currentQvalues = self.Q(state).gather(1,action.unsqueeze(1)).squeeze()
        y = (reward.unsqueeze(1) + self.gamma * (target * (1-done.unsqueeze(1)))).squeeze()

        loss = F.smooth_l1_loss(currentQvalues,y)
        self.Loss = loss
        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()

        soft_update(self.target_Q, self.Q, 0.995)

Transition = namedtuple('Transition',
                        ('state', 'action', 'next_state', 'reward', 'done'))

class ReplayMemory(object):

    def __init__(self, capacity):
        self.capacity = capacity
        self.memory = []
        self.position = 0

    def push(self, *args):
        """Saves a transition."""
        if len(self.memory) < self.capacity:
            self.memory.append(None)
        self.memory[self.position] = Transition(*args)
        self.position = (self.position + 1) % self.capacity

    def sample(self, batch_size):
        return random.sample(self.memory, batch_size)

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

# Writer to log data to tensorboard
writer = SummaryWriter('runs')

nb_epoch = 2000
env = gym.make('MountainCar-v0')

epsilon = 1
agent = Agent()
memory = ReplayMemory(100000)
batch_size = 128

for i in range(nb_epoch):
    obs = env.reset()
    done = False
    total_reward = 0
    epsilon *= 0.99
    action_histo = np.zeros(2)
    while not done:
        if i > nb_epoch-50:
            env.render()
        epsilon = max(epsilon, 0.1)

        obs_input = Variable(torch.from_numpy(obs).type(torch.FloatTensor))
        action = agent.act(obs_input, epsilon)

        next_obs, reward, done, _ = env.step(action)
        memory.push(obs_input.data.view(1,-1), action,
                    torch.from_numpy(next_obs).type(torch.FloatTensor).view(1,-1), torch.Tensor([reward]),
                   torch.Tensor([done]))

        action_histo[action] += 1
        obs = next_obs
        total_reward += reward

        if reward == 1:
            print("WON AT EPISODE : ", i)
    writer.add_scalar('data/epsilon', epsilon, i)
    writer.add_scalar('data/total_reward', total_reward, i)
    writer.add_scalar('data/memory', memory.__len__(), i)
    writer.add_scalars('data/actions', {'0':action_histo[0], '1':action_histo[1]}, i)
    print("Episode : ", i)
    if memory.__len__() > 10000:
        batch = memory.sample(batch_size)
        agent.backward(batch)
        writer.add_scalar('data/loss', agent.Loss, i)


#!/usr/bin/env python

"""Algoritmo de line sweep"""

from geocomp.common.segment import Segment
from geocomp.common.point import Point
from geocomp.common import control
from geocomp.common.guiprim import *
from geocomp.config import *
from geocomp.closest.treap import *
from geocomp.closest.square import *
import math
import time

T = Treap()

def Sweep (l):
	"Algoritmo que usa line sweep para encontrar o par de pontos mais proximo"
	if len (l) < 2: return None

	T.clear()

	l.sort(key=lambda o: o.x)

	closest = float("inf")
	a = b = None
	id = None
	dt = {}
	ult = 0

	for i in range (len(l)):
		control.freeze_update ()
		hid = l[i].hilight('red')
		vid = control.plot_vert_line(l[i].x)
		oid = None
		if(closest != float("inf")):
			oid = control.plot_vert_line(l[i].x - math.sqrt(closest), COLOR_ALT1)

		# Remocao em O(lgn)
		while(ult < i and math.sqrt(closest) <= l[i].x - l[ult].x):
			T.erasePoint(l[ult])
			l[ult].unhilight(dt[l[ult]])
			ult += 1

		control.thaw_update ()
		control.update ()

		# Checando se atualiza a distancia minima entre pontos em O(lgn)
		## Cria box
		box_id = lx = None
		rz = 0
		if(closest != float("inf")):
			rz = math.sqrt(closest)
			lx = l[i].x - rz
		box_id = plot_square(lx, l[i].y - rz, l[i].x, l[i].y+rz)
		control.sleep()

		mn = Point(l[i].x, l[i].y - math.sqrt(closest))
		o = T.findPoint(mn);

		while(o != None and abs(o.y-l[i].y) <= math.sqrt(closest)):
			dist = dist2 (l[i], o)
			if dist < closest:
				control.freeze_update ()
				if a != None: a.unhilight (hia)
				if b != None: b.unhilight (hib)
				if id != None: control.plot_delete (id)

				closest = dist
				a = l[i]
				b = o

				rz = math.sqrt(closest)
				if(lx == None):
					lx = l[i].x - rz
				erase_square(box_id)
				box_id = plot_square(lx, l[i].y - rz, l[i].x, l[i].y + rz)

				hia = a.hilight ()
				hib = b.hilight ()
				id = a.lineto (b)

				if(oid == None):
					oid = control.plot_vert_line(l[i].x - math.sqrt(closest), COLOR_ALT1)
				control.sleep()

			o = T.findUpperPoint(o)

		## Remove box
		erase_square(box_id)

		# Insere o ponto na Treap - O(lgn)
		T.insertPoint(l[i])
		l[i].unhilight(hid)
		hi = l[i].hilight(COLOR_ALT1)
		dt[l[i]] = hi

		control.plot_delete (vid)
		if(oid != None):
			control.plot_delete(oid)

		control.thaw_update()
		control.update()

	control.thaw_update()
	control.update()
	for p in l:
		if(p in dt):
			p.unhilight(dt[p])

	a.hilight('green')
	b.hilight('green')
	ret = Segment (a, b)
	ret.extra_info = 'distancia: %.2f'%math.sqrt (dist2 (a, b))
	return ret


from django.urls import path
from . import views

app_name = 'challenge'
urlpatterns = [
    path('', views.index, name='index'),
    path('request/', views.challenge_request, name='challenge_request'),
    path('list/', views.challenge_list, name='challenge_list'),
    path('fight/<int:challenge_id>/', views.fight, name='fight'),
    path('decline/<int:challenge_id>/', views.decline_challenge, name='decline')
]


from django.shortcuts import render, HttpResponse, redirect
from miapp.models import Producto
from miapp.models import Curso

# Create your views here.
def index(request):
    return render(request,'inicio.html', {
        'titulo':'Inicio',
        'mensaje':'Mensaje Saludo',
    })
def integrantes(request):
    estudiantes = 'Kevin Arturo Pinedo Romero'
    return render(request,'integrantes.html', {
        'titulo':'Integrantes',
        'estudiante': estudiantes,
    })
def crearcursos(request):
    return render(request, 'crearcursos.html', {
    })

def crearproductos(request):
    return render(request, 'crearproductos.html', {
    })
def crearproducto1(request):
    producto=Producto(
        codigo= "DL213",
        nombre= "Queso",
        precio_compra = "5 Soles",
        precio_venta = "70 Soles",
        fecha_compra = "2022-07-25",
        fecha_registro = "2022-08-02",
        estado = "B"
    )
    producto.save()
    return HttpResponse(f"Producto creado: {producto.codigo} - {producto.nombre} - {producto.precio_compra} - {producto.precio_venta} - {producto.fecha_compra} - {producto.fecha_registro} - {producto.estado}")
def crearcurso1(request):
    curso=Curso(
        codigo= "SD005",
        nombre = "Estadistica",
        horas= "4 Horas",
        creditos = "4",
        fecha_registro = "2021-02-02",
        estado = "A"
    )
    curso.save()
    return HttpResponse(f"Producto creado: {curso.codigo} - {curso.nombre} - {curso.horas} - {curso.creditos} - {curso.fecha_registro} - {curso.estado}")


import torch
import torch.nn as nn
import torch.nn.functional as F

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

class Loss(object):
    def __init__(self, vocab_size) -> None:
        super().__init__()
        self.loss_obj = nn.CrossEntropyLoss(reduction='none')
        self.vocab_size = vocab_size

    def loss_fn(self, y_pred, y_true):
        y_onehot = F.one_hot(y_true, num_classes=self.vocab_size).type(
            torch.float32).to(device)
        loss = self.loss_obj(y_pred, y_onehot)
        equal = torch.eq(y_true, torch.zeros_like(y_true, device=device))
        equal = torch.logical_not(equal)
        mask = equal.type(torch.float32)
        return torch.mean(loss*mask)

    def __call__(self, y_pred, y_true):
        loss = 0
        _, _, maxlen = y_pred.size()
        for i in range(maxlen):
            loss += self.loss_fn(y_pred[:, :, i], y_true[:, i])
        return loss/maxlen


import numpy as np

class QLearning(object):
    def __init__(self, state_dim, action_dim, cfg):
        self.action_dim = action_dim  # dimension of acgtion
        self.lr = cfg.lr  # learning rate
        self.gamma = cfg.gamma # 衰减系数
        self.epsilon = 0.1
        self.sample_count = 0
        self.Q_table = np.zeros((state_dim, action_dim))  # Q表格

    def predict(self,state):
        Q_list = self.Q_table[state, :]
        Q_max = np.max(Q_list)
        possible_actions = np.where(Q_list == Q_max)[0]
        action = np.random.choice(possible_actions)
        return action

    def choose_action(self, state):
        ####################### 智能体的决策函数，需要完成Q表格方法（需要完成）#######################
        self.sample_count += 1
        if np.random.uniform(0, 1) > self.epsilon:
            action=self.predict(state)
        else:
            action = np.random.choice(self.action_dim)
        return action

    def update(self, state, action, reward, next_state, done):
        ############################ Q表格的更新方法（需要完成）##################################
        Q_old = self.Q_table[state, action]
        if done:
            Q_n = reward
        else:
            Q_n = reward + self.gamma * np.max(self.Q_table[next_state, :])
        self.Q_table[state, action] += self.lr * (Q_n - Q_old)
        #pass

    def save(self, path):
        np.save(path + "Q_table.npy", self.Q_table)

    def load(self, path):
        self.Q_table = np.load(path + "Q_table.npy")


from helper import FeatureLines
import pdb

datapath = '/home/palma/Unive/RePAIR/Datasets/RePAIR_dataset/group_19/processed/RPf_00152.ply'
#Obj1 = FeatureLines("data/group19/RPf_00152.ply",voxel_size=0.7)
Obj1 = FeatureLines(datapath,voxel_size=0.7)

# calculates all penalty functions after creating the graph where N = 16 (nearest neighbor)
Obj1.init(16)

# set the parameters as specified in the paper
# alpha, gamma,crease_threshold, and border_threshold and pattern_length_threshold
# pattern_length_T is set by default to half sqrt of the number of nodes
Obj1.set_params(alpha=0.2,gamma=0.5,crease_threshold=1.7,border_threshold=2)

Obj1.show("crease")
pdb.set_trace()

data = Obj1.w_k
Obj1.show_heat(data)
pdb.set_trace()


from sympy import *

"""
This function refers to a more legible represetation using a tiposetter
x represents the math's variable X
expr represents an expression
"""
init_printing( use_latex='mathjax' )
x = Symbol('x')
expr = x**4 - 3*x**2

"""
expr_d represents the derivation of the expression
Eq is a function to make a equation equal to any value for resolving it
"""
expr_d = Derivative(expr, x, evaluate=True)
Eq(expr_d, 0)

"""
solve is use for resolving equations
"""
solve(Eq(expr_d, 0))


#! /usr/bin/env python3
#

import numpy as np
import matplotlib.pyplot as plt
import platform
import time
import sys
import os
import math
from mpl_toolkits.mplot3d import Axes3D
from sys import exit

sys.path.append(os.path.join("../"))
from base import plot2d, plotocc
from timestamp.timestamp import timestamp

from i4lib.i4vec_print import i4vec_print
from i4lib.i4mat_print import i4mat_print
from r8lib.r8vec_print import r8vec_print, r8vec_print_some
from r8lib.r8mat_print import r8mat_print, r8mat_print_some
from r8lib.r8mat_write import r8mat_write

obj = plot2d()

def chuckaluck_frequency_plot(counts):

    # *****************************************************************************80
    #
    # chuckaluck_frequency_plot_test tests chuckaluck_frequency_plot
    #
    #  Discussion:
    #
    #    This code makes a histogram of the frequency of 0, 1, 2 or 3 matches
    #    given a fixed choice for the user's spot.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    22 August 2019
    #
    #  Author:
    #
    #    John Burkardt
    #
    #  Input:
    #
    #    integer counts[4], the frequency with which 0, 1, 2 and 3 matches
    #    were encountered.
    #

    x = np.arange(4)

    obj.new_2Dfig(aspect="auto")
    filename = 'chuckaluck_frequency.png'
    obj.axs.bar(x, counts)
    obj.axs.set_title('Chuckaluck matches', fontsize=16)
    obj.axs.set_xlabel('<-- Number of matches -->', fontsize=16)
    obj.axs.set_ylabel('<-- Frequency -->', fontsize=16)
    obj.SavePng(filename)
    print('')
    print('  Graphics saved as "%s"' % (filename))

def chuckaluck_frequency_plot_test():

    # *****************************************************************************80
    #
    # chuckaluck_frequency_plot_test tests chuckaluck_frequency_plot
    #
    #  Discussion:
    #
    #    This code makes a histogram of the frequency of 0, 1, 2 or 3 matches
    #    given a fixed choice for the user's spot.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    22 August 2019
    #
    #  Author:
    #
    #    John Burkardt
    #

    spot = np.random.randint(1, 7)
    rounds = 10000

    #
    #  Throw all three dice, ROUNDS times.
    #
    #  (As a consequence of Python's MORONIC conventions, you get integers between
    #  1 and 6 by using a range of 1 to 7.)
    #
    throws = np.random.randint(1, 7, [rounds, 3])

    #
    #  Count the number of dice that match SPOT.
    #
    matches = (throws == spot)

    #
    #  Sum the number of dice that match SPOT on each round
    #
    scores = np.sum(matches, axis=1)

    #
    #  Count the number of times each score was achieved.
    #
    counts = np.zeros(4)
    for i in range(0, 4):
        counts[i] = np.count_nonzero(scores == i)

    #
    #  Make a bar plot of the frequency of each score.
    #
    chuckaluck_frequency_plot(counts)

def chuckaluck_game(spot):

    # *****************************************************************************80
    #
    # chuckaluck_game simulates one chuckaluck game.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    22 August 2019
    #
    #  Author:
    #
    #    John Burkardt
    #
    #  Input:
    #
    #    integer spot, the player's chosen number.
    #
    #  Output:
    #
    #    integer win, the payoff (-1, 1, 2 or 10 ).
    #

    dice = np.random.randint(1, 7, 3)
    win = chuckaluck_payoff(spot, dice)

    return win

def chuckaluck_games(spot, rounds):

    # *****************************************************************************80
    #
    # chuckaluck_games simulates many chuckaluck games.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    23 August 2019
    #
    #  Author:
    #
    #    John Burkardt
    #
    #  Input:
    #
    #    integer spot, the player's chosen number.
    #
    #    integer rounds, the number of games to play.
    #
    #  Output:
    #
    #    integer wins, the total payoff.
    #
    wins = 0
    for i in range(0, rounds):
        dice = np.random.randint(1, 7, 3)
        wins = wins + chuckaluck_payoff(spot, dice)

    return wins

def chuckaluck_history_plot(wins):

    # *****************************************************************************80
    #
    # chuckaluck_history_plot_test tests chuckaluck_history_plot
    #
    #  Discussion:
    #
    #    This code plots the player's total winnings at each stage of a sequence
    #    of chuckaluck games.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    22 August 2019
    #
    #  Author:
    #
    #    John Burkardt
    #
    #  Input:
    #
    #    integer wins[n], the total winnings at each stage of a sequence of
    #    chuckaluck games.
    #

    n = len(wins)
    games = np.arange(n)

    obj.new_2Dfig(aspect="auto")
    filename = 'chuckaluck_history.png'
    obj.axs.plot(games, wins, linewidth=3)
    obj.axs.plot([0, n], [0, 0], 'r-', linewidth=3)
    obj.axs.set_title('Chuckaluck winnings', fontsize=16)
    obj.axs.set_xlabel('<-- Number of games -->', fontsize=16)
    obj.axs.set_ylabel('<-- Winnings ($) -->', fontsize=16)
    obj.SavePng(filename)
    print('Graphics saved as "', filename, '".')

def chuckaluck_history_plot_test():

    # *****************************************************************************80
    #
    # chuckaluck_history_plot_test tests chuckaluck_history_plot
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    22 August 2019
    #
    #  Author:
    #
    #    John Burkardt
    #

    spot = np.random.randint(1, 7)
    rounds = 10000
    win_sum = np.zeros(rounds + 1)
    for i in range(0, rounds):
        dice = np.random.randint(1, 7, 3)
        win = chuckaluck_payoff(spot, dice)
        win_sum[i + 1] = win_sum[i] + win

    chuckaluck_history_plot(win_sum)

def chuckaluck_payoff(spot, dice):

    # *****************************************************************************80
    #
    # chuckaluck_payoff returns the payoff for a game of chuckaluck.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    22 August 2019
    #
    #  Author:
    #
    #    John Burkardt
    #
    #  Input:
    #
    #    integer spot, the user's choice, between 1 and 6.
    #
    #    integer dice[3], the values of the dice roll.
    #
    #  Output:
    #
    #    integer win, the payoff.
    #
    #

    match = np.count_nonzero(dice == spot)
    if (match == 0):
        win = -1
    elif (match == 1):
        win = +1
    elif (match == 2):
        win = +2
    elif (match == 3):
        win = +10

    return win

def chuckaluck_probability(rounds):

    # *****************************************************************************80
    #
    # chuckaluck_probability estimates chuckaluck probabilities.
    #
    #  Discussion:
    #
    #    This code plays a number of games and estimates the probability of
    #    0, 1, 2 or 3 matches.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    22 August 2019
    #
    #  Author:
    #
    #    John Burkardt
    #
    #  Input:
    #
    #    integer rounds, the number of rounds of the game.
    #
    #  Output:
    #
    #    real prob[4], the estimated probabilities of 0, 1, 2 or 3 matches.
    #

    #
    #  Arbitrarily choose SPOT.
    #
    spot = np.random.randint(1, 7)

    #
    #  Throw all three dice, ROUNDS times.
    #
    throws = np.random.randint(1, 7, [rounds, 3])

    #
    #  Count the number of dice that match SPOT.
    #
    matches = (throws == spot)

    #
    #  Sum the number of dice that match SPOT on each round
    #
    scores = np.sum(matches, axis=1)

    #
    #  Count the number of times each score was achieved.
    #
    counts = np.zeros(4)
    for i in range(0, 4):
        counts[i] = np.count_nonzero(scores == i)

    prob = counts / rounds

    return prob

def chuckaluck_probability_test():

    # *****************************************************************************80
    #
    # chuckaluck_probability_test tests chuckaluck_probability.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    22 August 2019
    #
    #  Author:
    #
    #    John Burkardt
    #

    print('')
    print('chuckaluck_probability_test:')
    print('  chuckaluck_probability estimates the probability of')
    print('  0, 1, 2, or 3 matches in chuckaluck, by simulating')
    print('  n games.')
    print('')
    print('        n        0        1        2        3')
    print('')

    n = 1
    for log10n in range(0, 7):
        prob = chuckaluck_probability(n)
        print('  %7d  %8.6f  %8.6f  %8.6f  %8.6f'
              % (n, prob[0], prob[1], prob[2], prob[3]))
        n = n * 10

    exact = np.array([5**3, 3 * 5**2, 3 * 5, 1]) / 6**3
    print('')
    print('  Exact:   %8.6f  %8.6f  %8.6f  %8.6f'
          % (exact[0], exact[1], exact[2], exact[3]))

def chuckaluck_simulation_test():

    # *****************************************************************************80
    #
    # chuckaluck_simulation_test tests chuckaluck_simulation.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    04 February 2019
    #
    #  Author:
    #
    #    John Burkardt
    #

    print('')
    print('chuckaluck_simulation_test:')
    print('  Python version: %s' % (platform.python_version()))
    print('  Test chuckaluck_simulation.')

    spot = 1
    rounds = 1000
    bet = 100
    triple = 10
    # chuckaluck_simulation ( spot, rounds, bet, triple )

    chuckaluck_frequency_plot_test()
    chuckaluck_history_plot_test()
    chuckaluck_probability_test()

    print('')
    print('chuckaluck_simulation_test:')
    print('  Normal end of execution.')
    print('')

if (__name__ == '__main__'):
    timestamp()
    chuckaluck_simulation_test()
    timestamp()


import pygame
import numpy as np
from numba import jit

pygame.init()

WIDTH, HEIGHT = 200, 200
size = 2
window = pygame.display.set_mode((WIDTH * size, HEIGHT * size))
clock = pygame.time.Clock()
fps = 144

f = 0.055
k = 0.062
dA = 1
dB = 0.5

grid = np.empty(shape=(WIDTH, HEIGHT, 2))
grid[0:][0:] = [1, 0]
grid[0][0] = [1, 0]

for y in range(HEIGHT // 2 - 10, HEIGHT // 2 + 11):
    for x in range(WIDTH // 2 - 10, WIDTH // 2 + 11):
        grid[y][x] = [0, 1]

@jit(nopython="True")
def update(grid):
    a = np.empty(shape=(WIDTH, HEIGHT, 2))
    for y in range(HEIGHT):
        for x in range(WIDTH):
            if y == 0 or x == 0 or y == HEIGHT - 1 or x == WIDTH - 1:
                a[y][x][0] = grid[y][x][0]
                a[y][x][1] = grid[y][x][1]
            else:
                a[y][x][0] = grid[y][x][0] + (
                            dA * laplace(x, y, 0, grid) - grid[y][x][0] * grid[y][x][1] ** 2 + f * (1 - grid[y][x][0]))
                a[y][x][1] = grid[y][x][1] + (
                            dB * laplace(x, y, 1, grid) + grid[y][x][0] * grid[y][x][1] ** 2 - (k + f) * grid[y][x][1])
    return a

@jit(nopython="True")
def laplace(x, y, p, grid):
    val = 0
    val += grid[y][x][p] * -1
    val += grid[y - 1][x][p] * 0.2
    val += grid[y + 1][x][p] * 0.2
    val += grid[y][x - 1][p] * 0.2
    val += grid[y][x + 1][p] * 0.2
    val += grid[y - 1][x - 1][p] * 0.05
    val += grid[y + 1][x + 1][p] * 0.05
    val += grid[y + 1][x - 1][p] * 0.05
    val += grid[y - 1][x + 1][p] * 0.05
    return val

def main():
    global grid
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        for y in range(HEIGHT):
            for x in range(WIDTH):
                # pygame.draw.rect(window, (int(max(0, min(grid[y][x][0] * 255, 255))), 0, int(max(0, min(grid[y][x][1] * 255, 255)))), (x * size, y * size, size, size))
                pygame.draw.rect(window, (grid[y][x][0] * 255, 0, grid[y][x][1] * 255),
                                 (x * size, y * size, size, size))
        grid = update(grid)

        pygame.display.update()
        # clock.tick(fps)

main()


import matplotlib.pyplot as plt
from main import *
import hotels_list

file = "chennai_reviews.xls"

def histogram(file, filter, filter_pos_neg, list_hotel):
    service = ["service", "waiter", "waitress", "employee", "lobby", "welcome", "reception", "staff", "porter",
               "security", "room-service", "internet", "wifi", "wi-fi"]
    location = ["place", "environment", "location", "area", "position", "region", "neighborhood"]
    rooms = ["rooms", "bathrooms", "toilet", "bed", "sleep", "decoration", "room service", "views", "quiet", "chic",
             "comfort", "noisy"]
    food = ["food", "restaurant", "tea", "drinks", "coffee", "dinner", "lunch", "breakfast", "cuisine", "tasty",
            "kitchen", "buffet", "delicious"]
    cleanliness = ["clean", "concierge", "laundry", "dirty", "cleanliness", "smelly", "cleaness", "smell", "grose",
                   "stinky"]
    price = ["price", "money", "pricing", "pricey", "expensive", "cheap", "cost", "discount"]
    entertainment = ["entertainment", "pool", "bar", "theater", "party", "spectacle", "sport"]

    list_y = []

    if filter == "service":
        list_y = get_all_reviews(file, list_hotel, service)
    elif filter == "location":
        list_y = get_all_reviews(file, list_hotel, location)
    elif filter == "rooms":
        list_y = get_all_reviews(file, list_hotel, rooms)
    elif filter == "food":
        list_y = get_all_reviews(file, list_hotel, food)
    elif filter == "price":
        list_y = get_all_reviews(file, list_hotel, price)
    elif filter == "cleanliness":
        list_y = get_all_reviews(file, list_hotel, cleanliness)
    elif filter == "entertainment":
        list_y = get_all_reviews(file, list_hotel, entertainment)
    elif filter == "all":
        list_y = get_all_reviews(file, list_hotel, [])

    # x = ["h1","h2","h3","h4","h5","h6","h7","h8","h9","h10"]
    # y = [50.4,46.3,10,20,5,50,46,80,20,5]

    x = list_hotel
    xpos = np.arange(len(x))

    y1 = list_y[0]

    y2 = list_y[1]

    # x = ['Aadithya', 'Abu sarovar portico ex Abu Palace', 'Accord Metropolitan', 'Akash Inn']
    # y = [100, 57, 94, 100]
    plt.close('all')
    if filter_pos_neg == "posneg":
        plt.bar(xpos , y1, width=0.2, label="positive", color="green")
        plt.bar(xpos + 0.2, y2, width=0.2, label="negative", color="red")
    if filter_pos_neg == "positive":
        plt.bar(x, y1, label="positive",color="green")
    if filter_pos_neg == "negative":
        plt.bar(x, y2, label="negative",color="red")

    axes = plt.gca()
    axes.set_ylim([0,100])

    plt.xticks(rotation=90)
    plt.xticks(xpos, x)
    plt.xlabel("hotels")
    plt.ylabel("review %")
    if filter_pos_neg == "positive":
        plt.title("positive " + filter + " reviews histogram")
    if filter_pos_neg == "negative":
        plt.title("negative " + filter + " reviews histogram")
    if filter_pos_neg == "posneg":
        plt.title("positive & negative " + filter + " reviews histogram")

    plt.legend()
    plt.tight_layout()
    plt.show()


#!/usr/bin/env python

import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import cv2
import os

class LoadImage(object):

	def __init__(self):

		self.image_sub = rospy.Subscriber("/camera/rgb/image_raw", Image, self.camera_callback)
		self.bridge_object = CvBridge()

	def camera_callback(self, data):
		try:
			cv_image = self.bridge_object.imgmsg_to_cv2(data, desired_encoding="bgr8")
		except CvBridgeError as e:
			print (e)

def main():
		load_image_object = LoadImage()
		rospy.init_node("load_image_node", anonymous=True)
		try:
			rospy.spin()
		except KeyboardInterrupt:
			print("shutting down")
		cv2.destroyAllWindows()

if __name__ == '__main__':
	main()


# jsonify lets us send JSON back!
from flask import Flask, render_template, request, redirect, jsonify
# Import MySQLConnector class from mysqlconnection.py
from mysqlconnection import MySQLConnector
app = Flask(__name__)

mysql = MySQLConnector(app, 'notes')

@app.route('/', methods=['GET'])
def index():
    query = "SELECT * FROM notes"
    notes = mysql.query_db("SELECT * FROM notes")
    return render_template('index.html', notes = notes)

@app.route('/notes/html', methods=['GET'])
def html_notes():
    query = "SELECT * FROM notes"
    notes = mysql.query_db("SELECT * FROM notes")
    return render_template('notes.html', notes = notes)

@app.route('/notes/create', methods=['POST'])
def create():
    query = "INSERT INTO notes (title, created_at, updated_at) VALUES (:title, NOW(), NOW())"
    data = {
        'title': request.form['title']
    }
    mysql.query_db(query, data)
    return redirect('/')

@app.route('/notes/<id>/delete')
def delete(id):
    query = "DELETE FROM notes WHERE id = :id"
    data = {
        'id': id
    }
    mysql.query_db(query, data)
    return redirect('/')

@app.route('/notes/<id>/update', methods=['POST'])
def update(id):
    query = "UPDATE notes SET description = :desc WHERE id = :id"
    data = {
        'id': id,
        'desc': request.form['description']
    }
    mysql.query_db(query, data)
    return redirect('/')

@app.route('/notes/index_json')
def index_json():
    notes = mysql.query_db("SELECT * FROM notes")

    return jsonify(notes = notes)

app.run(debug=True)


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

from requests import Session,Request, get as Get, post as Post
from requests.exceptions import  *
import requests
import time
import queue
import logging
from logger import get_logger
import threading

q = queue.Queue()
logger = get_logger(__name__)
api_url = "https://api.github.com/search/repositories"

def producer(url,  **kwargs):
    logger.info("produce one item")
    q.put((url, kwargs))

def consumer():
    logger.info("start consume")
    while True:
        url, params = q.get()
        send_req(url, params = params)

def send_req(url, params = None):
    def need_retry(resp):
        if(resp.status_code != requests.codes.ok):
            code = resp.status_code
            logger.warn(f"Warning response status_code = {code}, reason = {resp.reason}")
            return True

        remaining_count = int(resp.headers['X-RateLimit-Remaining'])
        logger.debug(f"X-RateLimit-Remaining  == {remaining_count}")
        if remaining_count == 0:
            return True

        return False

    def sleep_if_need(resp):
        remaining_count = int(resp.headers['X-RateLimit-Remaining'])
        if remaining_count == 0:
            logger.info("X-RateLimit-Remaining  == 0, sleeping")
            dead_line = int(resp.headers['X-RateLimit-Reset'])
            logger.debug(f"dead_line = {dead_line}")
            now_time = time.time()
            if(now_time > dead_line):
                sleep_during = 3
            else:
                sleep_during = dead_line - now_time + 3
            logger.info(f"sleep {sleep_during}s")
            time.sleep(sleep_during)

    session = Session()
    for i in range(3):
        try:
            logger.info("requesting")
            resp = session.get(url, params = params, timeout = 10)
        except RequestException as req_e:
            logger.warn(f"request_exception : {req_e}")
            continue
        except Exception as e:
            logger.warn(f"exception : {e}")
            continue

        logger.info("request completed")
        if need_retry(resp):
            sleep_if_need(resp)
            continue
        break # has been get result, so break loop
    else:
        logger.error("retry count  > 3")
        producer(url, **params)
        return None

    #get next_url and produce item
    next_url = resp.links.get("next", None)
    if next_url:
        producer(next_url['url'])
    else:
        logger.info("no next page")
    return resp

producer(api_url,q = "a", per_page = 1000)
producer(api_url,q = "b", per_page = 1000)
producer(api_url,q = "c", per_page = 1000)
producer(api_url,q = "d", per_page = 1000)

threads = []
for i in range(4):
    t = threading.Thread(target = consumer, daemon=True)
    threads.append(t)
    t.start()

try:
    time.sleep(100000)
except KeyboardInterrupt:
    exit()

logger = get_logger()
api_url = "https://api.github.com/search/repositories"

def send_req(url, params = None):
    def need_retry(resp):
        if(resp.status_code != requests.codes.ok):
            code = resp.status_code
            logger.warn(f"Warning response status_code = {code}, reason = {resp.reason}")
            return True

        remaining_count = int(resp.headers['X-RateLimit-Remaining'])
        if remaining_count == 0:
            return True

        return False

    def sleep_if_need(resp):
        remaining_count = int(resp.headers['X-RateLimit-Remaining'])
        if remaining_count == 0:
            logger.info("X-RateLimit-Remaining  == 0, sleeping")
            dead_line = int(resp.headers['X-RateLimit-Reset'])
            logger.debug(f"dead_line = {dead_line}")
            now_time = time.time()
            if(now_time > dead_line):
                sleep_during = 3
            else:
                sleep_during = dead_line - now_time + 3
            logger.info(f"sleep {sleep_during}s")
            time.sleep(sleep_during)

    session = Session()
    for i in range(3):
        try:
            logger.info("requesting")
            resp = session.get(url, params = params, timeout = 10)
        except RequestException as req_e:
            logger.warn(f"request_exception : {req_e}")
            continue
        except Exception as e:
            logger.warn(f"exception : {e}")
            continue

        if need_retry(resp):
            sleep_if_need(resp)
            continue
        logger.debug(f"X-RateLimit-Remaining  == {remaining_count}")
        return resp
    else:
        logger.error("error count  > 3")
        return None
    return resp

def get_respo_list(**kwargs)->list:
    resp = send_req(api_url, kwargs)
    #return resp
    for i in range(30):
        next_url = resp.links.get("next", None)
        if next_url:
            resp = send_req(next_url['url'])
        else:
            logger.info("no next page")
            break

if __name__ == "__main__":
    result = get_respo_list(q = "a", per_page = 1000)


from heapq import heappush, heappop
from read_and_drive import *
import sys
from math import sqrt
import time
from random import randint

gen_size = 100
error_tol = 10
converg_tol = 50
num_torn = int(math.sqrt(gen_size))

# main driver program
def evolution(gen_size, num_torn, district, tol):
    """
    :param data: the training data set, a list of input output touples
    :param gen_size: the size of each generation, could vary
    :param details: a touble specifying the type of selection (1 for tournament),
    and for tournament, the number of tournaments
    :param tol: the error below which we consider ourselves to have found the solution
    """''
    output = [] #tuple list of king fitness, diversity at each generation
    kings = []
    converged = False
    timesum = 0
    #print('making original generation')
    start = time.time()
    original = new_gen(gen_size, district) # create a population
    #print('finished making original generation')

    heappush(kings, original[1]) #put original[1], the king, onto the heap kings
    timesum += time.time()-start
    output.append((original[1].fitness, int(kings[0].fitness), diversity(original[0]), (time.time() - start) / 60.0, timesum))

    old_gen = original

    # simulate generations of natural selection
    converg_count = 0
    gen_count = 0
    while not converged:
        print ('#############################################################')
        print ('         Output:', sys.argv[1], sys.argv[2])
        print ('#############################################################')
        print ('King, Emperor, Diversity, Time, Total Time')
        for entry in output:
            print (int(entry[0]), int(entry[1]), entry[2], int(entry[3]), int(entry[4]))
        print ('')

        if kings[0].fitness < tol: #smallest element in a heap is always heap[0]
            converged = True
            print("Error below tolerance, sucess! Printing king")
            kings[0].pretty_print()
            print("Broke tolerance after ", gen_count, " generations")
            break

        gen_count += 1
        start = time.time()
        next_gen = run_generation(old_gen, num_torn, district)
        king = next_gen[1]
        heappush(kings, king)
        timesum += time.time() - start #caclulate time to run generation
        output.append((king.fitness, kings[0].fitness, diversity(next_gen[0]), time.time() - start, timesum)) #record results

        # age generation
        old_gen = next_gen

        # if we don't improve converg_count + 1 times in a row, consider us converged
        # kings[0] gets the smallest element in the heap
        if king.fitness > kings[0].fitness:
            converg_count += 1
            if converg_count > converg_tol:
                print("fitness has not improved in",  converg_count, " generations")
                converged = True
        else:
            converg_count = 0

def run_generation(old_gen, num_tourns, district):
    """
    :param old_gen: the generation to produce children from in index zero, the king in index 1
    :param details: a touple, the first integer specifying the type of
    parent selection (1 for tournament), the second entry specifying the
    number of tournaments (for tournament)
    :param district: district object for the problem
    :return: tuple: the first entry is the new population, of size equal to the
    old_gen, the second is the best overall tree from the new generation
    """
    next_gen = []
    best_fitness = float('inf')
    king = None
    old_king = Assignment(old_gen[1].rs_list)  #add the old king
    old_king.fitness = old_gen[1].fitness
    next_gen.append(old_king)
    while len(next_gen) < len(old_gen[0]):
        champs = tournament(old_gen[0], num_tourns, district)
        # get n kids from a tournament that splits the population into n groups
        for i in range(num_tourns):
            #print ' breeding child ', i, ' of ', num_tourns
            # randomly select a parent
            index1 = randint(0, len(champs) - 1)
            parent1 = champs[index1]

            rand = randint(0, 100)#reproduction options, currently set only to mutate
            #normal crossover
#             if rand < 50:
#                 print 'crossing over'
#                 child = parent1.crossover(parent2, district)
#
#             #crossover without considering fitness
#             elif rand < 75:
#                 print 'crossing over random'
#                 r_index1 = randint(0, len(old_gen[0]) - 1)
#                 r_index2 = randint(0, len(old_gen[0]) - 1)
#                 child = old_gen[0][r_index1].crossover(old_gen[0][r_index2], district)

            #regular mutate
            if rand < 90:
                #print 'mutating'
                parent1.mutate(district)
                child = parent1
            #new original
            else:
                #print 'spawning'
                child = district.spawn()

            if child.fitness < best_fitness:
                best_fitness = child.fitness
                king = Assignment(child.rs_list)
                king.fitness = child.fitness
            next_gen.append(child)

    #print 'the king has fitness ', king.fitness
    return next_gen, king

def tournament(pop, num_torns, district):
    """
    split the population into num_torn groups, plus one for the leftovers,
    then return the best of those groupsas the mating pool
    Requires that the list of trees, pop, is randomized
    For added complexity, we can change from just giving the best,
    to giving the best with probability p (probably around .8), the
    second best with probability p*(1-p), and the third best with probability
    p((1-p)^2), giving the remainder to the first best
    :param pop: the population to select a mate pool from
    :param num_torns: the number of tornaments to hold
    :param district: the district data type
    :return champions: a list of num_torns different champions, who
    are the most fit
    """
    champions = []
    # print(pop)
    # print()
    # print(list(map(lambda x : x.fitness, pop)))
    # exit()
    torn_size = int(len(pop) / num_torns) # the size of each tournament
    # create num_torn tournaments from which to choose a winner
    #print 'num_torns is', num_torns
    for i in range(num_torns):
        #print 'running tournament', i
        # run tournaments
        best = float('inf')
        best_child = None
        for j in range(torn_size):
            # print(pop[(i * torn_size) + j].fitness)
            assignment = pop[(i * torn_size) + j]
            assignment.calcFitness(district)
            fitness = assignment.fitness

            if fitness < best: #see if its the best
                best = fitness
                best_child = copy.deepcopy(pop[(i * torn_size) + j])
            # Use this if you want to keep track and give second place a chance
            # torns[i].append(pop[(i * torn_size) + j])
        if best_child is not None: # final best
            champions.append(best_child)

    if len(pop) % num_torns != 0:
        # add the stragglers leftover from integer division to the last one
        # definitely check this
        best = float('inf')
        best_child = None
        for j in range(len(pop) % num_torns):
            #print ' examining straggler '
            assignment = pop[((num_torns - 1) * torn_size) + torn_size + j]
            assignment.calcFitness(district)
            fitness = assignment.fitness
            if fitness < best:
                best = fitness
                best_child = copy.deepcopy(pop[((num_torns - 1) * torn_size) + torn_size + j])
        if best_child is not None:
            champions.append(best_child)
        # torns.append([])
        # Use for 2nd place chance
        # torns[num_torns].append(pop[((num_torns - 1) * torn_size) + torn_size + i])
    return champions

def new_gen(size, district):
    """
    :type size: size of the generation
    :return tuple: the new generation in the first entry,
    the very best individual in the second entry
    """
    children = []
    best_fit = float('inf')
    king = None

    for i in range(size):
        children.append(district.spawn())
        if children[i].fitness < best_fit:
            king = Assignment(children[i].rs_list)
            king.fitness = children[i].fitness #deepcopy doesn't fucking work
            best_fit = king.fitness
    return children, king

# calculates the diversity of the generation
def diversity(children):
    worst_fitness = float('inf')
    for child in children:
        if child.fitness < worst_fitness and child.fitness != float('inf'):
            worst_fitness = child.fitness
    sum = 0
    for child in children:
        if child.fitness and child.fitness != float('inf'):
            sum += (child.fitness / worst_fitness)

    mean = sum / len(children)

    diff_sum = 0
    for i in range(len(children)):
        if children[i].fitness != float('inf'):
            diff = ((children[i].fitness / worst_fitness) - mean) ** 2
            diff_sum += diff

    var = math.sqrt(diff_sum)
    return var

def main():
    if (len(sys.argv) != 3):
        print ()
        print ("***********************************************************")
        print ("You need to supply a .csv file containing the road data and school data")
        print ("as a command-line argument.")
        print()
        print ("Example:")
        print ("    python final_driver all-rc.csv allschools.csv")
        print ("***********************************************************")
        print()
        return
    for i in range(10):
        print()
    print ('Reading in ', sys.argv[1], 'with' , sys.argv[2] + '...')
    all_district = readData(sys.argv[1], sys.argv[2])
    print ('Finished')

    ##Set parameters
    # evolution with the data set, 100 people in a generation, (tournament selction with fifteen tournaments),
    # and mse error tolerance of 1
    evolution(gen_size, num_torn, all_district, error_tol)

if __name__ == "__main__":
    main()


import cv2
import argparse

import numpy as np

import os
from os import path

import sys
sys.path.append("../Few-Shot-Patch-Based-Training/_tools/")
import config

def gamma_lut(gamma):
    lut = np.empty((1, 256), np.uint8)
    lut[0] = [np.clip(pow(i / 255.0, gamma) * 255.0, 0, 255) for i in range(256)]
    return lut

def adjust_gamma(gamma, input_path, output_path):
    image_names = os.listdir(input_path)
    image_names.sort()

    image_names = image_names[int(config.frameFirst) - 1: int(config.frameLast)]
    image_paths = [path.join(input_path, x) for x in image_names]
    output_paths = [path.join(output_path, x) for x in image_names]

    if not path.isdir(output_path):
        os.mkdir(output_path)

    lut = gamma_lut(gamma)

    for i, image_path in enumerate(image_paths):
        img = cv2.imread(image_path)
        out_img = cv2.LUT(img, lut)
        cv2.imwrite(output_paths[i], out_img)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=""" Creates masks for body""")

    parser.add_argument("--gamma", "-g",
        help="Gamma for gamma correction",
        type=float,
        required=True
    )

    parser.add_argument("--input-path", "-i",
        help="The path to the folder with the images",
        required=True)

    parser.add_argument("--output-path", "-o",
        help="The folder the masks are writen to",
        required=True
    )

    args = parser.parse_args()
    adjust_gamma(args.gamma, args.input_path, args.output_path)


#!/usr/bin/env python
# coding: utf-8

# ## Series

# In[1]:

#Import pandas
# A basic series, which can be created is an Empty Serie
import pandas as pd
s = pd.Series()
print(s)

# In[2]:

#Create numpy 1-d array
import numpy as np

data = np.array(['a','b','c','d'])
s = pd.Series(data)
print(s)

# In[3]:

#Create a Series from numpy array
data = np.array(['a','b','c','d'])
s = pd.Series(data,index=[100,101,102,103])
print(s)

# In[4]:

#Create a Series from dictionary
data = {'a': 0., 'b': 1., 'c': 2.}
s = pd.Series(data)
print(s)

# In[5]:

#Create an empty DataFrame
df = pd.DataFrame()
print(df)

# In[6]:

#Create a DataFrame from Lists
data = [1,2,3,4,5]
df= pd.DataFrame(data)
print(df)

# In[7]:

#Create a DataFrame from Dict of ndarrays / Lists
data = {'Name':['Tom','Jack','Steve','Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data)
print(df)

# In[8]:

#Create a DataFrame from Dict of Series
d = {'one' : pd.Series([1,2,3], index=['a','b','c']),
    'two' : pd.Series([1,2,3,4], index=['a','b','c','d'])}

df = pd.DataFrame(d)
print(df)

# In[9]:

#Column selection
d = {'one' : pd.Series([1,2,3], index=['a','b','c']),
    'two' : pd.Series([1,2,3,4], index=['a','b','c','d'])}

df = pd.DataFrame(d)
print(df['one'])

# In[10]:

#column adition
d = {'one' : pd.Series([1,2,3], index=['a','b','c']),
    'two' : pd.Series([1,2,3,4], index=['a','b','c','d'])}

df = pd.DataFrame(d)

# Adding a new column to an existing DataFrame object with column label by passing new series
print("Adding a new column by passing as Series")
df['three']=pd.Series([10,20,30],index=['a','b','c'])
print(df)

print("Adding a new column using the existing columns in DataFrame")
df['four']=df['one']+df['three']

print(df)

Data Science Basics/Data Science & Business Intelligence/DataFrame and Series .py


import sys

def push(n):
    stack.append(n)

def pop():
    if len(stack) == 0:
        print("-1")
    else:
        print(stack[-1])
        stack.pop()

def size():
    print(len(stack))

def empty():
    if len(stack) == 0:
        print("1")
    else:
        print("0")

def top():
    if len(stack) == 0:
        print("-1")
    else:
        print(stack[-1])

stack = []

n = int(sys.stdin.readline())
data = [sys.stdin.readline().strip() for i in range(n)]

for i in range(n):
    if data[i].split()[0] == "push":
        push(int(data[i].split()[1]))
    elif data[i].split()[0] == "pop":
        pop()
    elif data[i].split()[0] == "empty":
        empty()
    elif data[i].split()[0] == "top":
        top()
    elif data[i].split()[0] == "size":
        size()