''' ========== Constants ========== '''
resizeWidth = 800  # image width for resizing
resizeHeight = 600  # image height for resizing
kSize = 3  # size of kernel for dilation and erosion

cardWidth = 1376  # card width (8.6 x 160)
cardHeight = 864  # card height (5.4 x 160)

CARDTYPE = ['CITIZEN', 'DRIVING']

# location of information in the card (from 1376x864)
citizenCardArea = {
    'id': {'start': (606, 92), 'end': (1085, 154)},
    'name': {'start': (395, 156), 'end': (1350, 256)},
    'dateOfBirth': {'start': (603, 378), 'end': (900, 442)},
    'address': {'start': (137, 553), 'end': (950, 686)}
}

drivingCardArea = {
    'name': {'start': (462, 370), 'end': (1120, 452)},
    'nameEng': {'start': (476, 454), 'end': (1120, 510)},
    'dateOfBirth': {'start': (537, 574), 'end': (809, 621)},
    'id': {'start': (812, 682), 'end': (1165, 727)},
}


"""
Routines for handling articulation of the MSL rover.

Author: Parker Abercrombie <parker.abercrombie@jpl.nasa.gov>
"""

import math
import numpy as np
import pds
import transforms3d
from msl import pppcs

INVALID_ARM_ANGLE = 1e30

instruments = [ 'mahli', 'apxs', 'drill', 'drt', 'portioner', 'scoopbase' ]

tool_transforms = {
    'mahli'     : pppcs.RVRdMAHLI,
    'apxs'      : pppcs.RVRdAPXS,
    'drill'     : pppcs.RVRdDrill,
    'drt'       : pppcs.RVRdDRT,
    'portioner' : pppcs.RVRdPortioner,
    'scoopbase' : pppcs.RVRdScoopBase
}

def mast_position():
    """Indicates mast position in rover navigation frame."""
    return np.array([ 0.80436, 0.55942, -1.90608 ])

class ArmPose(object):

    def __init__(self, pds_header):
        # Some PDS files use non-standard names for the arm group. Try a couple variations.
        possible_groups = [
            "ARM_ARTICULATION_STATE",
            "ARM_ARTICULATION_STATE_PARMS"
        ]

        for group_key in possible_groups:
            if group_key in pds_header:
                arm_group = pds_header[group_key]
                self.init_arm_angles(arm_group)
                break

    def get_instrument_position(self, instrument):
        """Compute the position (in rover nav frame) of an instrument on the arm turret."""
        try:
            func = tool_transforms[instrument]
        except KeyError:
            raise ValueError("Unsupported instrument: " + instrument)

        mat = func(
                self.arm_angle_1,
                self.arm_angle_2,
                self.arm_angle_3,
                self.arm_angle_4,
                self.arm_angle_5)

        vec4 = mat * np.matrix([0, 0, 0, 1]).transpose()
        return np.squeeze(np.asarray(vec4[0:3])) # Discard w coord

    def get_instrument_pointing(self, instrument):
        """Compute the pointing direction (in rover nav frame) of an instrument on the arm turret."""
        try:
            func = tool_transforms[instrument]
        except KeyError:
            raise ValueError("Unsupported instrument: " + instrument)

        mat = func(
                self.arm_angle_1,
                self.arm_angle_2,
                self.arm_angle_3,
                self.arm_angle_4,
                self.arm_angle_5)

        # Z-axis is pointing axis. Transform the Z direction in the
        # instrument coordinate system to rover nav frame. See
        # Figure 3 on Page 14 of the PPCS document.

        # (Note the PPPCS doc includes a note on page 10 that states that the
        # pointing axis changed to X in Dec 2008, and that updated transform
        # matrices would be included in a later revision of the document. However,
        # I have not been able to find this updated document. The use of Z as the
        # pointing axis is consistent with the 2009-01-09 version of the PPPCS doc.)
        vec4 = mat * np.matrix([0, 0, 1, 0]).transpose()
        direction = np.squeeze(np.asarray(vec4[0:3])) # Discard w coord
        return transforms3d.utils.normalized_vector(direction) # Normalize

    def get_turret_position(self):
        mat = pppcs.RVRdARM6(
            self.arm_angle_1,
            self.arm_angle_2,
            self.arm_angle_3,
            self.arm_angle_4,
            self.arm_angle_5)

        return mat * np.matrix([0, 0, 0, 1]).transpose()

    ##############################
    ## PDS image parsing
    ##############################

    def init_arm_angles(self, arm_group):
        arm_angles = self.parse_angles(arm_group)

        self.arm_angle_1 = self.get_arm_angle(arm_angles, ["JOINT 1 AZIMUTH", "JOINT 1 SHOULDER AZIMUTH"])
        self.arm_angle_2 = self.get_arm_angle(arm_angles, ["JOINT 2 ELEVATION", "JOINT 2 SHOULDER ELEVATION"])
        self.arm_angle_3 = self.get_arm_angle(arm_angles, ["JOINT 3 ELBOW"])
        self.arm_angle_4 = self.get_arm_angle(arm_angles, ["JOINT 4 WRIST"])
        self.arm_angle_5 = self.get_arm_angle(arm_angles, ["JOINT 5 TURRET"])

    def parse_angles(self, arm_group):

        angle_strings = arm_group["ARTICULATION_DEVICE_ANGLE"]
        angles = [self.parse_angle(ss) for ss in angle_strings]
        angle_names = arm_group["ARTICULATION_DEVICE_ANGLE_NAME"]

        if len(angles) != len(angle_names):
            raise ValueError("Malformed image header. Length of articulation angle list should match length of angle name list")

        angle_dict = {}
        for i, name in enumerate(angle_names):
            name = name.strip()
            angle_dict[name] = angles[i]
        return angle_dict

    def get_arm_angle(self, arm_group, possible_joint_names):
        """Read an arm angle from a parsed dictionary of angles.

        This method first attempts to read the resolver angle for the given joint.
        If the resolver angle is missing or invalid (1e30), then the method reads
        the corresponding encoder angle.

        In some cases, images contain an incorrect resolver angle that is very different
        than the encoder angle. This method detects cases in which the resolver angle is
        more than 10 degrees different than the encoder angle. In these cases, the encoder
        angle is returned.

        Parameters:
          angleDict: Dictionary of named angles
          possible_joint_names: List of names of the joint for which to retrieve angle. Some
               APXS files have been known to use non-standard names for some angles
               (e.g. "JOINT 1 AZIMUTH", "JOINT 1 SHOULDER AZIMUTH"). The first name that matches an
               angle in the file header will be returned.

        Returns:
           Joint angle in radians.
        """

        for joint in possible_joint_names:
            resolver_key = joint + "-RESOLVER"
            encoder_key = joint + "-ENCODER"

            # Parse out resolver and encoder angles, and then decide which to use
            resolver_angle = arm_group[resolver_key] if resolver_key in arm_group else None
            encoder_angle = arm_group[encoder_key] if encoder_key in arm_group else None
            raw_angle = arm_group[joint] if joint in arm_group else None

            # In the normal case we have both resolver and encoder angles
            if resolver_angle is not None and encoder_angle is not None:
                return self.choose_resolver_or_encoder_angle(resolver_angle, encoder_angle)
            elif resolver_angle is not None:
                # Only have the resolver angle. Return it as long as it is valid.
                return resolver_angle if self.is_valid_arm_angle(resolver_angle) else None
            elif encoder_angle is not None:
                return encoder_angle if self.is_valid_arm_angle(encoder_angle) else None
            elif raw_angle is not None:
                return raw_angle if self.is_valid_arm_angle(raw_angle) else None

        # Unable to find any of the possible angle names.
        raise KeyError("Unable to find angle for joint " + joint)

    def choose_resolver_or_encoder_angle(self, resolver_angle, encoder_angle, resolver_tolerance_degrees=10):
        """Return either the resolver or encoder angle for a joint, preferring the resolver angle.

        In normal cases the encoder and resolver angles are similar. In some abnormal cases resolver
        angles that are very wrong. Detect cases in which the two angles are very different, and
        return the encoder angle in those cases (if it is valid).

        Parameters:
           resolverToleranceDegrees: Use resolver angle is resolver and encoder are within
                this tolerance. If angles are not within this tolerance, assume that resolver
                is incorrect and return encoder
        """

        if self.is_valid_arm_angle(resolver_angle):
            angles_very_different = math.fabs(resolver_angle - encoder_angle) > math.degrees(resolver_tolerance_degrees)
            if angles_very_different and is_valid_arm_angle(encoder_angle):
                print("Resolver and encoder angles more than " + resolver_tolerance_degrees +
                 " degrees different. Using encoder angle. (" + filename + ")")
                return encoder_angle
            return resolver_angle

        return encoder_angle

    def is_valid_arm_angle(self, angle, epsilon=1e-10):
        """Determine if an arm joint angle represents a valid measurement.

        This function compares an angle to the Invalid Angle value specified in PPPS Vol 6.

        Parameters:
          angle: Angle to test
          epsilon: Epsilon value for floating point comparison. Consider angle invalid if within this number
                   of radians of the invalid angle value.
        """
        return math.fabs(angle - INVALID_ARM_ANGLE) > epsilon

    def parse_angle(self, angle_str):
        """Parse an angle from a string in the form "##.#### <rad>".

        Parameters:
           angle_str: String to parse

        Return:
           Angle in radians.
        """

        parts = angle_str.strip().split(' ')

        # Invalid angles don't always have <rad> on them.  If this angle is invalid
        # don't assert that we need <rad> to be specified
        if len(parts) == 1:
            d = float(parts[0])
            if not is_valid_arm_angle(d):
                return d

        if len(parts) != 2:
            raise ValueError("Unexpected angle format: " + angle_str + ". Expecting '##.### <rad>'")
        if parts[1] != "<rad>":
            raise NotImplementedError("Parsing non-radian angles is not supported")

        return float(parts[0])


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

import os
import sys
from src.extractor import Extractor

def main():
    if len(sys.argv) == 2:
        jar_path = sys.argv[1]
    else:
        print ('[ERROR] jar path need input!')
        return
    extractor = Extractor(jar_path)
    extractor.start()

if __name__ == '__main__':
    main()


import json
from typing import Dict

from core.constants import REDIRECT_URLS
from .amount_models import AmountModel
from .buyer_models import BuyerModel

class PaymentModel:
    token: str
    amount: AmountModel
    buyer: BuyerModel
    redirect_urls: Dict

    def __init__(
        self,
        *,
        token: str,
        buyer: BuyerModel,
        amount: AmountModel,
        urls: Dict = REDIRECT_URLS,
    ):
        self.token = token
        self.amount = amount
        self.buyer = buyer
        self.redirect_urls = urls

    def as_dict(self):
        data = {
            "paymentTokenId": self.token,
            "totalAmount": self.amount.as_dict(),
            "buyer": self.buyer.as_dict(),
            "redirectUrl": self.redirect_urls,
        }

        return data

    def serialize(self):
        return json.dumps(self.as_dict())


from __future__ import annotations

import logging

from typing import TYPE_CHECKING

from airflow.decorators import task
from airflow.operators.email import EmailOperator

from airflow_supporter.service import check_off_dag_op

if TYPE_CHECKING:
    from airflow import DAG

    from airflow_supporter.model import CheckOffDagVariable

logger = logging.getLogger(__name__)

def create_check_off_dag(codv: CheckOffDagVariable, dag: DAG) -> None:
    """
    This will create DAG named 'check_off_dag'

    Returns:
        None
    """

    with dag:
        @task
        def get_off_dag_list_op(exclude_dag_list: list[str]) -> list[str]:
            return check_off_dag_op.get_off_dag_list_func(exclude_dag_list)

        @task
        def turn_on_dag_op(dag_list: list[str]) -> None:
            check_off_dag_op.turn_of_dag_func(dag_list)

        off_dag_list_op = get_off_dag_list_op(codv.exclude_dag_list)

        if codv.email:
            EmailOperator(
                task_id="alert_off_dag_list_op",
                to=codv.email,
                subject="alert check_off_dag",
                html_content=",".join(off_dag_list_op),
            )

        turn_on_dag_op(off_dag_list_op)


# coding: utf-8

import uuid
import datetime
from os import path
from PIL import Image
from StringIO import StringIO

from django.core.files.storage import default_storage

from autowb.db import Model

