#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
| Featurizers for pretrain-gnn.

| Adapted from https://github.com/snap-stanford/pretrain-gnns/tree/master/chem/utils.py
"""

import numpy as np
import networkx as nx
import pgl
from rdkit.Chem import AllChem

from pahelix.featurizers.featurizer import Featurizer
from pahelix.utils.compound_tools import mol_to_graph_data

__all__ = [
    'PreGNNAttrMaskFeaturizer',
    'PreGNNSupervisedFeaturizer',
    'PreGNNContextPredFeaturizer',
]

class PreGNNAttrMaskFeaturizer(Featurizer):
    """Featurizer for attribute mask model of pretrain gnns"""
    def __init__(self, graph_wrapper, atom_type_num=None, mask_ratio=None):
        super(PreGNNAttrMaskFeaturizer, self).__init__()
        self.graph_wrapper = graph_wrapper
        self.atom_type_num = atom_type_num
        self.mask_ratio = mask_ratio

    def gen_features(self, raw_data):
        """Convert smiles into graph data.

        Returns:
            data(dict): a dict of numpy ndarray consists of graph features.
        """
        smiles = raw_data['smiles']
        mol = AllChem.MolFromSmiles(smiles)
        if mol is None:
            return None
        data = mol_to_graph_data(mol)
        data['smiles'] = smiles
        return data

    def collate_fn(self, batch_data_list):
        """Aggregate a list of graph data into a batch data"""
        g_list = []
        for data in batch_data_list:
            g = pgl.graph.Graph(num_nodes = len(data['atom_type']),
                    edges = data['edges'],
                    node_feat = {
                        'atom_type': data['atom_type'].reshape([-1, 1]),
                        'chirality_tag': data['chirality_tag'].reshape([-1, 1]),
                    },
                    edge_feat ={
                        'bond_type': data['bond_type'].reshape([-1, 1]),
                        'bond_direction': data['bond_direction'].reshape([-1, 1]),
                    })
            g_list.append(g)
        join_graph = pgl.graph.MultiGraph(g_list)

        ### mask atom
        num_node = len(join_graph.node_feat['atom_type'])
        masked_size = int(num_node * self.mask_ratio)
        masked_node_indice = np.random.choice(range(num_node), size=masked_size, replace=False)
        masked_node_labels = join_graph.node_feat['atom_type'][masked_node_indice]

        join_graph.node_feat['atom_type'][masked_node_indice] = self.atom_type_num
        join_graph.node_feat['chirality_tag'][masked_node_indice] = 0

        feed_dict = self.graph_wrapper.to_feed(join_graph)
        feed_dict['masked_node_indice'] = np.reshape(masked_node_indice, [-1, 1]).astype('int64')
        feed_dict['masked_node_label'] = np.reshape(masked_node_labels, [-1, 1]).astype('int64')
        return feed_dict

class PreGNNSupervisedFeaturizer(Featurizer):
    """Featurizer for supervised model of pretrain gnns"""
    def __init__(self, graph_wrapper):
        super(PreGNNSupervisedFeaturizer, self).__init__()
        self.graph_wrapper = graph_wrapper

    def gen_features(self, raw_data):
        """Convert smiles into graph data.

        Returns:
            data(dict): a dict of numpy ndarray consists of graph features.
        """
        smiles, label = raw_data['smiles'], raw_data['label']
        mol = AllChem.MolFromSmiles(smiles)
        if mol is None:
            return None
        data = mol_to_graph_data(mol)
        data['label'] = label.reshape([-1])
        data['smiles'] = smiles
        return data

    def collate_fn(self, batch_data_list):
        """Aggregate a list of graph data into a batch data"""
        g_list = []
        label_list = []
        for data in batch_data_list:
            g = pgl.graph.Graph(num_nodes = len(data['atom_type']),
                    edges = data['edges'],
                    node_feat = {
                        'atom_type': data['atom_type'].reshape([-1, 1]),
                        'chirality_tag': data['chirality_tag'].reshape([-1, 1]),
                    },
                    edge_feat ={
                        'bond_type': data['bond_type'].reshape([-1, 1]),
                        'bond_direction': data['bond_direction'].reshape([-1, 1]),
                    })
            g_list.append(g)
            label_list.append(data['label'])

        join_graph = pgl.graph.MultiGraph(g_list)
        feed_dict = self.graph_wrapper.to_feed(join_graph)

        batch_label = np.array(label_list)
        batch_label = ((batch_label + 1.0) / 2).astype('float32')
        batch_valid = (batch_label != 0.5).astype("float32")
        feed_dict['supervised_label'] = batch_label
        feed_dict['valid'] = batch_valid
        return feed_dict

def reset_idxes(G):
    """
    Resets node indices such that they are numbered from 0 to num_nodes - 1

    Args:
        G: network x object.

    Returns:
        new_G: copy of G with relabelled node indices.
        mapping:
    """
    mapping = {}
    for new_idx, old_idx in enumerate(G.nodes()):
        mapping[old_idx] = new_idx
    new_G = nx.relabel_nodes(G, mapping, copy=True)
    return new_G, mapping

def graph_data_obj_to_nx_simple(data):
    """
    Converts graph data object into a network x data object.

    NB: Uses simplified atom and bond features, and represent as indices.

    NB: possible issues with recapitulating relative stereochemistry since the edges in the nx object are unordered.

    Args:
        data(dict): a dict of numpy ndarray consists of graph features.

    Returns:
        G: a network x object
    """
    G = nx.Graph()

    # atoms
    # atom_features = data['node_feat']
    num_atoms = data['atom_type'].shape[0]
    for i in range(num_atoms):
        # atomic_num_idx, chirality_tag_idx = atom_features[i]
        G.add_node(i,
                atom_num_idx=data['atom_type'][i],
                chirality_tag_idx=data['chirality_tag'][i])

    # bonds
    edge_index = data['edges']
    # edge_attr = data['edge_feat']
    num_bonds = edge_index.shape[0]
    for j in range(0, num_bonds, 2):
        begin_idx = int(edge_index[j, 0])
        end_idx = int(edge_index[j, 1])
        # bond_type_idx, bond_dir_idx = edge_attr[j]
        if not G.has_edge(begin_idx, end_idx):
            G.add_edge(begin_idx, end_idx,
                    bond_type_idx=data['bond_type'][j],
                    bond_dir_idx=data['bond_direction'][j])

    return G

def nx_to_graph_data_obj_simple(G):
    """
    Converts nx graph to graph data. Assume node indices are numbered from
    0 to num_nodes - 1.

    NB: Uses simplified atom and bond features, and represent as indices.

    NB: possible issues with recapitulating relative stereochemistry since the edges in the nx object are unordered.

    Args:
        G: nx graph object

    Returns:
        data(dict): a dict of numpy ndarray consists of graph features.
    """
    # atoms
    atom_types = []
    chirality_tags = []
    for _, node in G.nodes(data=True):
        atom_types.append(node['atom_num_idx'])
        chirality_tags.append(node['chirality_tag_idx'])
    atom_types = np.array(atom_types)
    chirality_tags = np.array(chirality_tags)

    # bonds
    # num_bond_features = 2  # bond type, bond direction
    if len(G.edges()) > 0:  # mol has bonds
        edges = []
        bond_types = []
        bond_directions = []
        for i, j, edge in G.edges(data=True):
            # edge_feature = [edge['bond_type_idx'], edge['bond_dir_idx']]
            edges.append((i, j))
            bond_types.append(edge['bond_type_idx'])
            bond_directions.append(edge['bond_dir_idx'])
            edges.append((j, i))
            bond_types.append(edge['bond_type_idx'])
            bond_directions.append(edge['bond_dir_idx'])

        edges = np.array(edges)
        bond_types = np.array(bond_types)
        bond_directions = np.array(bond_directions)

    else:   # mol has no bonds
        edges = np.zeros((0, 2)).astype("int")
        bond_types = np.zeros((0,)).astype("int")
        bond_directions = np.zeros((0,)).astype("int")

    data = {
        'atom_type': atom_types,         # (N,)
        'chirality_tag': chirality_tags,    # (N,)
        'edges': edges,            # (E, 2)
        'bond_type': bond_types,    # (E,)
        'bond_direction': bond_directions,  # (E,)
    }
    return data

def transform_contextpred(data, k, l1, l2):
    """
    Randomly selects a node from the data object, and adds attributes
    that contain the substructure that corresponds to k hop neighbours
    rooted at the node, and the context substructures that corresponds to
    the subgraph that is between l1 and l2 hops away from the
    root node.
    """
    assist_data = {}

    num_atoms = data['atom_type'].shape[0]
    root_idx = np.random.choice(range(num_atoms), 1)[0]

    G = graph_data_obj_to_nx_simple(data)  # same ordering as input data obj

    # Get k-hop subgraph rooted at specified atom idx
    substruct_node_idxes = nx.single_source_shortest_path_length(
            G, root_idx, k).keys()

    if len(substruct_node_idxes) == 0:
        return None
    substruct_G = G.subgraph(substruct_node_idxes)
    substruct_G, substruct_node_map = reset_idxes(substruct_G)  # need
    # to reset node idx to 0 -> num_nodes - 1, otherwise data obj does not
    # make sense, since the node indices in data obj must start at 0
    substruct_data = nx_to_graph_data_obj_simple(substruct_G)
    assist_data['substruct_center_idx'] = np.array([substruct_node_map[root_idx]])  # need
    # to convert center idx from original graph node ordering to the
    # new substruct node ordering

    # Get subgraphs that is between l1 and l2 hops away from the root node
    l1_node_idxes = nx.single_source_shortest_path_length(
            G, root_idx, l1).keys()
    l2_node_idxes = nx.single_source_shortest_path_length(
            G, root_idx, l2).keys()
    context_node_idxes = set(l1_node_idxes).symmetric_difference(
            set(l2_node_idxes))
    if len(context_node_idxes) == 0:
        return None
    context_G = G.subgraph(context_node_idxes)
    context_G, context_node_map = reset_idxes(context_G)  # need to
    # reset node idx to 0 -> num_nodes - 1, otherwise data obj does not
    # make sense, since the node indices in data obj must start at 0
    context_data = nx_to_graph_data_obj_simple(context_G)

    # Get indices of overlapping nodes between substruct and context,
    # WRT context ordering
    context_substruct_overlap_idxes = list(set(
        context_node_idxes).intersection(set(substruct_node_idxes)))
    if len(context_substruct_overlap_idxes) == 0:
        return None
    context_substruct_overlap_idxes_reorder = [
            context_node_map[old_idx] for old_idx in context_substruct_overlap_idxes]
    # need to convert the overlap node idxes, which is from the
    # original graph node ordering to the new context node ordering
    assist_data['context_overlap_idx'] = np.array(context_substruct_overlap_idxes_reorder)

    return substruct_data, context_data, assist_data

class PreGNNContextPredFeaturizer(Featurizer):
    """Featurizer for context pred model of pretrain gnns"""
    def __init__(self, substruct_graph_wrapper, context_graph_wrapper, k, l1, l2):
        super(PreGNNContextPredFeaturizer, self).__init__()
        self.substruct_graph_wrapper = substruct_graph_wrapper
        self.context_graph_wrapper = context_graph_wrapper
        self.k = k
        self.l1 = l1
        self.l2 = l2

    def gen_features(self, raw_data):
        """Convert smiles into graph data.

        Returns:
            data(dict): a dict of numpy ndarray consists of graph features.
        """
        smiles = raw_data['smiles']
        mol = AllChem.MolFromSmiles(smiles)
        if mol is None:
            return None
        data = mol_to_graph_data(mol)
        data['smiles'] = smiles
        return data

    def collate_fn(self, batch_data_list):
        """Aggregate a list of graph data into a batch data"""
        list_substruct_g = []
        list_context_g = []
        list_substruct_center_idx = []
        list_context_overlap_idx = []
        cum_substruct, cum_context = 0, 0
        for data in batch_data_list:
            transformed = transform_contextpred(data, self.k, self.l1, self.l2)
            if transformed is None:
                continue
            substruct_data, context_data, assist_data = transformed
            substruct_g = pgl.graph.Graph(num_nodes = len(substruct_data['atom_type']),
                    edges = substruct_data['edges'],
                    node_feat = {
                        'atom_type': substruct_data['atom_type'].reshape([-1, 1]),
                        'chirality_tag': substruct_data['chirality_tag'].reshape([-1, 1]),
                    },
                    edge_feat ={
                        'bond_type': substruct_data['bond_type'].reshape([-1, 1]),
                        'bond_direction': substruct_data['bond_direction'].reshape([-1, 1]),
                    })
            context_g = pgl.graph.Graph(num_nodes = len(context_data['atom_type']),
                    edges = context_data['edges'],
                    node_feat = {
                        'atom_type': context_data['atom_type'].reshape([-1, 1]),
                        'chirality_tag': context_data['chirality_tag'].reshape([-1, 1]),
                    },
                    edge_feat ={
                        'bond_type': context_data['bond_type'].reshape([-1, 1]),
                        'bond_direction': context_data['bond_direction'].reshape([-1, 1]),
                    })
            list_substruct_g.append(substruct_g)
            list_context_g.append(context_g)
            list_substruct_center_idx.append(assist_data['substruct_center_idx'] + cum_substruct)
            list_context_overlap_idx.append(assist_data['context_overlap_idx'] + cum_context)
            cum_substruct += len(substruct_data['atom_type'])
            cum_context += len(context_data['atom_type'])

        join_substruct_graph = pgl.graph.MultiGraph(list_substruct_g)
        join_context_graph = pgl.graph.MultiGraph(list_context_g)
        substruct_center_idx = np.concatenate(list_substruct_center_idx, 0)
        context_overlap_idx = np.concatenate(list_context_overlap_idx, 0)
        context_overlap_lod = np.append([0], np.cumsum([len(x) for x in list_context_overlap_idx]))
        batch_size = len(list_context_overlap_idx)
        context_cycle_index = np.append(np.arange(1, batch_size), [0])

        feed_dict = self.substruct_graph_wrapper.to_feed(join_substruct_graph)
        feed_dict.update(self.context_graph_wrapper.to_feed(join_context_graph))
        feed_dict['substruct_center_idx'] = np.reshape(substruct_center_idx, [-1, 1]).astype('int64')
        feed_dict['context_overlap_idx'] = np.reshape(context_overlap_idx, [-1, 1]).astype('int64')
        feed_dict['context_overlap_lod'] = np.reshape(context_overlap_lod, [1, -1]).astype('int32')
        feed_dict['context_cycle_index'] = np.reshape(context_cycle_index, [-1, 1]).astype('int64')
        return feed_dict


# Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import argparse
import os
import re
import sys

_CWD = os.getcwd()
_HERE_DIR = os.path.dirname(__file__)
_SRC_DIR = os.path.normpath(os.path.join(_HERE_DIR, '..', '..'))

sys.path.append(os.path.join(_SRC_DIR, 'third_party', 'node'))
import node
import node_modules

def main(argv):
  parser = argparse.ArgumentParser()
  parser.add_argument('--out_dir', required=True)
  parser.add_argument('--root_dir', required=True)
  parser.add_argument('--js_files', nargs='*', required=True)
  args = parser.parse_args(argv)

  js_files = [os.path.join(args.root_dir, f) for f in args.js_files]

  node.RunNode([
      node_modules.PathToTypescript(),
      '--declaration',
      '--allowJs',
      '--emitDeclarationOnly',
      '--removeComments',
      '--noResolve',
      '--rootDir',
      args.root_dir,
      '--outDir',
      args.out_dir,
  ] + js_files)

if __name__ == '__main__':
  main(sys.argv[1:])


#!/usr/bin/env python3

import json
import requests
import sys
import time

URL_PREFIX = "http://{}:8181/restconf/{}"
INVENTORY_URL = URL_PREFIX + "/opendaylight-inventory:nodes"
TABLE_URL = INVENTORY_URL + "/node/{}/flow-node-inventory:table/{}"
FLOW_URL = TABLE_URL + "/flow/{}"
OP = "operational"
CFG = "config"
TABLE_ID = 0
LLDP = 0x88cc
ARP = 0x0806
HEADERS = {"content-type": "application/json", "accept": "application/json"}
AUTH = ("admin", "admin")

TIME_INTERVAL = 2 # check the flow rules every _ seconds

FLOW_RULE_TEMPLATE='''
{
    \"flow\": {
        \"id\": %s,
        \"match\": {
            \"ethernet-match\": {
                \"ethernet-type\": {
                    \"type\": %d
                }
            }
        },
        \"priority\": %d,
        \"idle-timeout\": 0,
        \"hard-timeout\": 0,
        \"table_id\": 0,
        \"instructions\": {
            \"instruction\": [
                {
                    \"order\": 0,
                    \"apply-actions\": {
                        \"action\": [
                            {
                                \"order\": 0,
                                \"output-action\": {
                                    \"output-node-connector\": \"CONTROLLER\",
                                    \"max-length\": 65535
                                }
                            }
                        ]
                    }
                }
            ]
        }
    }
}
'''

def is_matching_ethernet_protocol(flow, protocol):
    try:
        match = flow['match']
        if len(match) > 1:
            return False
        ethernet_match = match['ethernet-match']
        if len(ethernet_match) > 1:
            return False
        return ethernet_match['ethernet-type']['type'] == protocol
    except Exception:
        return False

def is_sending_to_controller(flow):
    try:
        instructions = flow['instructions']['instruction']
        if len(instructions) > 1:
            return False
        actions = instructions[0]['apply-actions']['action']
        if len(actions) > 1:
            return False
        return actions[0]['output-action']['output-node-connector'].upper() == 'CONTROLLER'
    except Exception:
        return False

def to_hex(value):
    return '0x{:04x}'.format(value)

def check_and_install(controller_ip, node_id, proto):
    tbl_url = TABLE_URL.format(controller_ip, OP, node_id, TABLE_ID)

    response = requests.get(tbl_url, headers=HEADERS, auth=AUTH)
    checked = False
    try:
        table = response.json()['flow-node-inventory:table'][0]
        print(table)
        for flow in table['flow']:
            if not is_matching_ethernet_protocol(flow, proto):
                continue
            if not is_sending_to_controller(flow):
                continue
            checked = True
            break;
    except Exception:
        pass

    print('{} status: {}'.format(node_id, checked))

    if not checked:
        fl_url = FLOW_URL.format(controller_ip, CFG, node_id, TABLE_ID, to_hex(proto))
        priority = 100 if proto == LLDP else 1
        data = FLOW_RULE_TEMPLATE % ('\"{}\"'.format(to_hex(proto)), proto, priority)
        response = requests.put(fl_url, headers=HEADERS, data=data, auth=AUTH)
        print(response.status_code)

def stabilize(controller_ip):
    while True:
        try:
            oneshot_stabilize(controller_ip)
            time.sleep(TIME_INTERVAL)
        except KeyboardInterrupt as e:
            break
        except Exception as e:
            continue

def oneshot_stabilize(controller_ip):
    pattern = INVENTORY_URL
    url = pattern.format(controller_ip, OP)

    response = requests.get(url, headers=HEADERS, auth=AUTH)
    if response.ok:
        inventory = response.json()
        for node in inventory['nodes']['node']:
            node_id = node['id']
            print(node_id)
            check_and_install(controller_ip, node_id, LLDP)
            check_and_install(controller_ip, node_id, ARP)

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Usage: python {} CONTROLLER_IP".format(__file__))
        sys.exit()
    oneshot_stabilize(sys.argv[1])


from posts.models import posts

__author__ = 'vdjke'
from django import forms

class PostsForms(forms.ModelForm):

    titulo = forms.CharField(max_length=240, min_length=8, required=True,
                             widget=forms.TextInput(attrs={
                                 'class': 'form-control',
                                 'name': 'titulo', 'id': 'titulo', 'placeholder': 'Escribe un titulo'}))
    cuerpo = forms.CharField(required=True,
                             widget=forms.Textarea(attrs={
                                 'class': 'form-control',
                                 'name': 'cuerpo',
                                 'id': 'cuerpo',
                                 'placeholder': 'Contenido del posts'}))
    categoria = forms.Select(attrs={'class': 'form-control'})
    tags = forms.CharField(max_length=240, min_length=10, required=True,
                           widget=forms.TextInput(attrs={'class': 'form-control',
                                 'placeholder': 'Etiquetas separadas por comas (,)', 'id': 'tags'}))
    img_file = forms.CharField(required=True,
                               widget=forms.TextInput(attrs={
                                   'class': 'form-control',
                                   'placeholder': 'Seleccion un archivo',
                                   'id': 'append-big-btn',
                                   'readonly': '',

                               }))
    permitir_comentarios = forms.BooleanField(required=False,
                                              widget=forms.CheckboxInput(
                                                  attrs={}))

    class Meta:
        model = posts
        fields = {'titulo', 'categoria', 'cuerpo', 'tags', 'permitir_comentarios', 'img_file'}
        widgets = {
            'categoria': forms.Select(attrs={'class': 'form-control'})
        }


#-------------------------------------------------------------------------------------------------------------------
# depthwise_conv_v2 - Balaji Adithya V
# Define custom torch function approx_depth_conv() and implementation of MBM algo done
# Create lookup table for referring while performing MBM
# ------------------------------------------------------------------------------------------------------------------

import torch
import numpy as np
import torchvision as tv
from torch import nn
import torch.nn.functional as F
from torch.nn.functional import unfold
from torch.utils.cpp_extension import load

#---------------------------------------------- HERE ---------------------------------------------------------------
# This snippet of code extracts row-wise data from reference_mbm.csv that contains the data for determining product
# value based on the 2 inputs.
#
# Lookup_table created where the inputs themslves act as the pointers needed to locate the MBM product
# (eg) i=25, j=64, then lookup_table[i][j] = MBM(i,j). In tis manner the look up time complexity reduces to O(1)

import csv
import pandas as pd
import time

filename = "reference_mbm.csv"
rows = []

with open(filename, 'r') as file:
	rows = list(csv.reader(file))

	for row in rows[1:]:
		row[0], row[1], row[2] = int(row[0]), int(row[1]), int(row[2])

lookup_table = np.zeros((256,256))
for row in rows[1:]:
	lookup_table[row[0]][row[1]] = row[2]

#-------------------------------------------------------------------------------------------------------------------
# approx_conv class
# Derived from the torch.autograd.Function class
# Performs in_feature * kernel where (*) represents depthwise-convolution operation
#
# out_channel = in_channel
#
# in_feature dimensions -> [batch_size, in_channel, in_height, in_width]
# kernel dimensions     -> [out_channel, 1, kh, kw]
#
# Create patches of input image based on kernel size; Kernel size is also reshaped -> done for efficient computation (parallelizing)
# patches dimensions -> [batch_size, in_channel, out_h*out_w, kh*kw]
# kernel dimensions  -> [in_channel, 1*kh*kw]
# result[b][c] = k[c]*patches[b][c] -> dimensions -> [out_channel, out_h, out_w]; where b denotes current batch, c=current channel
#--------------------------------------------------------------------------------------------------------------------

class depthwise_conv(torch.autograd.Function):
	@staticmethod

	def forward(ctx, in_feature, kernel, out_channel, stride, padding, dilation, groups, bias):
		print("I'm in conv fwd")
		print("input = {}".format(in_feature.shape))
		print("kernel= {}".format(kernel.shape))

		batch_size = in_feature.size(0)
		in_channels = in_feature.size(1)
		orig_h, orig_w = in_feature.size(2), in_feature.size(3)

		tmp = torch.abs(in_feature)
		mx = torch.max(tmp)
		mn = torch.min(tmp)
		mean = torch.mean(tmp)

		print(mx ,mn ,mean)

		#Kernel Dimenstions
		kh, kw = kernel.size(2), kernel.size(3)
		#Strides
		dh, dw = stride, stride

		pad = padding

		#output dimensions
		out_h = (orig_h+2*pad-kh)//dh + 1
		out_w = (orig_w+2*pad-kw)//dw + 1

		img = F.pad(input= in_feature, pad= (pad, pad, pad, pad), mode='constant', value= 0)

		patches = img.unfold(2,kh,dh).unfold(3,kw,dw).reshape(batch_size, in_channels, out_h*out_w, kh*kw)
		result = torch.zeros(batch_size, out_channel, out_h*out_w)
		kernel = kernel.reshape(out_channel, -1)

		for b in range(batch_size):
			x = patches[b]
			print(x.shape)
			for c in range(groups):
				start = time.time()
				for i in range(x.size(1)):
					r=0
					for j in range(kernel.size(1)):
						t1 = int((kernel[c][j]*10).round())
						t2 = int((x[c][i][j]*10).round())

						if(t1>255) : t1 =255
						if(t1<-255): t1 =-255
						if(t2>255) : t2 =255
						if(t2<-255): t2 =-255

						if((t1>0 and t2>0) or (t1<0 and t2<0)):
							t1=abs(t1)
							t2=abs(t2)
							sign=1
						else:
							t1=abs(t1)
							t2=abs(t2)
							sign=-1

						r += lookup_table[t1][t2]*sign

					result[b][c][i] = r/100

				end = time.time()
				print("time taken for channel {}/ {} in batch {} is {}s".format(c, groups, b, end-start))

		result = result.reshape(batch_size, out_channel, out_h, out_w)

		if bias is not None:
			result+= bias[None,:,None,None].expand_as(result)

		return result

#-------------------------------------------------------------------------------------------------
# approx_dconv class
# Derived from nn.Module class
# Used to register the parameters of the conv layer - weight, bias
# Call the depthwise_conv constructor to start depthwise convolution operation
#-------------------------------------------------------------------------------------------------

class approx_dconv(nn.Module):
	def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias=False):
		super(approx_dconv, self).__init__()

		#Initialize misc. variables
		self.in_channels = in_channels
		self.out_channels = out_channels
		self.stride = stride
		self.dilation = dilation
		self.groups = groups
		self.padding = padding
		self.weight = nn.Parameter(torch.Tensor(out_channels, 1, kernel_size, kernel_size))
		self.bias = self.register_parameter('bias',None)
		# print("I'm here")

	def forward(self, x):
		# print("I'm in fwd of approx_dconv")
		return depthwise_conv.apply(x, self.weight, self.out_channels, self.stride, self.padding, self.dilation, self.groups, self.bias)


import requests
from lxml import etree

'''
1.发送请求获取响应内容
2.解析内容获取所需信息
'''

class Baidu_hotspots:
    def __init__(self):
        self.url = 'http://top.baidu.com/buzz?b=1&c=513&fr=topbuzz_b341_c513'
        self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'}

    def get_url(self):
        try:
            r = requests.get(self.url,headers=self.headers)
            r.encoding = r.apparent_encoding
            content = r.content.decode('gbk')
            #print(content) 检测输出内容正常
            return content
        except:
            return '请求失败'

    def get_content(self,content):
        html = etree.HTML(content)
        title_one = html.xpath('//div[@class="top-title"]/h2/text()')[0] #获取大标题
        print('{:^55}'.format(title_one),'\n')

        #获取排名，关键词，搜索指数三个内容
        nums = html.xpath('//table[@class="list-table"]//td[@class="first"]/span/text()')
        keywords = html.xpath('//table[@class="list-table"]//td[@class="keyword"]/a[1]/text()')
        search_indexs = html.xpath('//table[@class="list-table"]//td[@class="last"]/span/text()')
        #print(nums,keywords,search_indexs)
        for num,keyword,search_index in zip(nums,keywords,search_indexs):
            hotspot = "排名：{0:^4}\t关键词：{1:^15}\t搜索指数：{2:^8}" .format(num,keyword,search_index)
            print(hotspot)

    def main(self):
        content = self.get_url()
        self.get_content(content)

if __name__ == '__main__':
    realtime_hotspot = Baidu_hotspots()
    realtime_hotspot.main()


import argparse, os

def parse():
  parser = argparse.ArgumentParser(description="Evaluate the truth")
  parser.add_argument('files', type=str, nargs="*")
  parser.add_argument('-v', '--verbose', action="store_true", help='Verbose output')
  args = parser.parse_args()
  if len(args.files) == 0:
    raise Exception("No file arguments found")
  files = args.files
  importedFiles = []
  errorFiles = []
  successFiles = []
  for currentFile in files:
    if (os.path.isfile(currentFile)):
      importedFiles.append((open(currentFile, 'r').readlines()))
      successFiles.append(currentFile)
    else:
      errorFiles.append(currentFile)
  if len(errorFiles) != 0:
    if len(successFiles) != 0:
      return args, importedFiles
    else:
      raise Exception("No files found in supplied file arguments", errorFiles)
  return args, importedFiles


# -*- coding: utf-8 -*-
"""
Created on Mon Jul 10 16:33:15 2017