class ImageFileRepo(Model):
    fields = [
        '_id',
        'name',  # full_name
        'size',  # e.g. 140x140
        'meta',
        'original',
        'versions',
        'created',
    ]

    @classmethod
    def create(cls, **kw):
        data = kw.copy()
        data.update({'created': datetime.datetime.now()})
        model = ImageFile(data)
        model.save()
        return model

    @classmethod
    def get_by_name(cls, name):
        return cls.get({'name': name})

    def url(self):
        return default_storage.url(self.name)

def _random_image_name(modifier=None, ext=None):
    modifier = '_' + modifier if modifier else ''
    if not ext:
        ext = 'jpg'

    return '%s%s.%s' % (uuid.uuid4().hex, modifier, ext)

class ImageDataBase:
    def save_with_random_name(self, path, modifier=None):
        ext = self.format if hasattr(self, 'format') else 'jpg'
        image_path = path + _random_image_name(modifier=modifier, ext=ext)
        return self.save(image_path)

class ImageData(ImageDataBase):
    def __init__(self, rawdata):
        self.rawdata = rawdata
        image = Image.open(StringIO(rawdata.read()))
        self.image = image
        self.width, self.height = image.size
        # if original is empty, this file is the original file itself
        self.original = ''
        self.format = image.format

    def save(self, path):
        self.path = default_storage.save(path, self.rawdata)

        model = ImageFileRepo({
            'name': path,
            'size': self.size_str(),
            'meta': '',
            'original': self.original,
            'versions': [],
            'created': datetime.datetime.now()
        })
        model.save()
        return self.path

    def size_str(self):
        return "%sx%s" % (self.width, self.height)

    @classmethod
    def load_from_path(cls, path):
        image = Image.open(path)
        return cls(image)

class ImageFile:
    def __init__(self, fullname):
        self.fullname = fullname
        self.name, self.ext = path.splitext(fullname)

    def name_of_width(self, width, square=False):
        square = 's' if square else ''
        return '%s_w_%s%s%s' % (self.name, square, width, self.ext)


# --------------------------------------------------------
# Pytorch Yolov2
# Licensed under The MIT License [see LICENSE for details]
# Written by Jingru Tan
# --------------------------------------------------------

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import torch.nn as nn
import numpy as np
from torch.autograd import Variable
import torch
import torch.nn.functional as F
from util.network import WeightLoader

def conv_bn_leaky(in_channels, out_channels, kernel_size, return_module=False):
    padding = int((kernel_size - 1) / 2)
    layers = [nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size,
                        stride=1, padding=padding, bias=False),
            nn.BatchNorm2d(out_channels),
            nn.LeakyReLU(0.1, inplace=True)]
    # layers = [nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size,
    #                     stride=1, padding=padding, bias=False),
    #           nn.LeakyReLU(0.1, inplace=True)]
    if return_module:
        return nn.Sequential(*layers)
    else:
        return layers

class de_Darknet19(nn.Module):

    cfg = {
        #'layer0': [256, 512, 256, 512, 256, 'M'],
        #'layer1': [128, 256, 128, 'M'],
        # 'layer1': ['M'],
        # 'layer2': [64, 128, 64, 'M'],
        # 'layer3': [32, 'M'],
        # 'layer4': [3]

        'layer2': ['M', 64, 128, 64],
        'layer3': ['M', 32],
        'layer4': ['M', 3]
    }

    def __init__(self):
        super(de_Darknet19, self).__init__()
        self.in_channels = 128

        #self.layer0 = self._make_layers(self.cfg['layer0'])
        #self.layer1 = self._make_layers(self.cfg['layer1'])
        self.layer2 = self._make_layers(self.cfg['layer2'])
        self.layer3 = self._make_layers(self.cfg['layer3'])
        self.layer4 = self._make_layers(self.cfg['layer4'])

    def forward(self, x):
        #x = self.layer0(x)
        #x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)
        return x

    def _make_layers(self, layer_cfg):
        layers = []

        # set the kernel size of the first conv block = 3
        kernel_size = 3
        for v in layer_cfg:
            if v == 'M':
                #layers += [nn.UpsamplingNearest2d(scale_factor=1)]
                #layers += [nn.Upsample(size=None, scale_factor=2, mode='bilinear', align_corners=True)]
                layers += [nn.ConvTranspose2d(in_channels=self.in_channels, out_channels=self.in_channels,  kernel_size=4, stride=2, padding=1, output_padding=0, bias= False)]
                #layers += [nn.Upsample(size=None, scale_factor=2, mode='bilinear', align_corners=True)]
                #layers += [nn.PixelShuffle(1)]
            elif v == 'S':
                layers += [nn.Upsample(size=None, scale_factor=2, mode='bilinear', align_corners=True)]

            else:
                layers += conv_bn_leaky(self.in_channels, v, kernel_size)
                kernel_size = 1 if kernel_size == 3 else 3
                self.in_channels = v
        return nn.Sequential(*layers)

    # very ugly code !! need to reconstruct
    def load_weights(self, weights_file):
        weights_loader = WeightLoader()
        weights_loader.load(self, weights_file)

#
# if __name__ == '__main__':
#     im = np.random.randn(1, 3, 224, 224)
#     im_variable = Variable(torch.from_numpy(im)).float()
#     model = de_Darknet19()
#     out = model(im_variable)
#     print(out.size())
#     print(model)


"""
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number.
For example, the sum of the proper divisors of 28 would be
1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.

A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum
exceeds n.

As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of
two abundant numbers is 24. By mathematical analysis,
it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers.
However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number
that cannot be expressed as the sum of two abundant numbers is less than this limit.

Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
"""
import math
import time

def divisor_generator(n):
    large_divisors = []
    for i in range(1, int(math.sqrt(n) + 1)):
        if n % i == 0:
            yield i
            if i * i != n and i != 1:
                large_divisors.append(int(n / i))
    for divisor in reversed(large_divisors):
        yield divisor

def calculate_divisor_sum(n):
    return sum(divisor_generator(n))

def is_abundant(n):
    return calculate_divisor_sum(n) > n

if __name__ == '__main__':

    start = time.time()

    abundants = set()  # note sets have a smaller memory complexity than lists
    limit, total = 28123, 0

    for num in range(1, limit + 1):
        if is_abundant(num):
            abundants.add(num)
        if not any((num - a in abundants) for a in abundants):
            total += num

    print("answer is {}, found in time {}".format(total, time.time() - start))


from transformers import AutoTokenizer, AutoModelForQuestionAnswering, RobertaForQuestionAnswering, RobertaTokenizerFast
import torch
from reader.reader import Reader
import math

class PtReader(Reader):

    def __init__(self, model_path):
        self.tokenizer = AutoTokenizer.from_pretrained(model_path)
        self.model = AutoModelForQuestionAnswering.from_pretrained(model_path)

    def predict(self, question, context, best_n=3):

        inputs = self.tokenizer(
            question, context, add_special_tokens=True, return_tensors="pt")
        input_ids = inputs["input_ids"].tolist()[0]

        text_tokens = self.tokenizer.convert_ids_to_tokens(input_ids)
        answer_start_scores, answer_end_scores = self.model(**inputs)

        answer_start = torch.argmax(
            answer_start_scores
        )
        answer_end = torch.argmax(answer_end_scores) + 1
        answer = self.tokenizer.convert_tokens_to_string(
            self.tokenizer.convert_ids_to_tokens(input_ids[answer_start:answer_end]))

        probabilities = []

        for start_score in answer_start_scores.cpu().detach().numpy():
            probabilities.append(self._compute_softmax(start_score))

        probability = (probabilities[0][answer_start] +
                       probabilities[0][answer_end-1])/2

        print(f'PT: {answer}')

        return answer, probability

    @staticmethod
    def _compute_softmax(scores):
        max_score = None
        for score in scores:
            if max_score is None or score > max_score:
                max_score = score

        exp_scores = []
        total_sum = 0.0
        for score in scores:
            x = math.exp(score - max_score)
            exp_scores.append(x)
            total_sum += x

        probs = []
        for score in exp_scores:
            probs.append(score / total_sum)
        return probs


class Solution191:
    def hammingWeight(self, n: int) -> int:
        if n == 1:
            return 1
        if n == 0:
            return 0
        # in Python: / is true division (floating point); // is integer division (floor)
        return self.hammingWeight(n//2) + (1 if n%2 == 1 else 0)

    # bit manipulation => how many 1s? use magic number
    def hammingWeight2(self, n: int) -> int:
        weight = 0
        while n > 0:
            n = n & (n-1)
            weight += 1
        return weight

class Solution198:
    def rob(self, nums: List[int]) -> int:
        total = [nums[0]]
        max_val = total[0]
        for i in range(1, len(nums)):
            picked_val = nums[i] + total[i-2] if i-2 >= 0 else nums[i]
            val = max(picked_val, total[i-1])
            total.append(val)
            max_val = max(max_val, val)
        return total[-1]


import cards
def List(R):
    player1_list=[]
    player2_list=[]
    for i in range( 5 ):
        player1_list.append(R.deal())
        player2_list.append(R.deal())
    return player1_list,player2_list

def Rules(player1_card,player2_card):
    if player1_card.rank() < player2_card.rank():
        if player1_card.value()!='player2':
            print ("Player 2 wins battle.")
            return 'player2'
        else:
            print ("Player 1 wins battle.")
            return 'player1'
    elif player1_card.rank() > player2_card.rank():
        if player2_card.value()!='player1':
            print ("Player 1 wins battle.")
            return 'player1'
        else:
            print("Player 2 wins battle.")
            return 'player2'
    else:
        print("Tie")
        return 'tie'

def Display(player1_list, player2_list):
    print ("Hand1: {}".format(player1_list))
    print ("Hand2: {}".format(player2_list))

def Display2(player1_list, player2_list):
    print ("hand1: {}".format(player1_list))
    print ("hand2: {}".format(player2_list))

print("Starting Hands")
R = cards.Deck()
player1_list,player2_list=List(R)
Display(player1_list, player2_list)
while True:
    player1_card = player1_list.pop( 0 )
    player2_card = player2_list.pop( 0 )
    print("Battle was 1: {}, 2: {}.".format(player1_card,player2_card))
    Winner=Rules(player1_card,player2_card)
    if Winner=='tie':
        player1_list.append(player1_card)
        player2_list.append(player2_card)
    elif Winner=='player1':
        player1_list.append(player1_card)
        player1_list.append(player2_card)
    elif Winner=='player2':
        player2_list.append(player2_card)
        player2_list.append(player1_card)
    Display2(player1_list, player2_list)
    if len(player1_list)==0:
        break
    if len(player2_list)==0:
        break
    c=input("Keep Going: (Nn) to stop:")
    if c.lower()=='n':
        break;

if len(player1_list)> len(player2_list):
    print ("Player 1 wins!!!")
elif len(player2_list)>len(player1_list):
    print ("Player 2 wins!!!")
else:
    print ("Game tie" )


"""
@author: jpzxshi
"""
import numpy as np
import matplotlib.pyplot as plt
import learner as ln

def plot(data, net):
    x = data.X_test_np
    f_true = data.y_test_np
    f_pred = net.predict(data.X_test, returnnp=True)

    plt.plot(x, f_true, color='b', label='Ground truth', zorder=0)
    plt.plot(x, f_pred, color='r', label='Prediction', zorder=1)
    plt.scatter(data.X_train_np, data.y_train_np, color='b', label='Learned data', zorder=2)
    plt.title(r'$\sin(x)$', fontsize=20)
    plt.legend()
    plt.savefig('regression.pdf')

def main():
    device = 'cpu' # 'cpu' or 'gpu'
    # FNN
    size = [1, 30, 30, 1]
    activation = 'relu'
    # training
    lr = 0.01
    iterations = 20000
    print_every = 1000

    X_train = (2 * np.pi * np.random.rand(30))[:, None]
    y_train = np.sin(X_train)
    X_test = np.linspace(0, 2 * np.pi, num=100)[:, None]
    y_test = np.sin(X_test)

    data = ln.Data(X_train=X_train, y_train=y_train, X_test=X_test, y_test=y_test)
    net = ln.nn.FNN(size, activation)
    args = {
        'data': data,
        'net': net,
        'criterion': 'MSE',
        'optimizer': 'adam',
        'lr': lr,
        'iterations': iterations,
        'batch_size': None,
        'print_every': print_every,
        'save': True,
        'callback': None,
        'dtype': 'float',
        'device': device
    }

    ln.Brain.Init(**args)
    ln.Brain.Run()
    ln.Brain.Restore()
    ln.Brain.Output()

    plot(data, ln.Brain.Best_model())

if __name__ == '__main__':
    main()


# -*- coding: UTF-8 -*-
import os
import winsound
import time
import serial
import serial.tools.list_ports
import shutil
import openpyxl

'''
串口端打印ASR
脚本控制本地唤醒词音频播放
——判断是否唤醒成功
——唤醒成功，则播放音频语料（如果没有唤醒成功，则再次播放唤醒音频，直到唤醒成功为止）
——读取串口端打印的ASR结果
——将此ASR结果和期望值比较
——完全一样，pass。不一样，fail。
需要注意的是：
1.要统计播放唤醒音频测试；
2.需要统计唤醒成功次数；
3.需要打印唤醒成功率；
4.需要打印识别成功率。

作者：
创建时间：
'''

# 全局变量-文件配置
wakeup_path = "D:/aicolud_file/001M26_01_40_0001.wav"   # #唤醒文件：你好小美的音频文件
audio_root_path =  "E:/audiofile/离在线音频/（非离线）纯在线本机&场景指令词表/"  #需要执行的音频文件路径
excel_path = 'E:/audiofile/离在线音频/（非离线）纯在线本机&场景指令词表.xlsx'   # 映射关系表，命令词
save_excelpath="E:/audiofile/离在线音频/测试结果.xlsx"   # 测试结果保存的文件路径
file_copy_rpath="E:/audiofile/命令的文件/"   # 拷贝路径.

# 查询可用串口
def query():
    plist = list(serial.tools.list_ports.comports())
    if len(plist) <= 0:
        print("The Serial port can't find!")
        return None
    else:
        #plist_0 =list(plist[0])
        #serialName = plist_0[0]

        #串口地址配置
        serialName="COM3"
        serialFd = serial.Serial(serialName, 9600, timeout=60)
        #serialFd = serial.Serial(serialName,921600,timeout = 60)
        print("check which port was really used > ",serialFd.name)

    return serialFd

# 打开串口
def open_interface(serialFd):
    if serialFd.isOpen():
        print("Serial port open success")
    else:
        print("Serial port open failed")

# 定义识别率 打断成功率 唤醒信息
def clear_data():
    # 识别信息
    global  cntCmdTotal,cntCmdSucc,cntCmdFail,ratioCmd
    cntCmdTotal = 0 # 案例总数
    cntCmdSucc = 0  # 识别成功次数
    cntCmdFail = 0  # 识别失败次数
    ratioCmd = 0.0  # 识别率

    # 唤醒信息
    global totalWk, cntWkSucc, cntWkFail,ratioWk
    totalWk = 0    # 总唤醒次数
    cntWkSucc = 0  # 唤醒成功次数
    cntWkFail = 0  # 唤醒失败次数
    ratioWk = 0.0  # 唤醒成功率

def returndictinfobyexcel(excel_path):
    workbook = openpyxl.load_workbook(excel_path)
    allname = workbook.get_sheet_names()
    dictinfo={}
    for one_sheet in allname:
        table = workbook.get_sheet_by_name(one_sheet)
        # 获取总行数
        nrows = table.max_row + 1
        for i in range(1, nrows):
            wav_value = table.cell(i,1).value  # wav文件值
            result_value = table.cell(i, 2).value  # 预期结果值
            dictinfo[wav_value]=result_value

    return  dictinfo

 # 拷贝某一个文件
def start_copy_file(s_path,taget_path):
     if os.path.exists(s_path) == True:
         root_dirpath = os.path.dirname(taget_path)
         print(root_dirpath)
         if os.path.exists(root_dirpath)==False:
             os.makedirs(root_dirpath)
         shutil.copyfile(s_path, taget_path)

# 获取excel，计算识别率 打断成功率 唤醒信息
def start_play_audio(serialFd,dictinfo):
    new_wb=openpyxl.Workbook();
    new_ws = new_wb.create_sheet(title="命中率")
    new_ws.append(["在线语料",'命中本地ASR','命中置信度','命中的录音文件名称'])
    list_dir=os.listdir(audio_root_path)
    for one_dir in list_dir:
        childpath=audio_root_path+one_dir
        list_child_dir=os.listdir(childpath)
        hitcounts=0  # 命中次数
        miss_hitcounts=0  # 未命中次数
        for one_file in list_child_dir:
            child_filepath=childpath+"/"+one_file
            if (os.path.exists(child_filepath) == False):
                print("文件不存在")
                continue

            issucess = wakeup_File(serialFd)  # 唤醒小美
            if issucess:
                # step 2-2, 播放命令词，读取串口，判断是否正确识别
                time.sleep(1)  # 间隔1秒.
                winsound.PlaySound(child_filepath, winsound.SND_FILENAME)
                ars_result = recvCmd(serialFd)  # 接收asr返回结果
                print("asr返回结果信息:" + ars_result)
                asrinfo_value=""  # asr的信息
                conf_value=""  # 置信度信息
                if ars_result!=""  and  ars_result.find("asr")!=-1:
                    hitcounts=hitcounts+1
                    asr_list=ars_result.split(":")
                    asrinfo_value=asr_list[1].replace("\\conf","").replace("]","").strip()
                    conf_value=asr_list[2].replace("]","").strip()
                    print(asrinfo_value,conf_value)

                    # 拷贝文件
                    #copy_tagetpath=file_copy_rpath+one_dir+"/"+one_file
                    #start_copy_file(child_filepath,copy_tagetpath)

                else:
                    miss_hitcounts=miss_hitcounts+1

                if dictinfo[one_file]!=None:
                    except_info=str(dictinfo[one_file]).strip()
                    print(except_info)

                new_ws.append([except_info,asrinfo_value,conf_value,child_filepath])

        totalcount=len(list_child_dir)
        ratioWk = (hitcounts / totalcount) * 100
        rate_value = "{:.2f}%".format(ratioWk)
        str_totalcount="总次数:"+str(totalcount)
        str_hitcounts="命中次数:"+ str(hitcounts)
        str_miss_hitcounts="未命中次数:"+str(miss_hitcounts)
        str_rate="命中率:" + str(rate_value)
        print(str_totalcount)
        print(str_hitcounts)
        print(str_miss_hitcounts)
        print(str_rate)

        print("命中率:" , rate_value)
        new_ws.append([str_totalcount, str_hitcounts, str_miss_hitcounts,str_rate])
        new_wb.save(save_excelpath)

def recvCmd(serial):
    global cntCmdSucc,cntCmdFail,cntCmdTotal
    i = 0
    res = 'ASR结果 '
    # 10 秒内收到回应
    cmd_newData=""
    try:
        while i < 20:
            count = serial.inWaiting()
            print("count: " + str(count))
            if count > 0:
                time.sleep(0.1)
                buff = serial.read_all()
                print("buff: " + str(buff))
                if isinstance(buff, bytes):
                    temp_data = buff.decode(encoding='utf-8', errors='ignore')
                    cmd_newData = cmd_newData + temp_data
                    break
            else:
                time.sleep(0.2)
                i += 1
    except Exception as e:
           #fileObject.write("获取asr结果异常："+str(e))
           print("获取asr结果异常："+str(e))

    if len(cmd_newData) <= 1:
        cmd_newData = ''

    #print("ASR结果：" + cmd_newData)
    cmd_newData=cmd_newData.replace(" ","")
    serial.flushInput()
    return cmd_newData

# 唤醒小美,读取音频文件
def  wakeup_File(serialFd):
    iswake = False
    istts=False
    winsound.PlaySound(wakeup_path, winsound.SND_FILENAME)  # 播放唤醒词
    is_wakeup,data= recvWakeup(serialFd)    # 接收是否唤醒成功
    #是否唤醒
    print("是否唤醒: " + str(is_wakeup))
    if is_wakeup == True:
         iswake=True
    else:
        iswake=wakeup_File(serialFd)
    return iswake

#唤醒小美,获取唤醒
def recvWakeup(serial):
    try:
        txt = 'xiaomei'
        i = 0
        new_data = ""
        while(i < 50):
            count = serial.inWaiting()
            print("count: " + str(count))
            if count > 0:
                buff = serial.read(count)
                print(type(buff))
                print("buff: " + str(buff))
                if isinstance(buff, bytes):
                    temp_data=buff.decode(encoding='utf-8',errors='ignore')
                    new_data =new_data+ temp_data
                    print("测试数据："+new_data)
                break
            else:
                time.sleep(0.1)
                i += 1

        ret = new_data.find(txt)
        serial.flushInput()
        if ret != -1:
            print('……唤醒成功……')
            return True,new_data
        else:
            print('……唤醒失败……')
            return False,new_data
    except Exception as e:
        #fileObject.write("获取唤醒语句异常: " + str(e))
        print("异常信息如下: "+str(e))
        return False,""

if __name__=="__main__":
    serialFd=query()   # 查询是否有插入串口
    if serialFd!=None:
        open_interface(serialFd)  # 打开串口
        if (os.path.exists(wakeup_path)==False):
            print("唤醒的音频文件不存在: " + wakeup_path)
        else:
            #读取excel文件，并存储到dict中.
            dict_infovalue=returndictinfobyexcel(excel_path)
            start_play_audio(serialFd,dict_infovalue)


import esdl
from influxdb import InfluxDBClient
from pyecore.ecore import EDate

from tno.essim_adapter.model.essim import ESSIM

if __name__ == "__main__":
    # <asset xsi:type="esdl:HeatingDemand" id="6992d3af-f3b7-4c91-8d81-67d861df8726" name="HeatingDemand_6992">
    #   <geometry xsi:type="esdl:Point" CRS="WGS84" lat="53.45044250555688" lon="5.753059387207032"/>
    #   <port xsi:type="esdl:InPort" id="2d09f9f3-3567-470f-a229-c654f41cadce" connectedTo="ffa0d830-11de-45c6-8f54-685ae2aec22a 16c06616-b849-4624-8ab4-121657bb1c66" carrier="7c6439be-42df-4f09-8263-a3f1e49ee0ce" name="In">
    #     <profile xsi:type="esdl:InfluxDBProfile" database="energy_profiles" startDate="2015-01-01T00:00:00.000000+0100" host="http://geis.hesi.energy" field="G1A" filters="" multiplier="50.0" endDate="2016-01-01T00:00:00.000000+0100" id="78eba100-6031-4c08-bad1-de4de1c4a086" port="8086" measurement="nedu_aardgas_2015-2018">
    #       <profileQuantityAndUnit xsi:type="esdl:QuantityAndUnitType" id="eb07bccb-203f-407e-af98-e687656a221d" description="Energy in GJ" multiplier="GIGA" unit="JOULE" physicalQuantity="ENERGY"/>
    #     </profile>
    #   </port>
    # </asset>

    profile = esdl.InfluxDBProfile(
        id="78eba100-6031-4c08-bad1-de4de1c4a086",
        host="http://geis.hesi.energy",
        port=8086,
        database="energy_profiles",
        measurement="nedu_aardgas_2015-2018",
        field="G1A",
        startDate=EDate.from_string("2016-01-01T00:00:00.000000+0100"),
        endDate=EDate.from_string("2017-01-01T00:00:00.000000+0100"),
        multiplier=50.0
    )

    profile.profileQuantityAndUnit = esdl.QuantityAndUnitType(
        id="123",
        physicalQuantity=esdl.PhysicalQuantityEnum.COST,
        unit=esdl.UnitEnum.EURO,
        perMultiplier=esdl.MultiplierEnum.MEGA,
        perUnit=esdl.UnitEnum.WATTHOUR,
        description="COST in EUR/MWh"
    )

    mdl = ESSIM()

    profile_info = mdl.query_esdl_influxdb_profile(profile)
    print(profile_info)

    profile_info.influxdb_info.database = "test"
    mdl.save_profile_to_influxdb(profile_info)


import json

from django.http import HttpResponse
from django.conf import settings

def render_json(data, code=200):
    """
    自定义render函数, code默认值为200, 返回正常
    """
    result = {
        'data': data,
        'code': code,
    }
    # 开发为了显示清晰使用
    if settings.DEBUG:
        json_str = json.dumps(
            result,
            indent=4,  # 缩进
            # sepatarors=[',', ':'],  # 分隔符
            ensure_ascii=False,  # 编码方式
            sort_keys=True,  # 排序
        )
    else:
        # 实际项目中使用
        json_str = json.dumps(result,
                              # sepatarors=[',', ':'],
                              ensure_ascii=False)
    return HttpResponse(json_str)


import pygame
import random

# Constants
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 400
CELL_SIZE = 100
PLAYER_SPEED = CELL_SIZE
FRUIT_DROP_SPEED = CELL_SIZE

# Colors
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)

# Initialize pygame
pygame.init()