@author: Jo_Lin
"""

#import pandas
#pd.Series()
#pd.show_Versions()

print("===== start =====")

from appium import webdriver
import time

desired_caps={
    'platformName':'Android',
    'deviceName':'H4AZCY00W518XPD',
    'platformVersion':'6.0.1',
    #APK Package Name
    'appPackage':'com.asus.deskclock',
    #APK Launch Activity
    'appActivity':'.DeskClock'
#     'appActivity':'com.asus.deskclock.DeskClock'
#    'appActivity':'com.asus.deskclock',
}

driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub',desired_caps)

time.sleep(5)

#確認上方tab按鈕的元件
#driver.find_element_by_id("com.asus.deskclock:id/tab_icon").click()
#comp=driver.find_element_by_class_name("android.widget.LinearLayout")
#print("type:",type(comp) , "\n","\n","Data:",comp)

comp=driver.find_element_by_class_name("android.widget.LinearLayout")
for a in comp:
    print(a.get_attribute('index'))

#count=0;
#for ob in comp:
#    count+=1
#    print(count ," . ",ob)
#for data in comp:

#呼叫new alarm page
#driver.find_element_by_id("com.asus.deskclock:id/bt_add_alarm").click()
#driver.find_element_by_id("com.asus.deskclock:id/asus_commonui_minutes").click()
#driver.press_keycode(7)
#driver.press_keycode(8)
#按下back
#for i in range(0,2):
#    driver.press_keycode(4)
#    time.sleep(2)
driver.quit()
print("=====end=====")


from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import NoSuchElementException
import time
from .models import Professor

def scrape_professors():
    #Open webpage
    url = "https://www.ratemyprofessors.com/campusRatings.jsp?sid=877"
    driver = webdriver.Chrome('C:\\Users\\jari\dev\\rmp_scraper\\chromedriver')
    driver.set_window_size(540,1080)
    driver.implicitly_wait(10)

    # Launch Webscraper
    driver.get(url)

    #Close cookie pop-up
    driver.find_element_by_xpath("/html/body/div[10]/button").click()

    #Click 'Top Professors'
    driver.find_element_by_xpath("//a[@class='button-link']").click()

    counter = 1
    page = 0
    result = False
    while result is False:
        try:
            while True:
                for i in range(20):
                    #time.sleep(.1)
                    try:
                        professors = driver.find_element_by_xpath("/html/body/div[3]/div[4]/div/div[1]/div/div[5]/ul/li[{}]".format(counter))
                        new_professor = Professor.objects.create(data=professors.text, page=page, counter=counter)
                        new_professor.save()
                        counter += 1
                    except:
                        counter -= 1
                try:
                    #time.sleep(.5)
                    driver.find_element_by_xpath("//*[@id='mainContent']/div[1]/div/div[5]/div/div[1]").click()
                    page += 1
                    print(counter)
                except:
                    break
            result = True
        except:
            pass

    print('Done')

    return


# -*- coding: utf-8 -*-
#########################################################################
#
# Copyright 2015-2018, GeoSolutions Sas.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
#
#########################################################################
from django import template

register = template.Library()

@register.inclusion_tag(
    'geonode-mapstore-client/_client_composer_js.html', takes_context=True)
def client_composer_js(context, options=None):
    """
    React Client Composer js template tag.
    """
    return context

@register.inclusion_tag(
    'geonode-mapstore-client/_client_viewer_js.html', takes_context=True)
def client_viewer_js(context, options=None):
    """
    React client viewer js template tag.
    """
    return context


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

img = cv2.imread("enhancedPic.jpg")
img = cv2.resize(img, None, fx=0.2, fy=0.2, interpolation=cv2.INTER_CUBIC)
cv2.waitKey(0)
picSize = img.shape
smallW = int(picSize[1]/4)
smallH = int(picSize[0]/2)
for i in range(2):
    for j in range(4):
        imgSlice = img[smallH*i:smallH*i+smallH,
                       smallW*j:smallW*j+smallW]  # sliced small pic
        filename = "slicedPic{}_{}.jpg".format(i, j)
        cv2.rectangle(img, (smallW*j, smallH*i), (smallW*j+smallW,
                                                  smallH*i+smallH), (0, 128, 128), 3)  # draw boundary rectangle
        cv2.imwrite(filename, imgSlice)
cv2.waitKey(0)
cv2.destroyAllWindows()

# pre process
for i in range(2):
    for j in range(4):
        rawImg = cv2.imread("slicedPic{}_{}.jpg".format(i, j))
        img = cv2.cvtColor(rawImg, cv2.COLOR_BGR2GRAY)
        # img = cv2.GaussianBlur(img, (2, 2), 10)#gauss morph
        ret, thresholdedImg = cv2.threshold(img, 5, 255, cv2.THRESH_BINARY)

        validShape = [0, 0, 0, 0]

        okFlag = False
        for y in range(thresholdedImg.shape[0]):
            if okFlag:
                break
            for x in range(thresholdedImg.shape[1]):
                if thresholdedImg[y, x] != 255:
                    validShape[0] = y
                    okFlag = True
                    break
        okFlag = False
        for y in range(thresholdedImg.shape[0]-1, -1, -1):
            if okFlag:
                break
            for x in range(thresholdedImg.shape[1]):
                if thresholdedImg[y, x] != 255:
                    validShape[1] = y
                    okFlag = True
                    break
        okFlag = False
        for x in range(thresholdedImg.shape[1]):
            if okFlag:
                break
            for y in range(thresholdedImg.shape[0]):
                if thresholdedImg[y, x] != 255:
                    validShape[2] = x
                    okFlag = True
                    break
        okFlag = False
        for x in range(thresholdedImg.shape[1]-1, -1, -1):
            if okFlag:
                break
            for y in range(thresholdedImg.shape[0]):
                if thresholdedImg[y, x] != 255:
                    validShape[3] = x
                    okFlag = True
                    break

        boxHalfSize = int(max(
            validShape[1]-validShape[0], validShape[3]-validShape[2])*1.5/2)  # set 30% margin
        boxCenter = (int((validShape[1]+validShape[0])/2),
                     int((validShape[3]+validShape[2])/2))

        limitedImg = thresholdedImg[boxCenter[0]-boxHalfSize:boxCenter[0] +
                                    boxHalfSize, boxCenter[1]-boxHalfSize:boxCenter[1]+boxHalfSize]

        resized_image = ~cv2.resize(limitedImg, (28, 28))
        outFilename = "slicedPic{}_{}mono.jpg".format(i, j)
        cv2.imwrite(outFilename, resized_image)

dafaultstderr = sys.stderr
nullstderr=open(os.devnull, 'w')

print('loading Keras')
sys.stderr =nullstderr
from keras.models import load_model
sys.stderr = dafaultstderr

print('loading model')
sys.stderr =nullstderr
model = load_model('mnistModel.h5')
sys.stderr = dafaultstderr
X_pred = np.zeros(shape=(8, 28, 28))
index = 0
for i in range(2):
    for j in range(4):
        img = cv2.imread("slicedPic{}_{}mono.jpg".format(i, j))
        imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        X_pred[index] = cv2.resize(imgGray, (28, 28))
        index += 1

X_test = X_pred.reshape(8, 784).astype('float32') / 255
y_test = [1, 2, 3, 4, 5, 6, 7, 8]

print('pridicting...')
sys.stderr =nullstderr
y_predict = model.predict_classes(X_test)
sys.stderr = dafaultstderr
correctCount = len(np.nonzero(y_predict == y_test)[0])
print('correct:{},total:{},percentage:{:.1f}%'.format(
    correctCount, len(y_predict), 100*correctCount/len(y_predict)))


import os, sys
import numpy as np
from sympy import *

from itertools import count
from pprint import pprint
from collections import defaultdict

class State:
    """ States
    """
    def __init__(self, value):
        self.value = value

class VASS:
    """Implementing Vector Addition Systems with States
    Which contains
    States set
    Transitions set
    Vectors set and some functions
    """

    def __init__(self, *configs):
        self.trans = defaultdict(dict)
        for i in configs:
            pre, suc = i[0].value, i[2].value
            self.trans[pre][suc] = i[1]
            pprint(self.trans)

    def initial(self, *configs):
        pass

    def is_reachable(self, state, vec):
        if not "Q_0" in self.trans:
            sys.exit("Q_0 is not the initial state")

        count = 0
        curr_state = "Q_0"
        curr_vec = [0, 0, 0]
        trans = self.trans

        while count < 100:
            count += 1
            if curr_state in trans:
                successors = list(trans[curr_state].keys())
                a_suc = successors[0]
                vector = trans[curr_state][a_suc]
                curr_state = a_suc

                for i in range(len(curr_vec)):
                    curr_vec[i] += vector[i]

        print (curr_vec)

if __name__ == '__main__':
    print ('File name: ' + str(__file__))

    q0 = State("Q_0")
    q1 = State("CALL !PUSH !1 !2")
    q2 = State("RET !PUSH !TRUE !2")
    vec_1 = [0, 1, 2]
    vec_2 = [0, 0, -1]
    vec_3 = [2, -2, 0]

    vass = VASS((q0, vec_1, q1), (q1, vec_2, q2), (q2, vec_3, q0))
    vass.is_reachable(q0,vec_1)

    # from scipy.linalg import solve

    a = np.array([vec_1, vec_2, vec_3])
    b = np.array([2, -1, 1])
    # b = np.array([66, -32, 35])
    # x = solve(a, b)

    a = Matrix([vec_1, vec_2])
    b = Matrix([[66], [-32], [35]]);
    x = symarray('x', 2)
    solve(a*x - b)


import click
import pandas as pd
import numpy as np
import json
from os import path
from datetime import date
from urllib.request import urlopen

AVAPI_KEY_JSON = "avapi_key.json"
BASE = "https://www.alphavantage.co/query?function={}&symbol={}&apikey={}&datatype=csv"

STOCK_FUNC_LIST = {
    'intraday': "TIME_SERIES_INTRADAY",
    'daily':    "TIME_SERIES_DAILY",
    'weekly':   "TIME_SERIES_WEEKLY",
    'monthly':  "TIME_SERIES_MONTHLY",
    'global':   "GLOBAL_QUOTE"
}

CRYPTO_FUNC_LIST = {
    'rating':   "CRYPTO_RATING",
    'daily':    "DIGITAL_CURRENCY_DAILY",
    'weekly':   "DIGITAL_CURRENCY_WEEKLY",
    'monthly':  "DIGITAL_CURRENCY_MONTHLY"
}

INTERVAL_LIST = ["1min", "5min", "15min", "30min", "60min"]

class avapiJsonFileNotFoundError(Exception):
    """ Raised when an avapi_key.json file is not found"""
    pass

class avapiJsonEmptyError(Exception):
    """
    Raised when the 'avapi_key.json file is empty
    or there is no data within the 'avapi_key'
    """
    pass

class invalidFunctionError(Exception):
    """ Raised when an incorrect function argument is provided"""
    pass

class invalidIntervalError(Exception):
    """ Raised when an incorrect interval is provided to the 'intraday' argument"""
    pass

def read_key():
    """Try to read 'avapi_key.json' and return the 'key' field."""
    try:
        if (path.exists(AVAPI_KEY_JSON)):
            with open(AVAPI_KEY_JSON, 'r') as f:
                j = json.load(f)
                if not 'key' in j or len(j['key']) == 0:
                    raise avapiJsonEmptyError
                else:
                    return j['key']

        else:
            raise avapiJsonFileNotFoundError

    except avapiJsonFileNotFoundError:
        print("Error: 'avapi_key.json' file found. Try running 'setkey'.")
    except avapiJsonEmptyError:
        print(
            "Error: 'avapi_key.json' does not contain an API Key. Try running 'setkey'."
        )

def get_pandas_df(url, n):
    if n != 0:
        return pd.read_csv(url).head(n)
    else:
        return pd.read_csv(url)

@click.group(invoke_without_command=True)  # Allow users to call w/o command
@click.pass_context
@click.option('--verbose',
              '-v',
              is_flag=True,
              help="Increase output verbosity level.")
def main(ctx, verbose):
    """
    A command-line interface written in Python for the Alpha Vantage API.

    Author: Mac Fox
    """
    if ctx.invoked_subcommand is None:  # No command was specified
        click.echo("No command specified, try using '--help'")
    ctx.obj['VERBOSE'] = verbose

@main.command('setkey')
@click.option('--k',
              prompt="Alpha Vantage API Key",
              help="Alpha Vantage API Key")
def setkey(k):
    """Save an Alpha Vantage API key to 'avapi_key.json'."""
    avapi_key = {"key": k}
    with open("avapi_key.json", 'w') as f:
        json.dump(avapi_key, f)

@main.command('exrate')
@click.argument('from_currency')
@click.argument('to_currency')
@click.option('--save', is_flag=True, help="Save data to .csv file.")
def exrate(from_currency, to_currency, save):
    """
    Returns the realtime exchange rate for any pair of digital currency
    (e.g., BTC) or physical currency (e.g., USD).
    """
    url = ("https://www.alphavantage.co/query?"
           "function=CURRENCY_EXCHANGE_RATE"
           f"&from_currency={from_currency}"
           f"&to_currency={to_currency}"
           f"&apikey={read_key()}")

    data = json.loads(urlopen(url).read())
    df = pd.json_normalize(data['Realtime Currency Exchange Rate'])
    click.echo(df.to_string(index=False))

    if save:
        filename = f"{date.today()}_exrate_{f}_{t}.csv"
        df.to_csv(filename, index=False)

@main.command('stock')
@click.argument('function')
@click.option('-s', '-symbol', prompt="Symbol", help="TSLA AAPL GME...")
@click.option('-i', '-interval', default="30min", help="1min 5min 15min 30min or 60min. Default = 30min")
@click.option('-n', '-last_n', default=0, help="Only get last_n rows of data")
@click.option('--save', is_flag=True, help="Save data to .csv file.")
def stock(function, s, i, n, save):
    """
    Get a specific time series function for a stock of interest.

    FUNCTION: intraday daily weekly monthly global

    Example: python3 avapi.py stock intraday -s'TSLA' -i'15min'

    Example: python3 avapi.py stock daily -s'TSLA'

    Example: python3 avapi.py stock daily -s'TSLA' -n30
    """
    try:
        if function not in STOCK_FUNC_LIST:  # Make sure function argument is valid
            raise invalidFunctionError
        else:
            if function == "rating":
                url = BASE.format(
                    STOCK_FUNC_LIST["intraday"], s, read_key()) + f"&interval={i}"
                df = get_pandas_df(url, n)
                click.echo(df)

            else:  # Construct query and get data
                url = BASE.format(
                    STOCK_FUNC_LIST[function], s, read_key())
                df = get_pandas_df(url, n)
                click.echo(df)

            if save:
                filename = f"{date.today()}_{function}_{s}_.csv"
                df.to_csv(filename, index=False)

    except invalidFunctionError:
        click.echo(
            "Error: Invalid function argument:'{}'".format(function))
    except invalidIntervalError:
        click.echo("Error: Invalid interval option:'{}'".format(i))

@main.command('crypto')
@click.argument('function')
@click.option('-s', '-symbol', prompt="Symbol", help="TSLA AAPL GME...")
@click.option('-n', '-last_n', default=0, help="Only get last_n rows of data")
@click.option('--save', is_flag=True, help="Save data to .csv file.")
def crypto(function, s, n, save):
    """
    Get a specific time series function for a crypto currency of interest.
    """
    try:
        if function not in CRYPTO_FUNC_LIST:  # Make sure function argument is valid
            raise invalidFunctionError
        if function == 'rating':
            url = ("https://www.alphavantage.co/query?"
                   "function=CRYPTO_RATING"
                   f"&symbol={s}&apikey={read_key()}")
            data = json.loads(urlopen(url).read())
            df = pd.json_normalize(data["Crypto Rating (FCAS)"])
            click.echo(df.to_string(index=False))
        else:
            url = ("https://www.alphavantage.co/query?"
                   f"function={CRYPTO_FUNC_LIST[function]}"
                   f"&symbol={s}&market=USD&apikey={read_key()}"
                   "&datatype=csv")
            df = get_pandas_df(url, n)
            click.echo(df)

        if save:
            filename = f"{date.today()}_{function}_{s}_.csv"
            df.to_csv(filename, index=False)

    except invalidFunctionError:
        click.echo(
            "Error: Invalid function argument for 'avapi get':'{}'".format(function))
    except invalidIntervalError:
        click.echo("Error: Invalid interval option:'{}'".format(i))

if __name__ == "__main__":
    # pylint: disable=unexpected-keyword-arg
    # pylint: disable=no-value-for-parameter
    main(obj={})