# Load images
player_image = pygame.image.load("C:/Users/megha/A Thesis/Flappy Bird/Game_Of_catch/basket.png")  # Replace with your image path
player_image = pygame.transform.scale(player_image, (100, 90))

fruit_image = pygame.image.load("C:/Users/megha/A Thesis/Flappy Bird/Game_Of_catch/fruit.png")     # Replace with your image path
fruit_image = pygame.transform.scale(fruit_image, (80, 80))

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Catch the Falling Fruit')
BLACK = (0, 0, 0)

def draw_grid():
    for x in range(0, SCREEN_WIDTH, CELL_SIZE):
        pygame.draw.line(screen, BLACK, (x, 0), (x, SCREEN_HEIGHT))
    for y in range(0, SCREEN_HEIGHT, CELL_SIZE):
        pygame.draw.line(screen, BLACK, (0, y), (SCREEN_WIDTH, y))

class Player:
    def __init__(self):
        self.x = 0
        self.y = SCREEN_HEIGHT - CELL_SIZE

    def move(self, direction):
        new_x = self.x + direction * CELL_SIZE
        if 0 <= new_x < SCREEN_WIDTH:
            self.x = new_x

    def draw(self):
        screen.blit(player_image, (self.x, self.y))

class Fruit:
    def __init__(self, x):
        self.x = x
        self.y = 0

    def move(self):
        self.y += FRUIT_DROP_SPEED/FPS

    def draw(self):
        screen.blit(fruit_image, (self.x, self.y))

    def is_caught(self, player):
        return self.y == player.y and self.x == player.x

    def is_missed(self):
        return self.y > SCREEN_HEIGHT

    def remove(self):
        screen.blit(fruit_image, (self.x, self.y))

player = Player()
fruits = []
score = 0

FPS = 30
fruit_drop_interval = FPS  # 30 frames, which means the fruit will drop once every second
fruit_drop_counter = 0

FRUIT_DROP_SPEED = CELL_SIZE

running = True
while running:
    screen.fill(WHITE)
    draw_grid()
    fruit_drop_counter += 1

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player.move(-1)
                score -= 0.1
            elif event.key == pygame.K_RIGHT:
                player.move(1)
                score -= 0.1

    # Randomly spawn a fruit
    if random.random() < 0.02:  # 2% chance per frame to spawn a fruit
        x = random.choice([i * CELL_SIZE for i in range(4)])
        fruits.append(Fruit(x))

    # Check if it's time to move the fruits
    if fruit_drop_counter >= fruit_drop_interval:
        for fruit in fruits:
            fruit.move()
        fruit_drop_counter = 0

    # Move and draw fruits
    for fruit in fruits[:]:
        fruit.move()
        fruit.draw()

        if fruit.is_caught(player):
            score += 10
            fruit.remove(fruit)
        elif fruit.is_missed():
            score -= 10
            fruit.remove(fruit)

    player.draw()

    # Show score
    score_display = pygame.font.Font(None, 36).render(str(score), True, GREEN)
    screen.blit(score_display, (10, 10))

    pygame.display.flip()
    pygame.time.Clock().tick(FPS)

pygame.quit()


import json
import os
from dataclasses import dataclass

# STORE_PATH = os.path.join(os.path.dirname(__file__), "store.json")
# Find path to Workflow Data folder
# https://www.alfredapp.com/help/workflows/advanced/variables/
STORE_PATH = os.path.join(os.environ["alfred_workflow_data"], "store.json")

@dataclass
class StoreItem:
    """
    Store item. Includes keyword used to query the URL and the URL itself.
    """

    keyword: str
    url: str

def load_store() -> list[StoreItem]:
    """
    Load store from file.

    Returns:
        list[StoreItem]: Store.
    """
    # Check if directory exists
    if not os.path.exists(os.path.dirname(STORE_PATH)):
        os.makedirs(os.path.dirname(STORE_PATH))

    # Check if store exists
    if not os.path.exists(STORE_PATH):
        return []

    with open(STORE_PATH, "r") as f:
        return [StoreItem(**item) for item in json.load(f)]

def save_store_item(item: StoreItem):
    """
    Save single store to file.

    Args:
        item (StoreItem): Store item to save.
    """
    store = load_store()
    store.append(item)
    save_store(store)

def save_store(items: list[StoreItem]):
    """
    Save store to file.

    Args:
        items (list[StoreItem]): Store items to save.
    """
    if not os.path.exists(os.path.dirname(STORE_PATH)):
        os.makedirs(os.path.dirname(STORE_PATH))

    with open(STORE_PATH, "w") as f:
        json.dump([item.__dict__ for item in items], f)


import sys
import os
import tools.structure_analysis_tools as sa
import tools.network_visualization as nv
import tools.helpers as helpers
import networkx as nx
import matplotlib.pyplot as plt
import pickle
import pandas as pd
import csv
from shutil import copyfile

plt.rc("text", usetex=True)

data_folder = "data"

# Read configuration file
config_file_path = "analysis_config.json"
parameters = helpers.get_configuration_parameters(config_file_path)

name = parameters["name"]
pdb_id = parameters["pdb_id"]
cutoff = parameters["cutoff"]
dim = parameters["dim"]
if dim == "all":
    dim = ""
rel_list = sa.list_relations(dim)
pdbs_path = parameters["pdbs_path"]
select_positions = parameters["select_positions"]
if select_positions:
    start = parameters["start"]
    stop = parameters["stop"]
    selected_positions = range(start, stop)
else:
    selected_positions = None
variant = parameters["variant"]
if variant:
    reference_folder = parameters["reference_folder"]
    threshold = parameters["threshold"]
    single_mutation = parameters["single_mutation"]
    if single_mutation:
        source = parameters["source"]
subnet_highnw = parameters["subnet_highnw"]
subnet_highwij = parameters["subnet_highwij"]
draw_neighborhoods = parameters["draw_neighborhoods"]
calculate_cliques = parameters["calculate_cliques"]
if calculate_cliques:
    draw_large_cliques = parameters["draw_large_cliques"]
remove_hydrogen_atoms = parameters["remove_hydrogen_atoms"]

results_to_report = []

folder_path = os.path.join("results", name, dim + "analysis")
os.makedirs(folder_path, exist_ok=True)

helpers.save_configuration_parameters(config_file_path, folder_path)

for k, v in parameters.items():
    print(k, "\t", v)

# import mutations
(
    mutations_type,
    pathogenic,
    non_pathogenic,
    both,
    pathogenic_names,
    non_pathogenic_names,
) = sa.import_mutations(folder_path)

# load k_w dictionary (from database)
k_w = pickle.load(open(os.path.join(data_folder, "k_w.p"), "rb"))

# create aa network and save database of its aa (2 formats)
net, db_1, db_2, mol, downloaded = sa.create_aa_network(
    pdb_id,
    rel_list,
    folder_path,
    selected_positions,
    cutoff=cutoff,
    kw_reprod=True,
    k_w=k_w,
    pdbs_path=pdbs_path,
    remove_hydrogen_atoms=remove_hydrogen_atoms,
    db_1_name=pdb_id + 'nodes_1.csv',
    db_2_name=pdb_id + 'nodes_2.csv'
)

print("AAN created")
print("N. nodes: ", len(net.nodes))
print("N. edges: ", len(net.edges))

contact_list = list(net.edges)
file_contacts = os.path.join(folder_path, pdb_id + "contact_list.csv")
with open(file_contacts, "w", newline="") as f:
    writer = csv.writer(f)
    for line in contact_list:
        writer.writerow(line)

results_to_report.append(["AAN"])
results_to_report.append(["N. nodes: ", len(net.nodes)])
results_to_report.append(["N. edges: ", len(net.edges)])

chains = sa.get_chains(mol)

# plot nw distribution
neigh_watch = db_2["Weight/Degree"].values

nw_helix, nw_sheet, nw_loop = sa.divided_nw_lists(db_2)

sa.plot_nw_hist(
    nw_helix,
    nw_sheet,
    nw_loop,
    folder_path,
    inset="herfindhal",
    file_name="neighborhood_watch_distribution1.pdf",
)

sa.plot_nw_hist(
    nw_helix,
    nw_sheet,
    nw_loop,
    folder_path,
    inset="boxplot",
    file_name="neighborhood_watch_distribution2.pdf",
)

# plot nw along the sequence

if name[0:3] == "ttr":
    onlyA = True
else:
    onlyA = False

sa.plot_nw_sequence(db_2, folder_path, onlyA=onlyA)

# plot wij distribution

sa.plot_wij_distribution(net, folder_path)

sa.plot_wij_distribution(
    net, folder_path, file_name="pairwise_distrib_log.pdf", yscale="log",
    boxplot=True, normed=False
)

# DRAW PROTEIN NETWORK
pict_folder = os.path.join(folder_path, "network_pictures")
os.makedirs(pict_folder, exist_ok=True)

if downloaded:
    pdb_id = "pdb" + pdb_id

node_labels, sizes, color_map, _ = nv.network_visualization_parameters(
    pdb_id,
    database=db_2,
    net=net,
    rel_list=rel_list,
    kw_reprod=True,
    k_w=k_w,
    colors="neighborhood_watch_sharp",
    sizes=None,
)
node_labels2, sizes2, color_map2, _ = nv.network_visualization_parameters(
    pdb_id,
    database=db_2,
    net=net,
    rel_list=rel_list,
    kw_reprod=True,
    k_w=k_w,
    colors=None,
    sizes=None,
)
node_labels3, sizes3, color_map3, edge_color_map = nv.network_visualization_parameters(
    pdb_id,
    database=db_2,
    net=net,
    rel_list=rel_list,
    kw_reprod=True,
    k_w=k_w,
    colors="pairwise_sharp",
    sizes="neighborhood_watch_sharp",
)

pos_spring = nx.spring_layout(net)
pos_circular = nx.circular_layout(net)

name1 = os.path.join(pict_folder, pdb_id + "_color")
name2 = os.path.join(pict_folder, pdb_id + "_size")
name3 = os.path.join(pict_folder, pdb_id + "_colorsize")
name3b = os.path.join(pict_folder, pdb_id + "_colornosize")
name4 = os.path.join(pict_folder, pdb_id + "_nodes")
name5 = os.path.join(pict_folder, pdb_id + "_links")
name6 = os.path.join(pict_folder, pdb_id + "_links_color")

nv.draw_network(
    net,
    node_labels,
    color_map=color_map,
    draw_edges=False,
    draw_labels=False,
    name=name1,
    figsize=(50, 50),
    pos=pos_spring,
)
nv.draw_network(
    net,
    node_labels,
    sizes=sizes,
    draw_labels=False,
    name=name2,
    figsize=(50, 50),
    pos=pos_spring,
)
nv.draw_network(
    net,
    node_labels,
    sizes=sizes,
    color_map=color_map,
    draw_labels=False,
    name=name3,
    figsize=(50, 50),
    pos=pos_spring
)
nv.draw_network(
    net,
    node_labels,
    color_map=color_map,
    draw_labels=False,
    name=name3b,
    figsize=(50, 50),
    pos=pos_spring,
    edge_thickness=False
)

nv.draw_network(
    net,
    node_labels2,
    color_map="deepskyblue",
    draw_edges=False,
    draw_labels=False,
    name=name4,
    figsize=(50, 50),
    pos=pos_spring
)
nv.draw_network(
    net,
    node_labels2,
    sizes=sizes2,
    color_map="deepskyblue",
    draw_labels=False,
    name=name5,
    figsize=(50, 50),
    pos=pos_spring,
    legend_thickness=True
)
nv.draw_network(
    net,
    node_labels3,
    sizes=sizes3,
    edge_color_map=edge_color_map,
    draw_labels=False,
    name=name6,
    figsize=(50, 50),
    pos=pos_spring,
    facecolor="silver",
)

net_path = os.path.join(folder_path, dim)

pickle.dump(net, open(net_path + "net.p", "wb"))

nv.plot_legends(folder_path=folder_path)

# sizes_dict = {node: size_map[i] for i, node in enumerate(net.nodes)}
edge_color_dict = {edge: edge_color_map[i] for i, edge in enumerate(net.edges)}
color_dict = {node: color_map[i] for i, node in enumerate(net.nodes)}

# CLIQUES
if calculate_cliques:
    cliques = sa.cliques(net)
    print("Cliques of AAN created")
    results_to_report.append(["Cliques of AAN"])

    if draw_large_cliques:
        cliques_folder = os.path.join(pict_folder, "large_cliques")
        os.makedirs(cliques_folder, exist_ok=True)

    for l in cliques:
        c_list = cliques[l]
        n = len(c_list)
        print(n, " cliques of size ", l)
        results_to_report.append(["%s cliques of size %s" % (n, l)])
        if draw_large_cliques and l > 4:
            for j, c in enumerate(c_list):
                c_net = nx.Graph()
                c_net.add_nodes_from(c)
                for i, v in enumerate(c[:-1]):
                    for u in c[i + 1 : :]:
                        wuv = net.get_edge_data(v, u)["weight"]
                        c_net.add_edge(u, v, weight=wuv)

                color_map_c = []
                edge_color_map_c = []
                node_labels_c = {}
                for v in c_net.nodes:
                    color = color_dict[v]
                    label = node_labels[v]
                    node_labels_c[v] = label
                    color_map_c.append(color)
                for u, v in c_net.edges:
                    edge_color = edge_color_dict[(u, v)]
                    edge_color_map_c.append(edge_color)

                file_name = os.path.join(
                    cliques_folder, "%sclique%s-%s" % (pdb_id, l, j)
                )
                nv.draw_network(
                    c_net,
                    node_labels_c,
                    edge_color_map=edge_color_map_c,
                    name=file_name,
                    figsize=(10, 10),
                    node_edge_size=1,
                    node_edge_colors="gray",
                )

# DRAW NEIGHBORHOODS
if draw_neighborhoods:
    neigh_path = os.path.join(pict_folder, "neighborhoods")
    os.makedirs(neigh_path, exist_ok=True)

    for node in net.nodes:
        if node[0] != "A":
            break
        file_name = os.path.join(neigh_path, pdb_id + node)
        nv.draw_neighborhood(
            net,
            node,
            node_labels,
            pathogenic,
            non_pathogenic,
            both,
            save_fig=True,
            file_name=file_name,
            threshold_edge=20,
        )

if variant:
    results_perturbation = []
    # DRAW PERTURBATION NETWORK
    #    path_ref = os.path.join(data_dir, reference_folder)
    net_ref_path = os.path.join(
        reference_folder, dim + "analysis", dim + "net.p"
    )
    net_ref = pickle.load(open(net_ref_path, "rb"))
    db_ref_path = os.path.join(reference_folder, "analysis", "database_pos_2.csv")
    db_ref = pd.DataFrame(pd.read_csv(db_ref_path))

    (
        net_p,
        node_labels_p,
        size_map_p,
        color_map_p,
        edge_color_dict_p,
        node_borders_p,
        edges_1only,
        edges_2only,
        common_edges,
    ) = nv.create_perturbation_network(
        net_ref, net, db_ref, db_2, threshold=threshold
    )

    print("Perturbation network")
    print("Threshold: ", threshold)
    print("N. nodes in PN: ", len(net_p.node))
    print("N. edges in PN: ", len(net_p.edges))
    n_components = nx.algorithms.components.number_connected_components(net_p)
    print("N. connected components in PN: ", n_components)

    results_perturbation.append(["Perturbation network created"])
    results_perturbation.append(["Threshold: ", threshold])
    results_perturbation.append(["N. nodes in PN: ", len(net_p.node)])
    results_perturbation.append(["N. edges in PN: ", len(net_p.edges)])
    results_perturbation.append(["N. connected components in PN: ", n_components])

    edge_color_map_p = []
    for u, v in net_p.edges:
        try:
            edge_color_map_p.append(edge_color_dict_p[u, v])
        except KeyError:
            edge_color_map_p.append(edge_color_dict_p[v, u])

    nodes_pos = nv.nodes_position_perturbation(
        net_p, dim, chains, scale=4, max_x=30
    )
    nodes_pos2 = nv.nodes_position_perturbation(
        net_p, dim, chains, columns=True
    )

    file_name = os.path.join(
        pict_folder, pdb_id + "perturbation_net_links_color" + str(threshold)
    )
    file_name2 = os.path.join(
        pict_folder,
        pdb_id + "perturbation_net_links_color" + str(threshold) + "_columns",
    )

    plt.rc("text", usetex=False)

    nv.draw_network(
        net_p,
        node_labels_p,
        sizes=size_map_p,
        edge_color_map=edge_color_map_p,
        color_map=color_map_p,
        draw_labels=True,
        name=file_name,
        figsize=(20, 15),
        node_edge_colors=node_borders_p,
        pos=nodes_pos,
    )

    nv.draw_network(
        net_p,
        node_labels_p,
        sizes=size_map_p,
        edge_color_map=edge_color_map_p,
        color_map=color_map_p,
        draw_labels=True,
        name=file_name2,
        figsize=(20, 30),
        node_edge_colors=node_borders_p,
        pos=nodes_pos2,
    )

    if draw_neighborhoods:
        neigh_pert_path = os.path.join(pict_folder, "neighborhoods_perturbation")
        os.makedirs(neigh_pert_path, exist_ok=True)
        for node in net_p.nodes:
            if node[0] != "A":
                continue
            file_name = os.path.join(neigh_pert_path, pdb_id + node)
            nv.draw_neighborhood_perturbation(
                net_p,
                node,
                node_labels_p,
                size_map_p,
                color_map_p,
                edge_color_map_p,
                node_borders_p,
                file_name=file_name,
            )

    sizes_dict = {node: size_map_p[i] for i, node in enumerate(net_p.nodes)}
    edge_color_dict = {edge: edge_color_map_p[i] for i, edge in enumerate(net_p.edges)}
    color_dict = {node: color_map_p[i] for i, node in enumerate(net_p.nodes)}
    node_borders_dict = {node: node_borders_p[i] for i, node in enumerate(net_p.nodes)}
    weights_p = nx.get_edge_attributes(net_p, "weight")

    net_p_file = os.path.join(folder_path, "net_p%s.csv" % (threshold))
    with open(net_p_file, "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["u", "v", "weight", "color"])
        for i, (u, v) in enumerate(net_p.edges):
            w = net_p.get_edge_data(u, v)["weight"]
            color = edge_color_map_p[i]
            writer.writerow([u, v, w, color])

    # INDUCED PERTURBATION NETWORK

    if single_mutation:

        ipn = nv.induced_perturbation_network(net_p, source)

        if ipn:
            node_labels_ipn = {node: node_labels_p[node] for node in ipn.nodes}

            sizes_ipn = [sizes_dict[node] for node in ipn.nodes]

            edge_color_ipn = []
            weights_ipn = {}
            for u, v in ipn.edges:
                try:
                    edge_color_ipn.append(edge_color_dict[(u, v)])
                except KeyError:
                    edge_color_ipn.append(edge_color_dict[(v, u)])
                try:
                    weights_ipn[(u, v)] = weights_p[(u, v)]
                except KeyError:
                    weights_ipn[(u, v)] = weights_p[(v, u)]

            nx.set_edge_attributes(ipn, weights_ipn, name="weight")

            print("Induced perturbation network created")
            print("N. nodes in IPN: ", len(ipn.node))
            print("N. edges in IPN: ", len(ipn.edges))

            results_perturbation.append(["Induced perturbation network"])
            results_perturbation.append(["N. nodes in IPN: ", len(ipn.node)])
            results_perturbation.append(["N. edges in IPN: ", len(ipn.edges)])

            color_ipn = [color_dict[node] for node in ipn.nodes]
            node_borders_ipn = [node_borders_dict[node] for node in ipn.nodes]

            pickle.dump(
                [
                    ipn,
                    node_labels_ipn,
                    sizes,
                    edge_color_ipn,
                    color_ipn,
                    node_borders_ipn,
                ],
                open(os.path.join(folder_path, "ipn.p"), "wb"),
            )

            pos_ipn = nv.nodes_position_perturbation(
                ipn, dim, chains
            )

            pos_ipn2 = nv.nodes_position_perturbation(
                ipn, dim, chains, columns=True
            )

            node_borders_ipn = ["r"]
            node_borders_ipn = node_borders_ipn + [
                "gray" for node in list(ipn.nodes)[1::]
            ]

            color_ipn = ["y"]
            color_ipn = color_ipn + ["lightgray" for node in list(ipn.nodes)[1::]]
            color_ipn_dict = {node: color_ipn[i] for i, node in enumerate(ipn.node)}

            name_ipn = os.path.join(
                pict_folder,
                pdb_id + "perturbation_ipn_" + str(threshold) + source + "_" + dim,
            )
            nv.draw_network(
                ipn,
                node_labels_ipn,
                sizes=600,
                edge_color_map=edge_color_ipn,
                color_map=color_ipn,
                draw_labels=True,
                name=name_ipn,
                figsize=(30, 30),
                pos=pos_ipn,
                labels_size=18,
                node_edge_size=1,
            )

            name_ipn2 = os.path.join(
                pict_folder,
                pdb_id
                + "perturbation_ipn_"
                + str(threshold)
                + source
                + "_"
                + dim
                + "columns",
            )
            nv.draw_network(
                ipn,
                node_labels_ipn,
                sizes=600,
                edge_color_map=edge_color_ipn,
                color_map=color_ipn,
                draw_labels=True,
                name=name_ipn2,
                figsize=(30, 30),
                pos=pos_ipn2,
                labels_size=18,
                node_edge_size=1,
            )

            ipn_file = os.path.join(folder_path, "ipn%s.csv" % (threshold))
            with open(ipn_file, "w", newline="") as f:
                writer = csv.writer(f)
                writer.writerow(["u", "v", "weight", "color"])
                for i, (u, v) in enumerate(ipn.edges):
                    w = ipn.get_edge_data(u, v)["weight"]
                    color = edge_color_ipn[i]
                    writer.writerow([u, v, w, color])

            triangles_ipn = sa.triangles_ipn(ipn, edge_color_dict)

            green_tr = triangles_ipn["ggg"]
            red_tr = triangles_ipn["rrr"]
            mostlygreen_tr = triangles_ipn["ggr"]
            mostlyred_tr = triangles_ipn["rrg"]

            print("N. green triangles: ", len(green_tr))
            print("N. mostly green triangles: ", len(mostlygreen_tr))
            print("N. red triangles: ", len(red_tr))
            print("N. mostly red triangles: ", len(mostlyred_tr))

            results_perturbation.append(["N. green triangles: ", len(green_tr)])
            results_perturbation.append(
                ["N. mostly green triangles: ", len(mostlygreen_tr)]
            )
            results_perturbation.append(["N. red triangles: ", len(red_tr)])
            results_perturbation.append(
                ["N. mostly red triangles: ", len(mostlyred_tr)]
            )

            # Green and red IPN
            green_ipn = nx.Graph()
            red_ipn = nx.Graph()
            for i, (u, v) in enumerate(ipn.edges):
                color = edge_color_ipn[i]
                wuv = ipn.get_edge_data(u, v)["weight"]
                if color == "green":
                    green_ipn.add_edge(u, v, weight=wuv)
                else:
                    red_ipn.add_edge(u, v, weight=wuv)

            color_green_ipn = [color_ipn_dict[node] for node in green_ipn.nodes]
            color_red_ipn = [color_ipn_dict[node] for node in red_ipn.nodes]

            name_green = os.path.join(
                pict_folder,
                pdb_id
                + "perturbation_green_ipn_"
                + str(threshold)
                + source
                + "_"
                + dim,
            )

            name_red = os.path.join(
                pict_folder,
                pdb_id + "perturbation_red_ipn_" + str(threshold) + source + "_" + dim,
            )

            nv.draw_network(
                green_ipn,
                node_labels_ipn,
                sizes=600,
                edge_color_map="green",
                color_map=color_green_ipn,
                draw_labels=True,
                name=name_green,
                figsize=(10, 10),
                pos=pos_ipn,
                labels_size=18,
                node_edge_size=1,
            )

            nv.draw_network(
                red_ipn,
                node_labels_ipn,
                sizes=600,
                edge_color_map="red",
                color_map=color_red_ipn,
                draw_labels=True,
                name=name_red,
                figsize=(10, 10),
                pos=pos_ipn,
                labels_size=18,
                node_edge_size=1,
            )

            print("Green IPN created")
            print("N. nodes in green IPN: ", len(green_ipn))
            print("N. edges in green IPN: ", len(green_ipn.edges))
            n_components = nx.algorithms.components.number_connected_components(
                green_ipn
            )
            print("N. connected components in green IPN: ", n_components)

            results_perturbation.append(["Green IPN"])
            results_perturbation.append(["N. nodes in green IPN: ", len(green_ipn)])
            results_perturbation.append(
                ["N.edges in green IPN: ", len(green_ipn.edges)]
            )
            results_perturbation.append(
                ["N. connected components in green IPN: ", n_components]
            )

            # CLIQUES
            green_cliques = sa.cliques(green_ipn)
            pickle.dump(
                green_cliques, open(net_path + "green_cliques%s.p" % (threshold), "wb")
            )
            print("Cliques of green IPN created")
            results_perturbation.append(["Cliques of green IPN created"])

            for l in green_cliques:
                c_list = green_cliques[l]
                n = len(c_list)
                print(n, " cliques of size ", l)
                results_perturbation.append(["%s cliques of size %s" % (n, l)])
                if l > 5:
                    green_cliques_folder = os.path.join(
                        pict_folder, "large_cliques_greenIPN"
                    )
                    os.makedirs(green_cliques_folder, exist_ok=True)
                    for j, c in enumerate(c_list):
                        c_net = nx.Graph()
                        c_net.add_nodes_from(c)
                        for i, v in enumerate(c[:-1]):
                            for u in c[i + 1 : :]:
                                wuv = net.get_edge_data(v, u)["weight"]
                                c_net.add_edge(u, v, weight=wuv)

                        color_map_c = []
                        edge_color_map_c = []
                        node_labels_c = {}
                        for v in c_net.nodes:
                            color = color_dict[v]
                            label = node_labels[v]
                            node_labels_c[v] = label
                            color_map_c.append(color)
                        for u, v in c_net.edges:
                            edge_color = edge_color_dict[(u, v)]
                            edge_color_map_c.append(edge_color)

                        file_name = os.path.join(
                            cliques_folder, "%sclique%s-%s" % (pdb_id, l, j)
                        )
                        nv.draw_network(
                            c_net,
                            node_labels_c,
                            edge_color_map=edge_color_map_c,
                            name=file_name,
                            figsize=(10, 10),
                            node_edge_size=1,
                            node_edge_colors="gray",
                        )

            print("Red IPN created")
            print("N. nodes in red IPN: ", len(red_ipn))
            print("N.edges in red IPN: ", len(red_ipn.edges))
            n_components = nx.algorithms.components.number_connected_components(red_ipn)
            print("N. connected components in red IPN: ", n_components)

            results_perturbation.append(["Red IPN"])
            results_perturbation.append(["N. nodes in red IPN: ", len(red_ipn)])
            results_perturbation.append(["N.edges in red IPN: ", len(red_ipn.edges)])
            results_perturbation.append(
                ["N. connected components in red IPN: ", n_components]
            )

            # CLIQUES
            red_cliques = sa.cliques(red_ipn)
            pickle.dump(
                red_cliques, open(net_path + "red_cliques%s.p" % (threshold), "wb")
            )
            print("Cliques of red IPN created")
            results_perturbation.append(["Cliques of red IPN created"])

            for l in red_cliques:
                c_list = red_cliques[l]
                n = len(c_list)
                print(n, " cliques of size ", l)
                results_perturbation.append(["%s cliques of size %s" % (n, l)])
                if l > 5:
                    red_cliques_folder = os.path.join(
                        pict_folder, "large_cliques_redIPN"
                    )
                    os.makedirs(red_cliques_folder, exist_ok=True)
                    for j, c in enumerate(c_list):
                        c_net = nx.Graph()
                        c_net.add_nodes_from(c)
                        for i, v in enumerate(c[:-1]):
                            for u in c[i + 1 : :]:
                                wuv = net.get_edge_data(v, u)["weight"]
                                c_net.add_edge(u, v, weight=wuv)

                        color_map_c = []
                        edge_color_map_c = []
                        node_labels_c = {}
                        for v in c_net.nodes:
                            color = color_dict[v]
                            label = node_labels[v]
                            node_labels_c[v] = label
                            color_map_c.append(color)
                        for u, v in c_net.edges:
                            edge_color = edge_color_dict[(u, v)]
                            edge_color_map_c.append(edge_color)

                        file_name = os.path.join(
                            cliques_folder, "%sclique%s-%s" % (pdb_id, l, j)
                        )
                        nv.draw_network(
                            c_net,
                            node_labels_c,
                            edge_color_map=edge_color_map_c,
                            name=file_name,
                            figsize=(10, 10),
                            node_edge_size=1,
                            node_edge_colors="gray",
                        )

            file_results_perturbation = os.path.join(
                folder_path, "results_perturbation%s.csv" % (threshold)
            )
            with open(file_results_perturbation, "w", newline="") as f:
                writer = csv.writer(f)
                for line in results_perturbation:
                    writer.writerow(line)

if subnet_highnw:
    # SUBNETWORK OF HIGH NW
    subnet = sa.subnet_highnw(net)

    print("Subnetwork of high nw created")
    N_subnet = len(subnet)
    print("N. nodes in subnet (before removing degrees zero): ", N_subnet)
    print("N. edges in subnet: ", len(subnet.edges))
    n_components = nx.algorithms.components.number_connected_components(subnet)
    print("N. connected components in subnet: ", n_components)

    results_to_report.append(["Subnetwork of high nw created"])
    results_to_report.append(
        ["N. nodes in subnet (before removing degrees zero): ", len(subnet)]
    )
    results_to_report.append(["N. edges in subnet: ", len(subnet.edges)])
    results_to_report.append(["N. connected components in subnet: ", n_components])

    # remove nodes of degree zero
    degrees_zero = []
    for node in subnet.nodes:
        k = nx.degree(subnet, node)
        if k == 0:
            degrees_zero.append(node)
    subnet.remove_nodes_from(degrees_zero)

    print("N. nodes in subnet (after removing degrees zero): ", len(subnet))
    print("N. components of size 1: ", N_subnet - len(subnet))

    results_to_report.append(
        ["N. nodes in subnet (after removing degrees zero): ", len(subnet)]
    )
    results_to_report.append(["N. components of size 1: ", N_subnet - len(subnet)])

    # plot P(wij) subnet
    wij_list_sn, edge_colors_sn = sa.get_edge_data(subnet)

    file_name = os.path.join(folder_path, "pairwise_distrib_highnw.pdf")
    title = "Pairwise weight distribution in the sub-network with $w/k\geq13$"
    sa.plot_wij_distribution(
        subnet, folder_path, title=title, file_name=file_name, yscale="log"
    )

    # plot subnet
    node_labels_subnet = {node: node_labels3[node] for node in subnet.nodes}
    nw_subnet_size = sa.get_size_from_nw(subnet)

    nv.draw_network(
        subnet,
        node_labels_subnet,
        sizes=nw_subnet_size,
        edge_color_map=edge_colors_sn,
        draw_labels=False,
        name=pict_folder + pdb_id + "_links_color" + "_highnw",
        figsize=(50, 50),
        pos=pos_spring,
        facecolor="silver",
    )

    # largest connected component
    lcc = sa.lcc(subnet)

    print("LCC of subnetwork of high nw created")
    print("N. nodes in LCC of subnet: ", len(lcc))

    results_to_report.append(["LCC of subnetwork of high nw"])
    results_to_report.append(["N. nodes in LCC of subnet: ", len(lcc)])

    # plot P(wij) of lcc of subnet

    wij_list_lcc, edge_colors_lcc = sa.get_edge_data(lcc)

    file_name = os.path.join(folder_path, "pairwise_distrib_highnwLCC.pdf")
    title = (
        "Pairwise weight distribution in the LCC of the sub-network with $w/k\geq13$"
    )
    sa.plot_wij_distribution(
        lcc, folder_path, title=title, file_name=file_name, yscale="log"
    )

    # plot lcc
    node_labels_lcc = {node: node_labels3[node] for node in lcc.nodes}
    nw_lcc_size = sa.get_size_from_nw(lcc)

    name = os.path.join(pict_folder, pdb_id + "_links_color" + "_highnwLCC")

    nv.draw_network(
        lcc,
        node_labels_lcc,
        sizes=nw_lcc_size,
        edge_color_map=edge_colors_lcc,
        draw_labels=False,
        name=name,
        figsize=(50, 50),
        pos=pos_spring,
        facecolor="silver",
    )

if subnet_highwij:
    # SUBNETWORK OF HIGH wij
    subnet2 = sa.subnet_highwij(net)

    print("Subnetwork of high wij created")
    N_subnet = len(subnet2)
    print("N. nodes in subnet: ", N_subnet)
    print("N. edges in subnet: ", len(subnet2.edges))
    n_components = nx.algorithms.components.number_connected_components(subnet2)
    print("N. connected components in subnet: ", n_components)

    results_to_report.append(["Subnetwork of high wij created"])
    results_to_report.append(
        ["N. nodes in subnet (before removing degrees zero): ", len(subnet2)]
    )
    results_to_report.append(["N. edges in subnet: ", len(subnet2.edges)])
    results_to_report.append(["N. connected components in subnet: ", n_components])

    wij_list_sn2, edge_colors_sn2 = sa.get_edge_data(subnet2)

    # plot subnet
    node_labels_subnet2 = {node: node_labels3[node] for node in subnet2.nodes}
    nw_subnet_size2 = sa.get_size_from_nw(subnet2)

    name = os.path.join(pict_folder, pdb_id + "_links_color" + "_highwij")

    # nv.draw_network(
    #     subnet2,
    #     node_labels_subnet2,
    #     sizes=nw_subnet_size2,
    #     edge_color_map=edge_colors_sn2,
    #     draw_labels=False,
    #     name=name,
    #     figsize=(50, 50),
    #     pos=pos_spring,
    #     facecolor="silver",
    # )

    nv.draw_network(
        subnet2,
        node_labels_subnet2,
        draw_labels=False,
        name=name,
        figsize=(50, 50),
        pos=pos_spring,
        facecolor="silver",
    )

    # largest connected component
    lcc2 = sa.lcc(subnet2)

    print("LCC of subnetwork of high wij created")
    print("N. nodes in LCC of subnet: ", len(lcc2))

    results_to_report.append(["LCC of subnetwork of high wij created"])
    results_to_report.append(["N. nodes in LCC of subnet: ", len(lcc2)])

file_results = os.path.join(folder_path, "results.csv")
with open(file_results, "w", newline="") as f:
    writer = csv.writer(f)
    for line in results_to_report:
        writer.writerow(line)


##Load the train and test data
##Train the model with the training data
##Save the parameters
import os
import json
import joblib
import argparse
import numpy as np
import pandas as pd
from get_data import read_params
from sklearn.model_selection import train_test_split
from sklearn.linear_model import ElasticNet
from sklearn.metrics import mean_squared_error,mean_absolute_error,r2_score

def train_evaluate(config_path):
    config = read_params(config_path)
    test_data_path = config['split_data']['test_data_path']
    train_data_path = config['split_data']['train_data_path']
    random_state = config['split_data']['random_state']
    model_store_dir = config['train_evaluate']['model_store_dir']
    alpha = config['train_evaluate']['alpha']
    l1_ratio = config['train_evaluate']['l1_ratio']
    target_col = [config['train_evaluate']['target_col']]
    scores_json = config['reports']['scores_json']
    params_file = config['reports']['params_json']

    train_data = pd.read_csv(train_data_path,sep=",")
    test_data = pd.read_csv(test_data_path,sep=",")

    train_x = train_data.drop(columns=target_col,axis=1)
    test_x = test_data.drop(columns=target_col,axis=1)

    train_y = train_data[target_col]
    test_y = test_data[target_col]

    lr = ElasticNet(alpha=alpha,l1_ratio=l1_ratio,random_state=random_state)
    lr.fit(train_x,train_y)

    predicted_qualities = lr.predict(test_x)
    rmse,mae,r2 = evaluate_metrics(test_y,predicted_qualities)
    print(rmse,mae,r2)

    with open(params_file,'w') as rb:
        params = {
            "alpha": alpha,
            "l1_ratio": l1_ratio,
        }
        json.dump(params,rb,indent=4)

    with open(scores_json,'w') as rb:
        scores = {
            "rmse": rmse,
            "mae": mae,
            "r2": r2
        }
        json.dump(scores,rb,indent=4)

    os.makedirs(model_store_dir,exist_ok=True)
    model_path = os.path.join(model_store_dir,"model.joblib")
    joblib.dump(lr,model_path)

def evaluate_metrics(actual,predicted):
    rmse = np.sqrt(mean_squared_error(actual, predicted))
    mae = mean_absolute_error(actual, predicted)
    r2 = r2_score(actual, predicted)
    return rmse,mae,r2

if __name__=='__main__':
    args = argparse.ArgumentParser()
    config_path = os.path.join("config","params.yml")
    args.add_argument("--config", default=config_path)
    parsed_args = args.parse_args()
    train_evaluate(config_path=parsed_args.config)


import numpy as np
import matplotlib.pyplot as plt
from numpy import linalg as LA
import cv2 as cv
import math
import matplotlib.cm as cm
from scipy.signal import convolve2d
import random

# function to calculate 1st order derivative of gaussian
def gaussian(sigma,x,y):
    a= 1/(np.sqrt(2*np.pi)*sigma)
    b=math.exp(-(x**2+y**2)/(2*(sigma**2)))
    c = a*b
    return a*b

## getting kernel from  gaussian for [-1,0,1]
def gaussian_kernel():
    G=np.zeros((5,5))
    for i in range(-2,3):
        for j in range(-2,3):
            G[i+1,j+1]=gaussian(1.5,i,j)
    return G

def Lucas_Kanade_Expand(image):

    w, h = image.shape
    newWidth = int(w * 2)
    newHei = int(h * 2)
    newImage = np.zeros((newWidth,
                         newHei))  # interpolate of image i.e. inserting making image by inserting 0 alternate to every original pixels
    newImage[::2, ::2] = image
    G = gaussian_kernel()
    for i in range(2, newImage.shape[0] - 2, 2):
        for j in range(2, newImage.shape[1] - 2, 2):
            newImage[i, j] = np.sum(newImage[i - 2:i + 3, j - 2:j + 3] * G)  # convolving with gaussian mask

    return newImage

def LK_Expand_Iterative(Img,Level):
    if Level==0:#level 0 means current level i.e. no change
        return Img
    i=0
    newImage=cv.imread(Img,0)
    while(i<Level):
        newImage=Lucas_Kanade_Expand(newImage)
        i=i+1
    return newImage

def Lucas_Kanade_Pyramid_Reduce(img,level):
    print(cv.imread(img).shape)
    I1 = cv.imread(img, 0)
    if level==0: #if level is zero than returing original image as no change
        return I1
    x=0
    while(x<level):
        w,h=I1.shape
        newWidth=int(w/2)
        newHei=int(h/2)
        G=gaussian_kernel()
        newImage = np.ones((newWidth,newHei))
        for i in range(2,I1.shape[0]-2,2):#making image of half size by skiping alternate pixels
            for j in range(2,I1.shape[1]-2,2):
                newImage[int(i/2),int(j/2)]=np.sum(I1[i - 2:i + 3, j - 2:j + 3]*G)#convolving with gaussian mask
        print(newImage.shape)
        x=x+1
        if x==level:
            return newImage

def Lucas_Kanade_Reduce(I1):
    w, h = I1.shape
    newWidth = int(w / 2)
    newHei = int(h / 2)
    G = gaussian_kernel()
    newImage = np.ones((newWidth, newHei))
    for i in range(2, I1.shape[0] - 2, 2):  # making image of half size by skiping alternate pixels
        for j in range(2, I1.shape[1] - 2, 2):
            newImage[int(i / 2), int(j / 2)] = np.sum(I1[i - 2:i + 3, j - 2:j + 3] * G)  # convolving with gaussian mask

    return newImage

def LK_Reduce_Iterative(Img,Level):
    if Level==0:#level 0 means current level i.e. no change
        return Img
    i=0
    newImage=cv.imread(Img,0)
    while(i<Level):
        newImage=Lucas_Kanade_Reduce(newImage)
        i=i+1

    return newImage

def Lucas_Kanade(image1,I1, image2,I2,Level,Reduce_Expand):
    oldframe = cv.imread(image1)
    I11 = cv.cvtColor(oldframe, cv.COLOR_BGR2GRAY)
    #I1=I1.astype(np.float64)
    newframe = cv.imread(image2)
    #I2 = cv.cvtColor(newframe, cv.COLOR_BGR2GRAY)

    color = np.random.randint(0, 255, (100, 3))
    Gx = np.reshape(np.asarray([[-1, 1], [-1, 1]]), (2, 2))  # for image 1 and image 2 in x direction
    Gy = np.reshape(np.asarray([[-1, -1], [1, 1]]), (2, 2))  # for image 1 and image 2 in y direction
    Gt1 = np.reshape(np.asarray([[-1, -1], [-1, -1]]), (2, 2))  # for 1st image
    Gt2 = np.reshape(np.asarray([[1, 1], [1, 1]]), (2, 2))  # for 2nd image

    Ix = (convolve2d(I1, Gx) + convolve2d(I2, Gx)) / 2 #smoothing in x direction

    Iy = (convolve2d(I1, Gy) + convolve2d(I2, Gy)) / 2 #smoothing in y direction
    It1 = convolve2d(I1, Gt1) + convolve2d(I2, Gt2)   #taking difference of two images using gaussian mask of all -1 and all 1

    # parameter to get features
    feature_params = dict(maxCorners=100,
                          qualityLevel=0.3,
                          minDistance=7,
                          blockSize=7)

    features= cv.goodFeaturesToTrack(I11, mask = None, **feature_params)  #using opencv function to get feature for which we are plotting flow
    feature = np.int32(features)

    ## IF we are reducing than fetures will be reduced by 2**Level
    if Reduce_Expand=="Reduce":
        feature=np.int32(feature/(2**Level))
    else:
        feature=np.int32(feature*(2**Level)) #if we are expanding than feature will expand by 2*Level
    # print(feature)
    feature = np.reshape(feature, newshape=[-1, 2])

    u = np.ones(Ix.shape)
    v = np.ones(Ix.shape)
    status=np.zeros(feature.shape[0]) # this will tell change in x,y
    A = np.zeros((2, 2))
    B = np.zeros((2, 1))
    mask = np.zeros_like(oldframe)

    newFeature=np.zeros_like(feature)
    """Assumption is  that all the neighbouring pixels will have similar motion.
    Lucas-Kanade method takes a 3x3 patch around the point. So all the 9 points have the same motion.
    We can find (fx,fy,ft) for these 9 points. So now our problem becomes solving 9 equations with two unknown variables which is over-determined.
    A better solution is obtained with least square fit method.
    Below is the final solution which is two equation-two unknown problem and solve to get the solution.
                               U=Ainverse*B
    where U is matrix of 1 by 2 and contains change in x and y direction(x==U[0] and y==U[1])
    we first calculate A matrix which is 2 by 2 matrix of [[fx**2, fx*fy],[ fx*fy fy**2] and now take inverse of it
    and B is -[[fx*ft1],[fy,ft2]]"""

    for a,i in enumerate(feature):

        x, y = i

        A[0, 0] = np.sum((Ix[y - 1:y + 2, x - 1:x + 2]) ** 2)

        A[1, 1] = np.sum((Iy[y - 1:y + 2, x - 1:x + 2]) ** 2)
        A[0, 1] = np.sum(Ix[y - 1:y + 2, x - 1:x + 2] * Iy[y - 1:y + 2, x - 1:x + 2])
        A[1, 0] = np.sum(Ix[y - 1:y + 2, x - 1:x + 2] * Iy[y - 1:y + 2, x - 1:x + 2])
        Ainv = np.linalg.pinv(A)

        B[0, 0] = -np.sum(Ix[y - 1:y + 2, x - 1:x + 2] * It1[y - 1:y + 2, x - 1:x + 2])
        B[1, 0] = -np.sum(Iy[y - 1:y + 2, x - 1:x + 2] * It1[y - 1:y + 2, x - 1:x + 2])
        prod = np.matmul(Ainv, B)

        u[y, x] = prod[0]
        v[y, x] = prod[1]

        newFeature[a]=[np.int32(x+u[y,x]),np.int32(y+v[y,x])]
        if np.int32(x+u[y,x])==x and np.int32(y+v[y,x])==y:    # this means that there is no change(x+dx==x,y+dy==y) so marking it as 0 else
            status[a]=0
        else:
            status[a]=1 # this tells us that x+dx , y+dy is not equal to x and y

    um=np.flipud(u)
    vm=np.flipud(v)
    if Reduce_Expand=="Reduce":# multiplying by 2**Level to get position in original image
        good_new=np.int32(newFeature[status==1]*(2**Level)) #status will tell the position where x and y are changed so for plotting getting only that points
        good_old = np.int32(feature[status==1]*(2**Level))
        print(good_old)
        print("Good new")

        print(good_new)
    else:#divding by 2**level to get original position back
        good_new = np.int32(newFeature[status == 1] / (2 ** Level))  # status will tell the position where x and y are changed so for plotting getting only that points
        good_old = np.int32(feature[status == 1] / (2 ** Level))

    # draw the tracks
    for i, (new, old) in enumerate(zip(good_new, good_old)):
        a, b = new.ravel()
        c, d = old.ravel()
        mask = cv.line(mask, (a, b), (c, d), color[i].tolist(), 2)
        newframe = cv.circle(newframe, (a, b), 5, color[i].tolist(), -1)
    img = cv.add(newframe, mask)
    return img

"""
 Tracking over image pyramids
allows track points of interest despite large disparity between
photos
"""

###### Reduced Image Pyramid###############################

I1_reduce=LK_Reduce_Iterative("basketball1.png",1)
I2_reduce=LK_Reduce_Iterative("basketball2.png",1)
FinalReduceImage1=Lucas_Kanade("basketball1.png",I1_reduce,"basketball2.png",I2_reduce,1,"Reduce")

plt.imshow(FinalReduceImage1)
plt.show()

I3_Reduce=LK_Reduce_Iterative("grove1.png",2)

I4_Reduce=LK_Reduce_Iterative("grove2.png",2)
FinalReduceImage2=Lucas_Kanade("grove1.png",I3_Reduce,"grove2.png",I4_Reduce,2,"Reduce")
plt.imshow(FinalReduceImage2)
plt.show()
#
# ###### Expand Image Pyramid###############################

I1_expand=LK_Expand_Iterative("basketball1.png",1)
I2_expand=LK_Expand_Iterative("basketball2.png",1)
FinalExpandImage1=Lucas_Kanade("basketball1.png",I1_expand,"basketball2.png",I2_expand,1,"Expand")
plt.imshow(FinalExpandImage1)
plt.show()

I3_expand=LK_Expand_Iterative("grove1.png",2)

I4_expand=LK_Expand_Iterative("grove2.png",2)
FinalExpandImage2=Lucas_Kanade("grove1.png",I3_expand,"grove2.png",I4_expand,2,"Expand")
plt.imshow(FinalExpandImage2)
plt.show()


from parse import load_dataframes
import pandas as pd
import shutil

def sort_stores_by_score(dataframes, n=20, min_reviews=30):
    """
    Req. 1-2-1 각 음식점의 평균 평점을 계산하여 높은 평점의 음식점 순으로 `n`개의 음식점을 정렬하여 리턴합니다
    -> 현재 음식점 별 평균 평점을 구하는 코드는 완성되어 있음
    우리가 해야할 것 : 평균 평점을 기준으로 음식점을 정렬하여 리턴

    Req. 1-2-2 리뷰 개수가 `min_reviews` 미만인 음식점은 제외합니다.
    """
    stores_reviews = pd.merge(
        dataframes["stores"], dataframes["reviews"], left_on="id", right_on="store"
    )

    # 리뷰 개수가 `min_reviews` 미만인 음식점은 제외합니다.
    # store 컬럼을 기준으로 group by를한다. 그리고 store_name을 표시한다.
    # 이 이유는, 이후 mean()을 하였을 때 정수형 컬럼을 제외하고 다 생략되지만, 이름을 확인하기 위해 stor_name을 추가한다.
    scores_group = stores_reviews[stores_reviews['review_cnt'] >= min_reviews].groupby(["store", "store_name", "branch", "review_cnt"])

    # 평균 평점을 기준으로 음식점을 정렬하여 리턴
    scores = scores_group.mean().sort_values(by=['score'], axis=0, ascending=False) # 평균 구하기

    return scores.head(n=n).reset_index()

def get_most_reviewed_stores(dataframes, n=20):
    """
    Req. 1-2-3 가장 많은 리뷰를 받은 `n`개의 음식점을 정렬하여 리턴합니다
    """
    stores_reviews = pd.merge(
        dataframes["stores"], dataframes["reviews"], left_on="id", right_on="store"
    )
    reviews = stores_reviews.groupby(["store", "store_name", "branch", "review_cnt", "tel", "area"])
    reviews_mean = reviews.mean()   # groupby를 했으면, 연산은 꼭 해야한다.

    stores_sorted_by_reviews = reviews_mean.sort_values(by='review_cnt', ascending=False)
    return stores_sorted_by_reviews.head(n=n).reset_index()

def get_most_active_users(dataframes, n=20):
    """
    Req. 1-2-4 가장 많은 리뷰를 작성한 `n`명의 유저를 정렬하여 리턴합니다.
    """
     # user와 review를 병합
    users_reviews = pd.merge(
        dataframes["users"], dataframes["reviews"], left_on="id", right_on="user"
    )
    # 확인하고 싶은 컬럼을 넣고, size() 함수를 사용하면 몇 개의 데이터가 group으로 묶였는지 새로운 컬럼이 생성된다. dataFrameGroup의 경우, count()와 같다.
    # 이후 reset_index, rename을 사용해 원하는 컬럼명을 설정한 뒤 사용한다.
    users = users_reviews.groupby(["user", "gender", "age"]).size().reset_index(name='reviews_cnt')

    users_sorted_by_review_counts = users.sort_values(by='reviews_cnt', ascending=False)
    return users_sorted_by_review_counts.head(n=n).reset_index()

def main():
    data = load_dataframes() # DUMP_FILE = os.path.join(DATA_DIR, "dump.pkl")

    # 단순 출력 형식문
    term_w = shutil.get_terminal_size()[0] - 1
    separater = "-" * term_w

    stores_most_scored = sort_stores_by_score(data)

    print("[최고 평점 음식점]")
    print(f"{separater}\n")
    for i, store in stores_most_scored.iterrows():
        print(
            "{rank}위: {store}({score}점)".format(
                rank=i + 1, store=store.store_name, score=store.score
            )
        )
    print(f"\n{separater}\n\n")

if __name__ == "__main__":
    main()


class DebtsDeleteMessage:
   def __init__(self,input):
      self.debts = []
      _val2 = None
      self._reasonFunc(input)
      _debtsLen = input.readUnsignedShort()
      for _i2 in range(0,_debtsLen):
         _val2 = input.readDouble()
         if(_val2 < 0 or _val2 > 9007199254740992) :
            raise RuntimeError("Forbidden value (" + _val2 + ") on elements of debts.")
         self.debts.append(_val2)

   def _reasonFunc(self,input) :
      self.reason = input.readByte()
      if(self.reason < 0) :
         raise RuntimeError("Forbidden value (" + str(self.reason) + ") on element of DebtsDeleteMessage.reason.")

   def resume(self):
      print("reason :",self.reason)
      print("debts :",self.debts)


#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author:haiton
# datetime:18-9-21 下午2:29
import pickle
import torch
import time
from utils.dataset import DefSeqDataset
from torch.utils.data import DataLoader
from datetime import timedelta

def get_testloader(filepath):
    with open(filepath, 'rb') as f:
        test = pickle.load(f)
    test_set = DefSeqDataset(test, mode='test')
    test_loader = DataLoader(
        dataset=test_set,
        batch_size=1,
        shuffle=True,
        num_workers=2
    )
    return test_loader

def repackage_hidden(h):
    """用新的变量重新包装隐藏层，将它们从历史中分离。"""
    """Wraps hidden states in new Tensors, to detach them from their history."""
    if isinstance(h, torch.Tensor):
        return h.detach()
    else:
        return tuple(repackage_hidden(v) for v in h)

def get_time_dif(start_time):
    """获取已使用时间"""
    end_time = time.time()
    time_dif = end_time - start_time
    return timedelta(seconds=int(round(time_dif)))


from pybtex.database import parse_file
import pybtex
import os

name = 'ANNs&StockMarket.bib'

f = open(name,"r", encoding='utf8')
text = f.readlines()
f.close()

first_comment = 0
for i, line in enumerate(text):
  if "@Comment" in line:
    first_comment = i
    break

text = text[first_comment:]

append = ""
for line in text:
  append += line

bib_data = parse_file(name)
clean_bib_data = pybtex.database.BibliographyData()

repeated_keys = []
query = ''
for k1 in bib_data.entries.keys():
  if "title" in bib_data.entries[k1].fields and k1 not in repeated_keys:
    t1 = bib_data.entries[k1].fields["title"]
    t1 = t1.lower().replace(":","").strip()
    for k2 in bib_data.entries.keys():
      if "title" in bib_data.entries[k2].fields and k1 not in repeated_keys:
        t2 = bib_data.entries[k2].fields["title"]
        t2 = t2.lower().replace(":","").strip()
        if t1 == t2 and k1 != k2:
          # bib_data.entries[k1].fields["__markedentry"] = "[tesse:4]"
          # bib_data.entries[k2].fields["__markedentry"] = "[tesse:4]"
          # print(t2)
          repeated_keys.append(k2)

print(f"{len(repeated_keys)} repeated entries found and marked")
for k in repeated_keys:
  bib_data.entries[k].fields["__markedentry"] = "[tesse:5]"

bib_data.to_file(name, "bibtex")

f = open(name,"a")
f.write(append)
f.close()


import datetime
import os
import xlrd
import xlsxwriter
from xlrd import XLRDError

from app.apis.utils.exception_helper import ExcelError
from config import Config

class XlrdReader(object):
    """
    读取excel，适用于.xls and .xlsx
    """
    def __init__(self,file):
        self.file=file
        self.titles=[]
        self.datas=[]

    def readSheetToList(self,sh_number=None):
        """
        读取sheet转换为list
        :param sh_number:
        :return:
        """
        # 打开文件
        try:
            workbook = xlrd.open_workbook(self.file)
            # 打开工作表
            if sh_number:
                worksheet = workbook.get_sheet(sh_number)
            else:
                worksheet = workbook.sheets()[0]
            # 获得所有行数
            nrows = worksheet.nrows
            for x in range(nrows):
                if x ==0:
                    self.titles=worksheet.row_values(x)
                else:
                    self.datas.append(worksheet.row_values(x))
        except XLRDError as ex:
            raise ExcelError(ex)

    def readAllToDict(self):
        """
        读取所有的sheet转换为dict
        :return:
        """
        try:
            # 打开文件
            workbook = xlrd.open_workbook(self.file)
            # 打开工作表
            worksheets = workbook.sheets()
            dict_sheet={}
            for worksheet in worksheets:
                # 获得所有行数
                nrows = worksheet.nrows
                list_data = []
                for x in range(nrows):
                    list_data.append(worksheet.row_values(x))
                    dict_sheet[worksheet.name]=list_data
            return dict_sheet
        except XLRDError as ex:
            raise ExcelError(ex)

class XlsxwriterWriter(object):
    """
    写入到excel，只适用于xlsx
    """
    def __init__(self):
        self.filepath=Config.EXPORT_PATH
        self.filename=datetime.datetime.now().strftime('%Y%m%d%H%M%S')+".xlsx"
        self.file=os.path.join(self.filepath,self.filename)
        self.workbook = None

    def open(self):
        self.workbook = xlsxwriter.Workbook(self.file)

    def close(self):
        if self.workbook:
            self.workbook.close()

    def writeSheetbyList(self,df,titles=None,sheetname=None):
        """
        写入list到xlsx
        :param datas:
        :param sheetname:
        :return:
        """
        try:
            if sheetname:
                worksheet = self.workbook.add_worksheet(sheetname)
            else:
                worksheet = self.workbook.add_worksheet()
            # add_format() 为当前workbook添加一个样式名为titleformat
            titleformat = self.workbook.add_format()
            titleformat.set_bold(bold=True)  # 设置粗体字
            titleformat.set_font_size(11)  # 设置字体大小为11
            titleformat.set_font_name('Microsoft yahei')  # 设置字体样式为雅黑
            titleformat.set_align('left')  # 设置水平居中对齐
            titleformat.set_align('vcenter')  # 设置垂直居中对齐
            if titles is None:
                titles=df.columns
            for index_col, value in enumerate(titles):
                worksheet.write(0, index_col, value, titleformat)
            # 再添加一个样式rowformat,将作为数据行的格式
            rowformat = self.workbook.add_format()
            rowformat.set_bold(bold=False)
            rowformat.set_font_size(10)
            rowformat.set_font_name('Microsoft yahei')
            rowformat.set_align('left')
            rowformat.set_align('vcenter')
            rowformat.set_text_wrap()  # 设置自动换行
            column_len=len(titles)
            worksheet.set_column(0, 1, 20)
            worksheet.set_column(1,column_len-1,12)
            worksheet.set_column(column_len-1, column_len, 35)
            for index_row, row in enumerate(df.values):
                # 文本对齐方式
                for index_col, value in enumerate(row):
                    worksheet.write(index_row+1, index_col, value, rowformat)
        except ValueError as ex:
            raise ExcelError(ex)


from FWCore.ParameterSet.VarParsing import VarParsing
opt = VarParsing ('analysis')
opt.parseArguments()

#outFileName = opt.outputFile
outFileName = 'Onia2MuMuPAT-mc.root'
#inFileNames = opt.inputFiles
inFileNames = '/store/relval/CMSSW_7_4_6_patch1/RelValBuJpsiK_13/GEN-SIM-RECO/MCRUN2_74_V9-v1/00000/7C57573C-891E-E511-A5FE-0025905A611C.root','/store/relval/CMSSW_7_4_6_patch1/RelValBuJpsiK_13/GEN-SIM-RECO/MCRUN2_74_V9-v1/00000/92DDC045-891E-E511-8DC8-0025905A6134.root'
nEvents = -1
#Global_Tag  = 'auto:run2_mc'
Global_Tag  = 'MCRUN2_74_V9'
MC          = True
Filter      = True

import FWCore.ParameterSet.Config as cms
process = cms.Process('PAT')

from HeavyFlavorAnalysis.Skimming.CompactSkim_cff import CompactSkim
CompactSkim(process,inFileNames,outFileName,nEvents,Global_Tag,MC,Filter)


distances = [(0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1)]

def getNeighbors(i, j):
	return [(i+di, j+dj) for (di, dj) in distances]

def valid(i, j, plot):
	m, n = len(plot), len(plot[0])
	return 0 <= i < m and 0 <= j < n

def getSize(i, j, plot, visited):
	if (i, j) in visited or plot[i][j] > 0:
		return 0
	result = 1
	visited.add((i,j))
	for r, c in getNeighbors(i, j):
		if not valid(r, c, plot) or (r,c) in visited:
			continue
		result += getSize(r, c, plot, visited)
	return result

def pondSizes(plot):
	m, n = len(plot), len(plot[0])
	visited = set()
	sizes = set()
	for i in range(m):
		for j in range(n):
			size = getSize(i, j, plot, visited)
			if (size > 0):
				sizes.add(size)
	return list(sizes)

plot = [[0, 2, 1, 0],
		[0, 1, 0, 1],
		[1, 1, 0, 1],
		[0, 1, 0, 1]]
print(pondSizes(plot))


import cv2
import time
import faceRecognition as fr
import os

sid = input("enter your SID : ")
os.mkdir(sid)

# initialise webcam
cap = cv2.VideoCapture(0)

path = os.getcwd()

count = 0
while count < 50:

    os.chdir(path)

    # This code initiates an infinite loop (to be broken later by a break statement), where we have ret and frame being
    # defined as the cap.read(). Basically, ret is a boolean regarding whether or not there was a return at all, at the
    # frame is each frame that is returned. If there is no frame, you wont get an error, you will get None.
    ret, test_img = cap.read()
    if not ret:
        continue
    faces, gray_img = fr.faceDetection(test_img)
    if len(faces) == 1:
        resized_img = cv2.resize(test_img, (1000, 700))
        cv2.imshow('face detection Tutorial ', resized_img)

        os.chdir(sid)

        cv2.imwrite(r"frame%d.jpg" % count, test_img)  # save frame as JPG file
        # print("img written!")
        count += 1
        if count % 10:
            print(count)
        if cv2.waitKey(10) == ord('q'):  # wait until 'q' key is pressed
            break

cap.release()
cv2.destroyAllWindows()


import sys

def change(i):
    if switch[i] == 0:
        switch[i] = 1
    else:
        switch[i] = 0

def boy(index):
    for i in range(index, n + 1, index):
        change(i)

def girl(index):
    left = index
    right = index
    change(index)
    while True:
        left -= 1
        right += 1
        if left < 1 or right > n or switch[left] != switch[right]:
            break
        change(left)
        change(right)

n = int(input())
switch = [-1]
switch.extend(list(map(int, sys.stdin.readline().rstrip().split())))
student_cnt = int(input())
for _ in range(student_cnt):
    gender, index = map(int, sys.stdin.readline().rstrip().split())
    if gender == 1:
        boy(index)
    else:
        girl(index)
answer = ''
for i in range(1, n + 1):
    answer += str(switch[i]) + ' '
    if len(answer) >= 40:
        print(answer)
        answer = ''
if len(answer) == 0:
    exit(0)
print(answer)