# -*- coding: utf-8 -*-
"""Chemical Engineering Design Library (ChEDL).

Utilities for process modeling. Copyright (C) 2020, Caleb Bell
<Caleb.Andrew.Bell@gmail.com> Permission is hereby granted, free of charge, to
any person obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction, including without
limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions: The
above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS
IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""

from __future__ import division
import sys
import importlib.util
import types
import numpy as np
import numba
import chemicals
import fluids
import fluids.numba
import re
normal = chemicals
import inspect

__all__ = []

__funcs = {}

numerics = fluids.numba.numerics
replaced = fluids.numba.numerics_dict.copy()

normal_fluids = fluids

orig_file = __file__
def transform_complete_chemicals(replaced, __funcs, __all__, normal, vec=False):
    cache_blacklist = set( ['Rachford_Rice_solution', 'Rachford_Rice_solution_LN2', 'Rachford_Rice_solution_polynomial',
              'Rachford_Rice_solution_numpy', 'Li_Johns_Ahmadi_solution', 'flash_inner_loop',
              'Rachford_Rice_solutionN', 'Rachford_Rice_solution2', 'flash_wilson',
              'Lastovka_Shaw_T_for_Hm', 'Lastovka_Shaw_T_for_Sm'])

    blacklist = set(['to_num'])

    __funcs.update(normal_fluids.numba.numbafied_fluids_functions.copy())
    new_mods = normal_fluids.numba.transform_module(normal, __funcs, replaced, vec=vec,
                                                    blacklist=blacklist,
                                                    cache_blacklist=cache_blacklist)
    if vec:
        conv_fun = numba.vectorize
    else:
        conv_fun = numba.jit

    to_change = ['utils.zs_to_ws', 'utils.ws_to_zs', 'utils.zs_to_Vfs',
             'utils.dxs_to_dxsn1', 'utils.dxs_to_dns', 'utils.dns_to_dn_partials',
             'utils.dxs_to_dn_partials', 'utils.dxs_to_dxsn1',
             'utils.d2xs_to_dxdn_partials', 'viscosity.Lorentz_Bray_Clarke',
             'viscosity.Herning_Zipperer', 'volume.COSTALD_mixture',
             'viscosity.Wilke_large', 'viscosity.Wilke_prefactored',
             'interface.Winterfeld_Scriven_Davis',

             'rachford_rice.Rachford_Rice_solution',
             'rachford_rice.Rachford_Rice_solution_LN2',
             'rachford_rice.Rachford_Rice_solution_numpy',
             'rachford_rice.Rachford_Rice_polynomial',
             'rachford_rice.Rachford_Rice_polynomial_3',
             'rachford_rice.Rachford_Rice_polynomial_4',
             'rachford_rice.Rachford_Rice_polynomial_5',
             'rachford_rice.Rachford_Rice_solution_polynomial',
             'rachford_rice.Rachford_Rice_numpy_err_fprime2',
             'rachford_rice.Li_Johns_Ahmadi_solution',
             'rachford_rice._Rachford_Rice_analytical_3',
             'rachford_rice.flash_inner_loop',
             'rachford_rice.Rachford_Rice_solution2',
             'rachford_rice.Rachford_Rice_solutionN',
             'rachford_rice.RRN_new_betas',
             'rachford_rice.Rachford_Rice_flashN_f_jac',
             'rachford_rice.Rachford_Rice_flash2_f_jac',
             'rachford_rice.Rachford_Rice_valid_solution_naive',
             'flash_basic.flash_wilson',
             'solubility.Henry_pressure_mixture',
             'critical.Chueh_Prausnitz_Tc',
             'critical.Chueh_Prausnitz_Vc',
             'thermal_conductivity.Lindsay_Bromley',
             'thermal_conductivity.DIPPR9I',
             'virial.Z_from_virial_density_form',
             ]
    normal_fluids.numba.transform_lists_to_arrays(normal, to_change, __funcs, cache_blacklist=cache_blacklist)

    for mod in new_mods:
        mod.__dict__.update(__funcs)
        try:
            __all__.extend(mod.__all__)
        except AttributeError:
            pass

transform_complete_chemicals(replaced, __funcs, __all__, normal, vec=False)

globals().update(__funcs)
globals().update(replaced)

__name__ = 'chemicals.numba'
__file__ = orig_file


from be_volumetria.core.config import UNKNOWN_CLASS_THRESHOLD, VOLUMETRIA_MODEL_SX, VOLUMETRIA_MODEL_DX
from be_volumetria.business_logic.utils import load_automl_model, reorder_predictions
from loguru import logger

import warnings
#suppressing deprecation warnings due to the use of 'imp' module
#deprecation warnings would break pytest tests
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    import tensorflow as tf
import numpy as np

class IncompatibleClassificationsError(Exception):
    pass

class VolumetriaInferenceModel:
    @classmethod
    def from_filepath(cls, model_path):
        """
            Creates an instance containing a model loaded from a filepath

            :param model_path: a filepath, can be a GCS path too

            :returns: VolumetriaInferenceModel instance
        """
        inference_function = load_automl_model(model_path)
        return cls(inference_function)

    def __init__(self, inference_function):
        """
            It is advisable to use a classmethod to create instances instead of this constructor
        """
        self.inference_function = inference_function
        self.debug = False

    def _debug(self, val):
        self.debug = val

    def infer_images(self, batch_of_image_bytes):
        """
            produces ordered predctions (by class alphabetical order) given a batch of images
            :param batch_of_image_bytes: batch of images in bytes format

            :returns: tuple of (ordered labels, ordered scores by corresponding labels)
        """
        pred = self.inference_function(
            image_bytes=tf.convert_to_tensor(batch_of_image_bytes),
            key=tf.convert_to_tensor('')
        )
        labels = pred["labels"].numpy()
        scores = pred["scores"].numpy()
        ordered_labels, ordered_scores = reorder_predictions(labels, scores)
        if self.debug:
            print(f"pred: {pred}")
            print(f"labels: {labels}")
            print(f"scores: {scores}")
            print(f"ordered_labels: {ordered_labels}")
            print(f"ordered_scores: {ordered_scores}")
        return ordered_labels, ordered_scores

class VolumetriaInferenceEnsamble:
    @classmethod
    def from_filepath(cls, model_path_sx, model_path_dx=None):
        """
            Creates an instance containing SX and DX models loaded from a filepath

            :param model_path_sx: a filepath, can be a GCS path too
            :param model_path_dx: a filepath, can be a GCS path too, if omitted,
                                  SX model will be used for DX inference

            :returns: VolumetriaInferenceEnsamble instance
        """
        vol_model_sx = VolumetriaInferenceModel.from_filepath(model_path_sx)
        if model_path_dx is None:
            # same model for DX and SX
            vol_model_dx = vol_model_sx
        else:
            vol_model_dx = VolumetriaInferenceModel.from_filepath(model_path_dx)
        return cls(vol_model_sx, vol_model_dx)

    @staticmethod
    def get_predicted_class(labels, scores, is_unknown_class=None, unknown_label=b'unknown', debug=False):
        """
            Extracts label and confidence from predictions typically
            coming from VolumetriaInferenceEnsamble.infer function

            :param labels: batch of labels
            :param scores:  batch of scores
            :param is_unknown_class: batch of booleans, if omitted, unknown class will be ignored
            :param debug: enables debug stdout prints, defaults to False

            :returns: tuple containing:
            - ordered_labels: batch of alphabetically oredered labels
            - ordered_scores: batch of scores associated with each label
            - unknown_class: batch of booleans, when true, the class is unknown
        """
        positional_predictions = scores.argmax(axis=1)
        predicted_labels = labels[np.arange(labels.shape[0]), positional_predictions]
        predicted_scores = scores[np.arange(scores.shape[0]), positional_predictions]
        if is_unknown_class is not None:
            predicted_labels[is_unknown_class] = unknown_label
        if debug:
            print(f"positional_predictions: {positional_predictions}")
            print(f"predicted_labels: {predicted_labels}")
            print(f"predicted_scores: {predicted_scores}")
        return predicted_labels, predicted_scores

    def __init__(self, vol_model_sx, vol_model_dx):
        """
            It is advisable to use a classmethod to create instances instead of this constructor
        """
        self.vol_model_sx = vol_model_sx
        self.vol_model_dx = vol_model_dx
        self.debug = False

    def _debug(self, val):
        self.vol_model_sx._debug(val)
        self.vol_model_dx._debug(val)
        self.debug = val

    def infer(self, batch_of_sx_image_bytes, batch_of_dx_image_bytes, unknown_class_threshold = 0.0, return_intermediate_results = False):
        """
            Performs ensambled batch prediction on SX and DX images

            :param batch_of_sx_image_bytes: an iterable containing SX image bytes
            :param batch_of_dx_image_bytes: an iterable containing DX image bytes
            :param unknown_class_threshold: score threshold under which the inferred
                                            class will be considered unknown
            :param return_intermediate_results: if true, also returns DX and SX results

            :returns: tuple containing
                      - ordered_labels: batch of alphabetically oredered labels
                      - ordered_scores: batch of scores associated with each label
                      - unknown_class: batch of booleans, when true, the class is unknown
                      - ordered_scores_sx: batch of SX scores associated with each label
                                           only returned if return_intermediate_results
                                           is True
                      - ordered_scores_dx: batch of DX scores associated with each label
                                           only returned if return_intermediate_results
                                           is True
        """
        ordered_labels_sx, ordered_scores_sx = self.vol_model_sx.infer_images(batch_of_sx_image_bytes)
        ordered_labels_dx, ordered_scores_dx = self.vol_model_dx.infer_images(batch_of_dx_image_bytes)
        if not (ordered_labels_sx == ordered_labels_dx).all():
            if self.debug:
                print(f"ordered_labels_sx: {ordered_labels_sx}")
                print(f"ordered_scores_sx: {ordered_scores_sx}")
                print(f"ordered_labels_dx: {ordered_labels_dx}")
                print(f"ordered_scores_dx: {ordered_scores_dx}")
            raise IncompatibleClassificationsError("DX and SX predictions are not compatible, please verify that SX and DX models produce the same labels")
        ordered_labels = ordered_labels_sx
        ensambled_scores = (ordered_scores_dx + ordered_scores_sx)/2
        is_unknown_class = ensambled_scores.max(axis=1) < unknown_class_threshold
        if self.debug:
            print(f"ordered_labels: {ordered_labels}")
            print(f"ordered_scores_sx: {ordered_scores_sx}")
            print(f"ordered_scores_dx: {ordered_scores_dx}")
            print(f"ensambled_scores: {ensambled_scores}")
            print(f"is_unknown_class: {is_unknown_class}")
        if return_intermediate_results:
            return ordered_labels, ensambled_scores, is_unknown_class, ordered_scores_sx, ordered_scores_dx
        else:
            return ordered_labels, ensambled_scores, is_unknown_class

class VolumetriaInferenceEnsambleHub:
    def __init__(self):
        logger.info(f"Loading models from {VOLUMETRIA_MODEL_SX}, {VOLUMETRIA_MODEL_DX}")
        self.model = VolumetriaInferenceEnsamble.from_filepath(VOLUMETRIA_MODEL_SX, VOLUMETRIA_MODEL_DX)
        logger.info("Model(s) loaded")

    def check_model(self):
        logger.info(f"checking if model is loaded")
        logger.info(f"{self.model}")
        return self.model

    def predict(self, sx_bytes: bytes, dx_bytes: bytes) -> dict:
        """
            Main function for volume prediction \n
            The predictions for the two images are ensambled and the result score is thresholded.
            If the score does not exceed the threshold, the 'unknown' class is returned

            :param sx_bytes: bytes of left image to be predicted
            :param sx_bytes: bytes of right image to be predicted

            :returns: dictionary containing labels and scores for thresholded ensamble class
        """
        logger.debug("Performing volume inference")
        ordered_labels, ensambled_scores, is_unknown_class, _, _ = self.model.infer(
            [sx_bytes], [dx_bytes], unknown_class_threshold = UNKNOWN_CLASS_THRESHOLD, return_intermediate_results = True
        )

        logger.debug(f"Packing results")
        #ensamble_predictions = dict(zip(ordered_labels[0],ensambled_scores[0]))
        labels_batch, scores_batch = VolumetriaInferenceEnsamble.get_predicted_class(
            ordered_labels, ensambled_scores, is_unknown_class
        )
        ensamble_thresholded_prediction = {
            "label": labels_batch[0],
            "score": scores_batch[0]
        }
        return ensamble_thresholded_prediction


from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect,Http404
from .models import Topic,Entry
from .forms import TopicForm, EntryForm
from django.urls import reverse
from django.contrib.auth.decorators import login_required

# # Create your views here.

def index(request):
    return render(request,'index.html')

@login_required
def topics(request):
    topics = Topic.objects.filter(owner=request.user).order_by('-date_added')
    context= {'topics':topics}
    print("topics run")
    return render(request,'topics.html',context)

@login_required
def topic(request, topic_id):
    topic = Topic.objects.get(id=topic_id)
    print("topic_id:",topic_id)
    print("topic:",topic)
    check_topic_owner(topic,request)
    entries = topic.entry_set.order_by('-date_added')
    context = {'topic': topic, 'entries': entries}
    return render(request, 'topic.html', context)

def check_topic_owner(topic,request):
    if topic.owner !=request.user:
        raise Http404

@login_required
def new_topic(request):
# """添加新主题"""
    if request.method != 'POST':
        # 未提交数据：创建一个新表单
        form = TopicForm()
    else:
        # POST提交的数据,对数据进行处理
        form = TopicForm(request.POST)
        if form.is_valid():
            new_topic = form.save(commit = False)
            new_topic.owner = request.user
            new_topic.save()
            return HttpResponseRedirect(reverse('learning_logs:topics'))
    context = {'form': form}
    return render(request, 'new_topic.html', context)

@login_required
def new_entry(request, topic_id):
# """在特定的主题中添加新条目"""
    topic = Topic.objects.get(id=topic_id)
    check_topic_owner(topic,request)
    if request.method != 'POST':
        # 未提交数据,创建一个空表单
        form = EntryForm()
    else:
        # POST提交的数据,对数据进行处理
        form = EntryForm(data=request.POST)
        if form.is_valid():
            new_entry = form.save(commit=False)
            new_entry.topic = topic
            new_entry.save()
            return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic_id]))
    context = {'topic': topic, 'form': form}
    return render(request, 'new_entry.html', context)

@login_required
def edit_entry(request,entry_id):
    entry = Entry.objects.get(id=entry_id)
    topic=entry.topic
    check_topic_owner(topic,request)
    if request.method!='POST':
        form=EntryForm(instance=entry)
    else:
        form=EntryForm(instance=entry,data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id]))
    context = {'entry':entry,'topic':topic,'form': form}
    return render(request,'edit_entry.html',context)


from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base
from contextlib import contextmanager
from .config import Config

engine = create_engine(Config.SQLALCHEMY_DATABASE_URI, echo=True)

Session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))

Base = declarative_base()

Base.metadata.create_all(bind=engine)

@contextmanager
def session_scope():
    """Provide a transactional scope around a series of operations."""
    session = Session()
    session.expire_on_commit = False
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.expunge_all()
        session.close()


#!/usr/bin/env python3
import RPi.GPIO as GPIO
from subprocess import call

# Initialise "keyboard"
NULL_CHAR = chr(0)
def write_report(report):
    with open('/dev/hidg0', 'rb+') as fd:
        fd.write(report.encode())

GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering

# GPIO headers for orange LEDs
oled1=10
oled2=12
oled3=16
oled4=18
oled5=22

# RGB LED, green header/red header/blue header
rled=24
gled=26
bled=19

# Toggle switches
switch1=29
switch2=31
switch3=33
switch4=35
switch5=37

# Big Red Button
bigredbutton=40

# Make lists out of all that nonsense
outputs = [ oled1, oled2, oled3, oled4, oled5, gled, rled, bled ]
inputs = [ switch1, switch2, switch3, switch4, switch5, bigredbutton ]

# Setup input/output GPIOs.
GPIO.setup (outputs, GPIO.OUT)
GPIO.setup (inputs, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

# Turn off all LEDs
#for led in outputs:
#    GPIO.output(led, GPIO.HIGH)

# Turn RGB LED to green.
GPIO.output(rled, GPIO.HIGH)
GPIO.output(bled, GPIO.HIGH)
GPIO.output(gled, GPIO.LOW)

print("Hello!")
# Loop forever, check buttons, etc.
while True:
    for switch in [0, 1, 2, 3, 4]:
        if GPIO.input(inputs[switch]) == GPIO.HIGH:
            GPIO.output(outputs[switch], GPIO.LOW)
        else:
            GPIO.output(outputs[switch], GPIO.HIGH)

    # Check how many switches are pressed.
    pressed=0
    for switch in [1, 2, 3, 4, 5]:
        if GPIO.input(inputs[switch-1]) == GPIO.HIGH:
            pressed=pressed+1

    # Set RBG to red if anything other than 1 switch is flipped.
    # Unless it's 5, then turn everything on. So, white.
    if (pressed == 1):
        GPIO.output(gled, GPIO.LOW)
        GPIO.output(rled, GPIO.HIGH)
        GPIO.output(bled, GPIO.HIGH)
    elif (pressed == 5):
        GPIO.output(gled, GPIO.LOW)
        GPIO.output(rled, GPIO.LOW)
        GPIO.output(bled, GPIO.LOW)
    else:
        GPIO.output(rled, GPIO.LOW)
        GPIO.output(gled, GPIO.HIGH)
        GPIO.output(bled, GPIO.HIGH)

    if GPIO.input(bigredbutton) == GPIO.HIGH:
        pressed=0;
        print ("BRB pressed.")
        while GPIO.input(bigredbutton) == GPIO.HIGH:
            donothing=1

        print ("BRB Relesaed")
        for switch in [1, 2, 3, 4, 5]:
            if GPIO.input(inputs[switch-1]) == GPIO.HIGH:
                pressed=pressed+1
#                print ("Switch " ,switch, " is on.")
#
#        print (pressed, " switches are on.")

        if (pressed == 5):
            print ("Shutting down...")
            GPIO.output(gled, GPIO.HIGH)
            GPIO.output(rled, GPIO.HIGH)
            GPIO.output(bled, GPIO.LOW)

            call("sudo init 0", shell=True)

        if (pressed == 1):

            # Switch 1, Win+L
            if (GPIO.input(switch1) == GPIO.HIGH):
                print ("Switch 1, pressing Win+L.")
                write_report(chr(8)+NULL_CHAR+chr(15)+NULL_CHAR*5)

            # Switch 2, Ctrl+Shift+Power (???)
            elif (GPIO.input(switch2) == GPIO.HIGH):
                print ("Switch 2, pressing Ctrl+Shift+Power.")
                write_report(chr(3)+NULL_CHAR+chr(102)+NULL_CHAR*5)

            # Switch 3, press space
            elif (GPIO.input(switch3) == GPIO.HIGH):
                print ("Switch 3, pressing space.")
                write_report(NULL_CHAR*2+chr(44)+NULL_CHAR*5)

            # Switch 4, press enter?
            elif (GPIO.input(switch4) == GPIO.HIGH):
                print ("Switch 4, pressing enter.")
                write_report(NULL_CHAR*2+chr(40)+NULL_CHAR*5)

            # Switch 5, press Esc
            elif (GPIO.input(switch5) == GPIO.HIGH):
                print ("Switch 5, pressing Esc.")
                write_report(NULL_CHAR*2+chr(41)+NULL_CHAR*5)

            # Release all keys
            write_report(NULL_CHAR*8)


# 상하좌우

n = int(input())
road = list(map(str, input().split()))
x , y = 1, 1
# 이동 경로 lrud
dx = [0,0,-1,1]
dy = [-1,1,0,0]
syn = ['L','R','U','D']

for i in range(len(road)):
    for j in range(len(syn)):
        if road[i] == syn[j]:
            nx = x + dx[j]
            ny = y + dy[j]
    if nx < 1 or nx > n or ny < 1 or ny > n:
        continue
    x, y = nx, ny

print(x,y)


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

# =============enthought library imports=======================
from __future__ import absolute_import

from chaco.api import PlotGrid, BarPlot, ArrayDataSource, \
    DataRange1D, LinearMapper, add_default_axes

# =============local library imports  ==========================
from pychron.graph.graph import container_factory
from pychron.graph.guide_overlay import GuideOverlay
from .regression_graph import RegressionGraph

# =============standard library imports ========================

class ResidualsGraph(RegressionGraph):
    """
    """
    xtitle = None

    def _plotcontainer_default(self):
        """
        """
        return self.container_factory()

    def container_factory(self):
        """
        """
        kw = {'type': 'v', 'stack_order': 'top_to_bottom'}
        for k, v in self.container_dict.items():
            kw[k] = v
        return container_factory(**kw)

    def _metadata_changed(self, obj, name, new):
        """
        """
        # super(ResidualsGraph, self)._metadata_changed(obj, name, new)
        self.update_residuals()

    def update_residuals(self):
        """
        """
        x, _y, res = self.calc_residuals()
        if x is not None:
            args = self._split_residual(x, res)
            for p, i, v in [(0, 0, 1), (1, 2, 3)]:
                plot = self.residual_plots[p]

                plot.index.set_data(args[i])
                plot.value.set_data(args[v])

    def _split_residual(self, x, res):
        """
        """
        resneg = []
        respos = []
        xneg = []
        xpos = []
        for i, ri in enumerate(res):
            if ri <= 0:
                xneg.append(x[i])
                resneg.append(ri)
            else:
                xpos.append(x[i])
                respos.append(ri)

        return xneg, resneg, xpos, respos

    def add_datum(self, *args, **kw):
        """
        """
        super(ResidualsGraph, self).add_datum(*args, **kw)
        self.update_residuals()

    def new_plot(self, *args, **kw):
        self.xtitle = kw['xtitle'] if 'xtitle' in kw else None
        return super(ResidualsGraph, self).new_plot(*args, **kw)

    def new_series(self, x=None, y=None, plotid=0, **kw):
        """
        """

        plot, scatter, _line = super(ResidualsGraph, self).new_series(x=x, y=y, plotid=plotid, **kw)
        for underlay in plot.underlays:
            if underlay.orientation == 'bottom':
                underlay.visible = False
                underlay.padding_bottom = 0
        plot.padding_bottom = 0

        x, y, res = self.calc_residuals(plotid=plotid)

        ressplit = self._split_residual(x, res)
        resneg = ArrayDataSource(ressplit[1])
        xneg = ArrayDataSource(ressplit[0])
        respos = ArrayDataSource(ressplit[3])
        xpos = ArrayDataSource(ressplit[2])

        yrange = DataRange1D(ArrayDataSource(res))

        ymapper = LinearMapper(range=yrange)

        container = container_factory(type='o',
                                      padding=[50, 15, 0, 30],
                                      height=75,
                                      resizable='h')
        bar = BarPlot(index=xneg,
                      value=resneg,
                      index_mapper=scatter.index_mapper,
                      value_mapper=ymapper,
                      bar_width=0.2,
                      line_color='blue',
                      fill_color='blue',

                      border_visible=True)

        #        left_axis = PlotAxis(bar, orientation = 'left')
        # bottom_axis=PlotAxis(bar,orientation='bottom')

        kw = dict(vtitle='residuals')
        if self.xtitle:
            kw['htitle'] = self.xtitle
        add_default_axes(bar, **kw)
        hgrid = PlotGrid(mapper=ymapper,
                         component=bar,
                         orientation='horizontal',
                         line_color='lightgray',
                         line_style='dot')

        bar.underlays.append(hgrid)
        #        bar.underlays.append(left_axis)
        #        bar.underlays.append(bottom_axis)

        bar2 = BarPlot(index=xpos,
                       value=respos,
                       index_mapper=scatter.index_mapper,
                       value_mapper=ymapper,
                       bar_width=0.2,
                       line_color='green',
                       fill_color='green',
                       # bgcolor = 'green',

                       resizable='hv',
                       border_visible=True,
                       # padding = [30, 5, 0, 30]
                       )
        bar2.overlays.append(GuideOverlay(bar2, value=0, color=(0, 0, 0)))
        bar2.underlays.append(hgrid)
        container.add(bar)
        container.add(bar2)

        # container.add(PlotLabel('foo'))

        self.residual_plots = [bar, bar2]
        self.plotcontainer.add(container)

# ============= EOF =====================================


import discord
from discord.ext import commands
from .utils.chat_formatting import *
from .utils.dataIO import fileIO
from .utils import checks
from __main__ import send_cmd_help
from urllib import parse
import aiohttp
import os
import asyncio

try:   # check if pony cog is installed
    from .special_pony import Pony
    ponyAvailable = True
except ImportError:
    ponyAvailable = False

try:   # check if derpisafe cog is installed
    from .imagesafe import create_derpi_embed
    derpiAvailable = True
except ImportError:
    derpiAvailable = False

class Ponysub:
    def __init__(self, bot):
        self.bot = bot
        self.data = fileIO("data/ponysub/data.json", "load")
        self.sub_task = bot.loop.create_task(self.ponysub_service())

    @commands.group(name='ponysub',no_pm=True, pass_context=True)
    @checks.admin_or_permissions(manage_server=True)
    async def ponysub(self, ctx):
        """Manages subscription to a search string on derpibooru"""
        if ctx.invoked_subcommand is None:
            await send_cmd_help(ctx)

    @ponysub.command(name='add', pass_context=True)
    @checks.admin_or_permissions(manage_server=True)
    async def _add(self, ctx, sub_name : str, channel : discord.Channel, * , search_string : str=""):
        """Adds a new search string to check for updates:

        [p]ponysub add <name> #<channel> <search string>"""
        server = ctx.message.server
        sub_name = sub_name.lower().capitalize()
        new_sub = { 'name' : sub_name, 'channel' : channel.id, 'search string' : search_string, 'enabled' : False, 'latest image' : "1980" }
        if server.id not in self.data:
            self.data[server.id] = []
        else:
            if find_sub(self, server, sub_name):
                await self.bot.say("Name %s is already used!" % ( sub_name ))
                return
        self.data[server.id].append( new_sub )
        fileIO("data/ponysub/data.json", "save", self.data)
        await self.bot.say("Added %s to subscriptions! Don't forget to enable it!" % ( sub_name ))

    @ponysub.command(name='list', pass_context=True)
    async def _list(self, ctx, channel : discord.Channel=False):
        """Lists all subscriptions:

        [p]ponysub list"""
        server = ctx.message.server
        msg = "Listing:\n"
        if server.id not in self.data:
            msg += "No subscriptions in server!\n"
        else:
            for a in range(len(self.data[server.id])):
                if channel:
                    if channel.id != self.data[server.id][a]['channel']:
                        continue
                msg += "```Markdown\n"
                if self.data[server.id][a]['enabled']:
                    msg += "# %s: Enabled\n" % (self.data[server.id][a]['name'])
                else:
                    msg += "# %s: Disabled\n" % (self.data[server.id][a]['name'])
                msg += "Channel: #%s\n" % ( find_channel( self, server, self.data[server.id][a]['channel'] ).name )
                msg += "Search String: %s\n" % (self.data[server.id][a]['search string'])
                msg += "```\n"
        await self.bot.say(msg)

    @ponysub.command(name='toggle', pass_context=True)
    @checks.admin_or_permissions(manage_server=True)
    async def _toggle(self, ctx, sub_name):
        """Enable or disable a subscription

        [p]ponysub toggle <name>"""
        server = ctx.message.server
        sub_number = find_sub(self, server, sub_name)
        if type(sub_number) is bool:
            await self.bot.say("Can't find %s!" % (sub_name))
            return
        if self.data[server.id][sub_number]['enabled']:
            self.data[server.id][sub_number]['enabled'] = False
            fileIO("data/ponysub/data.json", "save", self.data)
            await self.bot.say( "Subscription %s now disabled!" % (self.data[server.id][sub_number]['name']))
            return
        else:
            search = "https://derpibooru.org/search.json?q="
            search += parse.quote_plus(self.data[server.id][sub_number]['search string'])
            search += "&filter_id=56027"
            try:
                async with aiohttp.get(search) as r:
                    website = await r.json()
            except:
                return await self.bot.say("Error.")
            if website['total'] == 0:
                await self.bot.say("There are no images matching this subscription!")
                return
            self.data[server.id][sub_number]['latest image'] = website['search'][0]['created_at']
            self.data[server.id][sub_number]['enabled'] = True
            fileIO("data/ponysub/data.json", "save", self.data)
            await self.bot.say( "Subscription %s now enabled!" % (self.data[server.id][sub_number]['name']))

    @ponysub.command(name='refresh', pass_context=True)
    @checks.admin_or_permissions(manage_server=True)
    async def _refresh(self, ctx, refresh_time : int):
        """Set the refresh time (how often to check the server in minutes)

        [p]ponysub refresh <time>"""
        server = ctx.message.server
        if refresh_time < 5:
            await self.bot.say("You can only enter a time over 5 minutes.")
            return
        self.data['refresh'] = refresh_time
        await self.bot.say( "Refresh time set to %i minutes." % (refresh_time))
        fileIO("data/ponysub/data.json", "save", self.data)

    @ponysub.command(name='del', pass_context=True)
    @checks.admin_or_permissions(manage_server=True)
    async def _delete(self, ctx, sub_name):
        """Deletes a subscription

        [p]ponysub del <name>"""
        server = ctx.message.server
        sub_number = find_sub(self, server, sub_name)
        if type(sub_number) is bool:
            await self.bot.say("Can't find %s!" % (sub_name))
            return
        if server.id not in self.data:
            await self.bot.say("No subscriptions for this server!")
            return
        await self.bot.say('Type **delete** to actually delete the subscription.')
        message = await self.bot.wait_for_message(timeout=60, author=ctx.message.author)
        if not message:
            return await self.bot.say("Aborted.")
        if message.content.lower() != 'delete':
            return await self.bot.say("Aborted.")
        self.data[server.id].remove( self.data[server.id][sub_number] )
        if not self.data[server.id]:
            del self.data[server.id]
        fileIO("data/ponysub/data.json", "save", self.data)
        await self.bot.say( "Deleted %s subscription." % (sub_name))

    async def ponysub_service(self):
        """Trigger loop"""
        await self.bot.wait_until_ready()
        try:
            while True:
                try:
                    await self.spam_looper()
                except asyncio.CancelledError:
                    raise
                except:
                    pass
                if type(self.data['refresh']) is int:
                    if self.data['refresh'] < 5:
                        self.data['refresh'] = 5
                        fileIO("data/ponysub/data.json", "save", self.data)
                else:
                    self.data['refresh'] = 5
                    fileIO("data/ponysub/data.json", "save", self.data)
                await asyncio.sleep(self.data['refresh'] * 60)
                print("Ponysub service tick.")
        except asyncio.CancelledError:
            pass

    def __unload(self):
        self.sub_task.cancel()

    async def spam_looper(self):
        self.filters = fileIO("data/pony/filters.json", "load")
        if not self.data:
            return
        for server, sub_data in self.data.items():
            if server == 'refresh':
                continue
    #        if type(sub_data) is not 'list':
    #            continue
            server = find_server(self, server)
            for sub_number in range(len(sub_data)):
                if not self.data[server.id][sub_number]['enabled']:
                    continue
                image_list = []
                search = "https://derpibooru.org/search.json?q="
                tagSearch = ""
                tagSearch += self.data[server.id][sub_number]['search string']
                tagSearch += ",created_at.gt:%s" % (self.data[server.id][sub_number]['latest image'])
                if server.id in self.filters:
                    if self.filters[server.id] != []:
                        tagSearch += ", "
                    tagSearch += ", ".join(self.filters[server.id])
                else:
                    tagSearch += ", "
                    tagSearch += ", ".join(self.filters["default"])
                search += parse.quote_plus(tagSearch)
                search += "&filter_id=56027"
                page_counter = 1
                while True:
                    try:
                        async with aiohttp.get(search + "&page=%i" % (page_counter)) as r:
                            website = await r.json()
                    except:
                        return await self.bot.say("Error.")
                    if not website['search']:
                        break
                    for key in range(len(website['search'])):
                        image_list.append(website['search'][key]['id'])
                    page_counter += 1
                if 'duplicate_reports' in website:
                    dupe_found = False
                    for reports in website['duplicate_reports']:
                        if 'state' in reports and reports['state'] == 'open' and 'reason' in reports and reports['reason'].lower() == 'automated perceptual dedupe match':
                            dupe_found = True
                            break
                    if dupe_found:
                        continue
                for key in range(len(image_list)):
                    await self.fetch_image(ctx=False, randomize=False, tags=[ "ID:%s" % (image_list[key]) ], server=server.id, channel=self.data[server.id][sub_number]['channel'])
                search = "https://derpibooru.org/search.json?q="
                search += parse.quote_plus(self.data[server.id][sub_number]['search string'])
                search += "&filter_id=56027"
                try:
                    async with aiohttp.get(search) as r:
                        website = await r.json()
                except:
                    return
                if website['total'] == 0:
                    return
                self.data[server.id][sub_number]['latest image'] = website['search'][0]['created_at']
                self.data[server.id][sub_number]['enabled'] = True
                fileIO("data/ponysub/data.json", "save", self.data)

    async def fetch_image(self, ctx, randomize, tags, server : str="", channel : str=""):

        if server != "" and channel != "":
            server = find_server(self, server)
            channel = find_channel(self, server, channel)
        else:
            server = ctx.message.server
        self.filters = fileIO("data/pony/filters.json", "load")
        self.settings = fileIO("data/pony/settings.json", "load")

        # Initialize base URL
        search = "https://derpibooru.org/search.json?q="
        tagSearch = ""

        # Apply tags to URL
        if tags:
            tagSearch += "{} ".format(" ".join(tags))
        if server.id in self.filters:
            if self.filters[server.id] != [] and tags:
                tagSearch += ", "
            tagSearch += ", ".join(self.filters[server.id])
        else:
            if tags:
                tagSearch += ", "
            tagSearch += ", ".join(self.filters["default"])
        search += parse.quote_plus(tagSearch)

        # Apply Derpibooru's "Everything" filter

        search += "&filter_id=56027"

        # Inform users about image retrieving
        if channel:
            message = await self.bot.send_message(channel, "Fetching pony image...")
        else:
            message = await self.bot.say("Fetching pony image...")

        # Fetch and display the image or an error
        try:
            async with aiohttp.get(search) as r:
                website = await r.json()
            if website["search"] != []:
                website = website["search"][0]
                imageURL = "https:{}".format(website["image"])
            else:
                return await self.bot.edit_message(message, "Your search terms gave no results.")
        except:
            return await self.bot.edit_message(message, "Error.")

        # Edits the pending message with the results
        if derpiAvailable:
            return await self.bot.edit_message(message, "Image found: <https://derpibooru.org/{}>".format(website["id"]), embed=await create_derpi_embed(website))
        else:
            return await self.bot.edit_message(message, imageURL)

def find_sub(self, server, sub_name):
    sub_name = sub_name.lower().capitalize()
    if server.id not in self.data:
        return False
    for a in range(len(self.data[server.id])):
        if self.data[server.id][a]['name'] == sub_name:
            return a
    return False

def find_channel(self, server, channel_id):
    return discord.utils.get(self.bot.get_all_channels(), server__name=server.name, id=channel_id)

def find_server(self, server):
    return self.bot.get_server(server)

def check_folder():
    if not os.path.exists("data/ponysub"):
        print("Creating data/pony folder...")
        os.makedirs("data/ponysub")

def check_files():
    data_default = {"refresh":10}

    if not fileIO("data/ponysub/data.json", "check"):
        print("Creating default ponysub data.json...")
        fileIO("data/ponysub/data.json", "save", data_default)
    else:
        data = fileIO("data/ponysub/data.json", "load")

def setup(bot):
    if ponyAvailable:
        check_folder()
        check_files()
        bot.add_cog(Ponysub(bot))
    else:
        raise RuntimeError("You need to install the pony cog from https://github.com/Alzarath/Booru-Cogs")


n= int(input("alunos: "))
x=n
notag= 0
while n>0:
    nota= float(input("nota: "))
    n= n-1
    if nota>11 or nota<0:
        print("nota inválida")
    notag= notag + nota
    media= notag/x
print(media)


CELERY_BROKER_URL = 'redis://127.0.0.1:6379/1'
CELERY_RESULT_BACKEND = CELERY_BROKER_URL
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'

BROKER_POOL_LIMIT = 10
BROKER_CONNECTION_TIMEOUT = 10

CELERY_SEND_EVENTS = True
CELERY_TASK_RESULT_EXPIRES = 3 * 86400
CELERY_IGNORE_RESULT = True
CELERY_ACKS_LATE = True


from copy import deepcopy
def check(x):
    s = []
    d, m = divmod(x, 8)
    for i in range(8):
        s.append(8*i + m)
        s.append(8*d + i)

    for d in [-9, 7]:
        y = deepcopy(x)
        while 0 <= y+d <= 63 and (y%8) > 0:
            y += d
            s.append(y)
    for d in [9, -7]:
        y = deepcopy(x)
        while 0 <= y+d <= 63 and (y%8) < 7:
            y += d
            s.append(y)
    return s

def dfs(se, qu):
    if len(qu) == 8:
        return qu
    #print(len(qu))

    for i in range(64):
        if i in se:
            continue
        ns = set(check(i))
        if len(qu & ns) == 0:
            res = dfs(se|ns, qu|set([i]))
            if not res is None:
                return res

C = []
for _ in range(8):
    C += list(input())

searched = set()
queens = [i for i in range(64) if C[i] == "Q"]

for i in range(3):
    ns = set(check(queens[i]))
    if len(set(queens[:i]) & ns):
        print("No Answer")
        break
    searched = searched | ns
else:
    queens = set(queens)
    qu = dfs(searched, queens)
    if qu is None:
        print("No Answer")
    else:
        ans = ["."]*64
        for q in qu:
            ans[q] = "Q"
        for i in range(8):
            print("".join(ans[i*8:(i+1)*8]))


import threading
from apscheduler.schedulers.background import BackgroundScheduler
from django.shortcuts import render
from schedule import Scheduler
import schedule
import time
import random
from . import main
from . import settings
from . import var_defs
from . import ogamu
from django.http import HttpResponse
from django.contrib.auth.models import User, auth
from django.shortcuts import render,redirect
from django.contrib import messages
import apscheduler.schedulers.blocking
import math

bot_is_on = False
scheduler = BackgroundScheduler()
job_autosave = None
job_expo = None
job_farm = None
text_id = 0
output_msg = ""
farming_an = False
init = True
first_farm = True
all_farm_planets = var_defs.AllFarmPlanets()
current_state = var_defs.FarmState
analyse_timer = 0
farm_timer = 0.5
random_timer = 30
idle_timer = 5
idle_counter = 0

def output_text(text):
    global output_msg
    global text_id
    output_msg = "Msg ID: "+str(text_id)+" > "+text
    text_id = text_id+1

def autosave_tick():
    if bot_is_on:
        print("Running autosave...")
        main.autoSave()

def expo_tick():
    if(settings.expo_an and bot_is_on):
        main.startExpo()
        print("Running expo...")

counter_bot = 0
counter_rand = random.randint(6, 14)
def farm_tick():
    global counter_bot
    global counter_rand
    global current_state
    global analyse_timer
    if(farming_an and bot_is_on):
        print(current_state)
        current_farm_planet = all_farm_planets.get_current_farm_planet()
        print("Running farm on...: "+current_farm_planet.name)
        if(not all_farm_planets.skip_if_not_allowed(current_farm_planet)):
            if(current_state == var_defs.FarmState.Scan and not all_farm_planets.all_already_scanned()
                    and not current_farm_planet.already_scanned):
                print("Scan Modus")
                main.scan_modus()
            elif (current_state == var_defs.FarmState.Scan and not all_farm_planets.all_already_scanned()
                    and current_farm_planet.already_scanned):
                all_farm_planets.next_farm_planet()
                print("SWITCH BACK!")
            elif (current_state == var_defs.FarmState.Scan and all_farm_planets.all_already_scanned()):
                current_state = var_defs.FarmState.Spy
                counter_bot = 0
                counter_rand = random.randint(6, 14)
            if (current_state == var_defs.FarmState.Spy and counter_bot > counter_rand):
                main.spy_modus()
                counter_bot = 0
                counter_rand = random.randint(6, 14)
            elif current_state == var_defs.FarmState.Spy:
                counter_bot = counter_bot + 1
            if (current_state == var_defs.FarmState.Analyse):
                analyse_timer = analyse_timer + 1
                print("Anal.Timer: "+str(analyse_timer))
                if(analyse_timer > 200):
                    print("Anaaaal!")
                    main.analyse_modus()
            if (current_state == var_defs.FarmState.Attack and counter_bot > counter_rand):
                print("Attack modudeska")
                main.attack_modus()
                counter_bot = 0
                counter_rand = random.randint(6, 14)
            elif current_state == var_defs.FarmState.Attack:
                counter_bot = counter_bot + 1
            if (current_state == var_defs.FarmState.Idle):
                print("Idlemode")
                main.go_out_of_idle()

def start_job():
    print("START!")
    global job_autosave
    global job_expo
    global job_farm
    job_autosave = scheduler.add_job(autosave_tick, 'interval', seconds=45 , id='autosave')
    job_expo = scheduler.add_job(expo_tick, 'interval', seconds=60, id='expo')
    job_farm = scheduler.add_job(farm_tick,'interval', seconds=farm_timer, id='farm')
    try:
        scheduler.start()
    except:
        pass

def stop_job():
    print("STOP!")
    scheduler.remove_job('autosave')
    scheduler.remove_job('expo')
    scheduler.remove_job('farm')

def home(request):
    global init
    global current_state
    if(init):
        var_defs.all_planets = ogamu.get_planets()
        for planet in var_defs.all_planets:
            planet['isFarming'] = False
        init = False
        current_state = var_defs.FarmState.Scan

    return render(request, 'home_norma.html', {'bot_on': bot_is_on, 'kt_exp': settings.kleine_transporter_exp,
                                               'gt_exp': settings.große_transporter_exp
        , 'lj_exp': settings.leichte_jaeger_exp, 'sj_exp': settings.schwere_jaeger_exp, 'xer_exp': settings.kreuzer_exp
        , 'ss_exp': settings.schlachtschiff_exp, 'sxer_exp': settings.schlachtkreuzer_exp,
                                               'reaper_exp': settings.reaper_exp
        , 'spy_exp': settings.spio_sonde_exp, 'path_exp': settings.pathfinder_exp, 'exp_an_exp': settings.expo_an
        , 'output_text': output_msg, "farm_on": farming_an, "farm_planets": var_defs.all_planets,
                                               "res_slot": settings.slots_reserviert,
                                               "exp_slot": settings.expo_reserviert})

#

def toggle_bot(request):
    global bot_is_on
    global farming_an
    if request.POST['bot_status'] == "bot_an":
        if not bot_is_on:
            bot_is_on = True
            ogamu.log_in()
            start_job()
            output_text("Bot ist an!")
        else:
            output_text("Bot ist bereits an!")
    else:
        if bot_is_on:
            bot_is_on = False
            ogamu.log_out()
            stop_job()
            output_text("Bot ist aus!")
        else:
            output_text("Bot ist bereits aus!")
    settings.slots_reserviert = request.POST['reserve_slots']
    settings.expo_reserviert = request.POST['exp_slots']

    return render(request, 'home_norma.html', {'bot_on': bot_is_on, 'kt_exp': settings.kleine_transporter_exp,
                                               'gt_exp': settings.große_transporter_exp
        , 'lj_exp': settings.leichte_jaeger_exp, 'sj_exp': settings.schwere_jaeger_exp, 'xer_exp': settings.kreuzer_exp
        , 'ss_exp': settings.schlachtschiff_exp, 'sxer_exp': settings.schlachtkreuzer_exp,
                                               'reaper_exp': settings.reaper_exp
        , 'spy_exp': settings.spio_sonde_exp, 'path_exp': settings.pathfinder_exp, 'exp_an_exp': settings.expo_an
        , 'output_text': output_msg, "farm_on": farming_an, "farm_planets": var_defs.all_planets,
                                               "res_slot": settings.slots_reserviert ,"exp_slot": settings.expo_reserviert })

def collect(request):
    global bot_is_on
    global farming_an
    if bot_is_on:
        if not request.POST['collect1'] == "" and not request.POST['collect2'] == ""  and not request.POST['collect3'] == "" :
            if int(request.POST['collect1']) >= 1 and int(request.POST['collect1']) <= 6:
                if int(request.POST['collect2']) >= 1 and int(request.POST['collect2']) <= 499:
                    if int(request.POST['collect3']) >= 1 and int(request.POST['collect3']) <= 15:
                        gal = request.POST['collect1']
                        sys = request.POST['collect2']
                        pos = request.POST['collect3']
                        moon = False
                        if(request.POST.get('collect4',False) == "on"):
                            moon = True
                        celest = ogamu.get_celest_by_pos(gal, sys,pos,moon)
                        selected_planis = []
                        allowed_slots = ogamu.get_allowed_slots()
                        for planet in var_defs.all_planets:
                            if request.POST.get(planet["Name"], False) == "on" and not planet["Name"] == celest["Name"]:
                                selected_planis.append(planet["Name"])
                        if(len(selected_planis) <= allowed_slots):
                            if (not celest is None):
                                output_text("Sammeln auf P:" + str(gal) + ":" + str(sys) + ":" + str(pos))
                                main.gather_all_res(gal, sys, pos,selected_planis,moon)
                            else:
                                output_text("Diese Koords gibt es nicht!")
                        else:
                            output_text("Du hast nicht genug freie Slots!")
                    else:
                        output_text("Error: Planizahl ist außerhalb des Wertebereichs")
                else:
                    output_text("Error: Syszahl ist außerhalb des Wertebereichs")
            else:
                output_text("Error: Galazahl ist außerhalb des Wertebereichs")
        else:
            output_text("Error: Zahlenfeld vergessen?")
    else:
        output_text("Bot ist aus!")

    return render(request, 'home_norma.html', {'bot_on': bot_is_on, 'kt_exp': settings.kleine_transporter_exp,
                                               'gt_exp': settings.große_transporter_exp
        , 'lj_exp': settings.leichte_jaeger_exp, 'sj_exp': settings.schwere_jaeger_exp, 'xer_exp': settings.kreuzer_exp
        , 'ss_exp': settings.schlachtschiff_exp, 'sxer_exp': settings.schlachtkreuzer_exp,
                                               'reaper_exp': settings.reaper_exp
        , 'spy_exp': settings.spio_sonde_exp, 'path_exp': settings.pathfinder_exp, 'exp_an_exp': settings.expo_an
        , 'output_text': output_msg, "farm_on": farming_an, "farm_planets": var_defs.all_planets,
                                               "res_slot": settings.slots_reserviert,
                                               "exp_slot": settings.expo_reserviert})

def set_expo(request):
    global farming_an
    kt = request.POST['exp_kt']
    gt = request.POST['exp_gt']
    lj = request.POST['exp_lj']
    sj = request.POST['exp_sj']
    xer = request.POST['exp_xer']
    ss = request.POST['exp_ss']
    sxer = request.POST['exp_sxer']
    reaper = request.POST['exp_reaper']
    spy = request.POST['exp_spy']
    path = request.POST['exp_path']
    exp_an = False
    if (request.POST.get('exp_an',False) == "on"):
        exp_an = True
        output_text("Expo Funktion eingeschaltet!")
    else:
        output_text("Expo Funktion ausgeschaltet!!")
    settings.kleine_transporter_exp = int(kt)
    settings.große_transporter_exp = int(gt)
    settings.leichte_jaeger_exp = int(lj)
    settings.schwere_jaeger_exp = int(sj)
    settings.kreuzer_exp = int(xer)
    settings.schlachtschiff_exp = int(ss)
    settings.schlachtkreuzer_exp = int(sxer)
    settings.reaper_exp = int(reaper)
    settings.spio_sonde_exp = int(spy)
    settings.pathfinder_exp = int(path)
    settings.expo_an = exp_an
    if(request.POST.get('manuel_senden', False)):
        main.startExpo()
        output_text("Expo Settings gespeichert und gestartet!")
    else:
        output_text("Expo gestartet!")

    return render(request, 'home_norma.html', {'bot_on': bot_is_on, 'kt_exp': settings.kleine_transporter_exp,
                                               'gt_exp': settings.große_transporter_exp
        , 'lj_exp': settings.leichte_jaeger_exp, 'sj_exp': settings.schwere_jaeger_exp, 'xer_exp': settings.kreuzer_exp
        , 'ss_exp': settings.schlachtschiff_exp, 'sxer_exp': settings.schlachtkreuzer_exp,
                                               'reaper_exp': settings.reaper_exp
        , 'spy_exp': settings.spio_sonde_exp, 'path_exp': settings.pathfinder_exp, 'exp_an_exp': settings.expo_an
        , 'output_text': output_msg, "farm_on": farming_an, "farm_planets": var_defs.all_planets,
                                               "res_slot": settings.slots_reserviert,
                                               "exp_slot": settings.expo_reserviert})

id_celest = 0
def farming(request):
    global id_celest
    global all_farm_planets
    global farming_an
    global current_state
    global first_farm
    if_added = False
    at_least_one = False

    for planet in var_defs.all_planets:
        if request.POST.get(planet["Name"],False) == "on":
            if(not all_farm_planets.already_exits(planet["Name"])):
                moon = True
                id_celest = planet["ID"]
                if(planet["Moon"]==None):
                    moon = False
                else:
                    id_celest = ogamu.get_celest_ID3(planet)
                    print(id_celest)
                (gal,sys,pos)= ogamu.get_coords(planet)
                planet['isFarming'] = True

                all_farm_planets.add_planet(id_celest,planet["Name"],gal,sys,pos,moon)
                print("Wurde der Datenbank hinzugefügt: "+planet["Name"])
                farm_plani = all_farm_planets.get_planet_by_name(planet["Name"])
                farm_plani.init_scan_vars()
                if_added = True
                at_least_one = True
            else:
                print("Ist schon in der Datenbank! Turn On!: "+planet["Name"])
                farm_plani = all_farm_planets.get_planet_by_name(planet["Name"])
                current_state == var_defs.FarmState.Scan
                planet['isFarming'] = True
                at_least_one = True
                farm_plani.turn_on()
        else:
            if(all_farm_planets.already_exits(planet["Name"])):
                planet['isFarming'] = False
                farm_plani = all_farm_planets.get_planet_by_name(planet["Name"])
                if(all_farm_planets.get_current_farm_planet().name == planet["Name"]):
                    current_state == var_defs.FarmState.Scan
                farm_plani.turn_off()
                print("Ist schon in der Datenkbank! Turn off:!  "+planet["Name"])
    if(if_added == True and first_farm == True):
        current_state = var_defs.FarmState.Scan
        first_farm = False
        print("Scan started for the first time!")
    if request.POST.get("farm_on", False) and at_least_one:
        farming_an = True
    else:
        farming_an = False

    return render(request, 'home_norma.html', {'bot_on': bot_is_on, 'kt_exp': settings.kleine_transporter_exp,
                                               'gt_exp': settings.große_transporter_exp
        , 'lj_exp': settings.leichte_jaeger_exp, 'sj_exp': settings.schwere_jaeger_exp, 'xer_exp': settings.kreuzer_exp
        , 'ss_exp': settings.schlachtschiff_exp, 'sxer_exp': settings.schlachtkreuzer_exp,
                                               'reaper_exp': settings.reaper_exp
        , 'spy_exp': settings.spio_sonde_exp, 'path_exp': settings.pathfinder_exp, 'exp_an_exp': settings.expo_an
        , 'output_text': output_msg, "farm_on": farming_an, "farm_planets": var_defs.all_planets,
                                               "res_slot": settings.slots_reserviert,
                                               "exp_slot": settings.expo_reserviert})


# time o(nlogn)
class Solution:
    def avoidFlood(self, rains):
        import heapq
        from collections import defaultdict
        h = []
        res = []
        heapq.heapify(h)
        dic = defaultdict(list)
        to_empty = []
        heapq.heapify(to_empty)
        res = [-1] * len(rains)

        for idx, rain in enumerate(rains):
            dic[rain].append(idx)

        for i , rain in enumerate(rains):
            if rain != 0:
                if dic[rain] and dic[rain][0] < i: # full
                    return []
                if dic[rain] and len(dic[rain]) > 1: # can put into waiting list
                    next_rain = dic[rain][1]
                    heapq.heappush(to_empty, next_rain)
            else: # needs to pop
                if to_empty: # can pop
                    res[i] = rains[heapq.heappop(to_empty)]
                    dic[res[i]].pop(0)
                else: # nothing to pop
                    res[i] = 1
        return res

if __name__ == "__main__":
    rains = [1,2,0,2,3,0,1]
    output = [-1,-1,2,-1,-1,1,-1]
    sol = Solution()
    print(sol.avoidFlood(rains))

    # Input:
    rains = [1,2,3,4]
    #Output: [-1,-1,-1,-1]
    sol = Solution()
    #print(sol.avoidFlood(rains))

    # Input:
    rains = [1,2,0,0,2,1]
    # Output: [-1,-1,2,1,-1,-1]
    sol = Solution()
    #print(sol.avoidFlood(rains))

    # Input:
    rains = [1,2,0,1,2]
    # Output: []
    sol = Solution()
    #print(sol.avoidFlood(rains))

    # Input:
    rains = [69,0,0,0,69]
    # Output: [-1,69,1,1,-1]
    sol = Solution()
    #print(sol.avoidFlood(rains))

    # Input:
    rains = [10,20,20]
    # Output: []
    sol = Solution()
    #print(sol.avoidFlood(rains))

Python/Contest /1488. Avoid Flood in The City.py


import abc
from flask import jsonify

class Model(object):

	__metaclass__ = abc.ABCMeta

	def __init__(self):
		self.response = {}

	def json(self):
		self.build_response()
		return jsonify(self.response)

	'''Abstract methods'''
	@abc.abstractmethod
	def build_response(self):
		return

	def get_response(self):
		self.build_response()
		return self.response

class SmallEntity(Model):

	def __init__(self):
		super(SmallEntity, self).__init__()
		self.name = None
		self.score = None
		self.url = None
		self.release_date = None

	def build_response(self):
		super(SmallEntity, self).build_response()
		self.response['name'] = self.name
		self.response['score'] = self.score
		self.response['url'] = self.url
		self.response['release_date'] = self.release_date

class Notable(Model):

	def __init__(self):
		super(Notable, self).__init__()
		self.name = None
		self.score = None
		self.url = None
		self.thumbnail = None

	def build_response(self):
		super(Notable, self).build_response()
		self.response['name'] = self.name
		self.response['score'] = self.score
		self.response['url'] = self.url
		self.response['thumbnail'] = self.thumbnail

class Product(SmallEntity):

	def __init__(self,):
		super(Product, self).__init__()
		self.userscore = None

	def build_response(self):
		super(Product, self).build_response()
		self.response['userscore'] = self.userscore

class Error(Model):

	__metaclass__ = abc.ABCMeta

	def __init__(self, arg):
		super(Error, self).__init__()

		self.code = None
		self.message = None

	def build_response(self):
		super(Error, self).build_response()
		self.response['code'] = self.code
		self.response['message'] = self.message

class Entity(Model):

	__metaclass__ = abc.ABCMeta

	def __init__(self, arg):
		super(Entity, self).__init__()

		self.code = 660
		self.name = None
		self.score = None
		self.genre = []
		self.thumbnail = None
		self.userscore = None
		self.summary = None
		self.rating = None
		self.release_date = None
		self.url = None
		self.userscore_distribution = None
		self.metascore_distribution = None

	def build_response(self):
		super(Entity, self).build_response()
		self.response['code'] = self.code
		self.response['name'] = self.name
		self.response['score'] = self.score
		self.response['genre'] = self.genre
		self.response['thumbnail'] = self.thumbnail
		self.response['userscore'] = self.userscore
		self.response['summary'] = self.summary
		self.response['release_date'] = self.release_date
		self.response['url'] = self.url
		self.response['rating'] = self.rating
		self.response['userscore_distribution'] = self.userscore_distribution
		self.response['metascore_distribution'] = self.metascore_distribution

class ListEntity(Model):

	__metaclass__ = abc.ABCMeta

	def __init__(self):
		super(ListEntity, self).__init__()

		self.build_type = True
		self.build_thumbnail = True
		self.build_summary = True
		self.build_rating = True
		self.build_userscore = True
		self.build_genre = True

		self.type = None
		self.name = None
		self.release_date = None
		self.genre = []
		self.summary = None
		self.score = None
		self.userscore = None
		self.url = None
		self.thumbnail = None
		self.rating = None

	def build_response(self):
		super(ListEntity, self).build_response()
		if self.build_type:
			self.response['type'] = self.type
		self.response['name'] = self.name
		self.response['score'] = self.score
		if self.build_genre:
			self.response['genre'] = self.genre
		if self.build_userscore:
			self.response['userscore'] = self.userscore
		if self.build_summary:
			self.response['summary'] = self.summary
		self.response['release_date'] = self.release_date
		self.response['url'] = self.url
		if self.build_thumbnail:
			self.response['thumbnail'] = self.thumbnail
		if self.build_rating:
			self.response['rating'] = self.rating

	def disable_type(self):
		self.build_type = False

	def disable_thumbnail(self):
		self.build_thumbnail = False

	def disable_summary(self):
		self.build_summary = False

	def disable_rating(self):
		self.build_rating = False

	def disable_userscore(self):
		self.build_userscore = False

	def disable_genre(self):
		self.build_genre = False


import errno
import os
import tempfile
import traceback
import zmq

from circus import logger
from circus.exc import AlreadyExist, MessageError
from circus.sighandler import SysHandler
from circus.show import Show

class Controller(object):
    def __init__(self, context, endpoint, trainer, timeout=1.0):
        self.context = context
        self.skt = self.context.socket(zmq.ROUTER)
        self.skt.bind(endpoint)
        self.poller = zmq.Poller()
        self.poller.register(self.skt, zmq.POLLIN)

        self.trainer = trainer
        self.timeout = timeout * 1000

        # start the sys handler
        self.sys_hdl = SysHandler(trainer)

    def send(self, msg):
        self.skt.send(msg)

    def poll(self):
        while True:
            try:
                events = dict(self.poller.poll(self.timeout))
            except zmq.ZMQError as e:
                if e.errno == errno.EINTR:
                    continue
                else:
                    return
            else:
                break

        for client in events:
            _id = client.recv()
            msg = client.recv() or ""
            msg = msg.strip()
            if not msg:
                self.send_response(_id, client, msg,
                        "error: empty command")
                continue

            msg_parts = msg.split(" ")
            resp = ""
            handler = None
            try:
                cmd, inst, args = self.parse_message(msg_parts)
                handler = getattr(inst, "handle_%s" % cmd)
            except MessageError as e:
                resp = "error: %s" % str(e)
            except AttributeError as e:
                resp = "error: message %r" % msg

            if handler is not None:
                ## hacky part we should be abble to handlle the response
                ## before the controller stop
                if cmd in ('stop', 'quit', 'terminate') and \
                        inst == self.trainer:
                    self.send_response(_id, client, msg, "ok")

                try:
                    resp = handler(*args)
                except OSError as e:
                    resp = "error: %s" % e

                except Exception as e:
                    tb = traceback.format_exc()
                    resp = "error: command %r: %s [%s]" % (msg, str(e), tb)

            if resp is None:
                continue

            if not isinstance(resp, (str, buffer,)):
                msg = "msg %r tried to send a non-string: %s" % (msg,
                        str(resp))
                raise ValueError(msg)

            self.send_response(_id, client, msg, resp)

    def send_response(self, client_id, sock, msg, resp):
        try:
            sock.send(client_id, zmq.SNDMORE)
            sock.send(resp)
        except zmq.ZMQError as e:
            logger.error("Received %r - Could not send back %r - %s" %
                                (msg, resp, str(e)))

    def _get_show(self, show_name):
        try:
            return self.trainer.get_show(show_name)
        except KeyError:
            raise MessageError("program %s not found" % show_name)

    def parse_message(self, msg_parts):
        cmd = msg_parts[0].lower()
        args = []
        inst = self.trainer

        if len(msg_parts) > 1 and msg_parts[1]:
            show_name = msg_parts[1].lower()
            if cmd == "add_show":
                if len(msg_parts) < 3:
                    raise MessageError("invalid number of parameters")

                show_cmd = " ".join(msg_parts[2:])
                args = [show_name, show_cmd]
            elif cmd == "del_show":
                self._get_show(show_name)
                args = [show_name]
            else:
                inst = self._get_show(show_name)
                if len(msg_parts) > 2:
                    args = msg_parts[2:]

        return cmd, inst, args


from control_and_ai.helpers import *
from rocketlander_v2 import *

hyper_parameters = {
        'population_size': 100,
        'action_size': 3,
        'noise_standard_deviation': 0.1,
        'number_of_generations': 200,
        'learning_rate': 0.00025,
        'state_size': 8,
        'max_num_actions': 250
    }

gen_num = hyper_parameters['number_of_generations']
population = hyper_parameters['population_size']
max_num_actions = hyper_parameters['max_num_actions']
learning_strategy = hyper_parameters.get('momentum')
EV = EvolutionNetwork(hyper_parameters, None)

verbose = True
logger = logging.getLogger(__name__)
if verbose:
    logging.basicConfig(format='%(asctime)s - %(message)s\t', datefmt='%d/%m/%Y %I:%M:%S %p', level=logging.INFO)
    logging.basicConfig(format='%(asctime)s - %(message)s\t', datefmt='%d/%m/%Y %I:%M:%S %p', level=logging.ERROR)
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)

savepath = None

def run_episode(env, weights, show=False, *args):
    state = env.reset()
    done = False
    total_reward = 0
    ground_touched_flag = False
    num_actions = 0
    while not done:
        if show:
            env.render()
        if ground_touched_flag or num_actions <= max_num_actions:
            action = np.matmul(weights.T, state)
        else:
            action = [0, 0, 0]
        state, reward, done, info = env.step(action)
        if (state[6] == 1 or state[7] == 1):
            ground_touched_flag = True
        total_reward += reward
        num_actions += 1
    return total_reward

def run(EV, env):
    # ---------------------------------------------------------------------------------------
    logger.info("{0}\t{1}\t{2}".format('Episode', 'Reward', 'Mean Genes Reward'))
    running_reward = 0
    # ---------------------------------------------------------------------------------------
    for episode in range(gen_num):
        # Run the episode result
        if episode % 20 == 0:
            running_reward = run_episode(env[0], EV.weights, show=True)

        population_weights, noise = EV.generateMutations()

        rewards = np.zeros(population)

        with concurrent.futures.ThreadPoolExecutor() as executor:
            for i in range(population):
                future = executor.submit(run_episode, env[i + 1], population_weights[i], False)
                rewards[i] = future.result()

        if learning_strategy is None:
            EV.updateWeights(noise, rewards)
        else:
            EV.updateWeights_momentum(noise, rewards)

        if savepath is not None:
            EV.save_genes(savepath)
        logger.info("{0}\t{1}\t{2}".format(episode, running_reward, np.mean(rewards)))

simulation_settings = {'Side Engines': True,
                           'Clouds': False,
                           'Vectorized Nozzle': True,
                           'Graph': True,
                           'Render': True,
                           'Starting Y-Pos Constant': 1,
                           'Initial Force': 'random',
                           'Rows': 1,
                           'Columns': 2}

env = []
for i in range(hyper_parameters['population_size'] + 1):
    env.append(RocketLander(simulation_settings))

run(EV, env)


import wikipedia
from nltk import sent_tokenize
import json

def clean_paragraph(para):
    para = para.replace("\\'", "'")
    para = re.sub(r'\[[^]]*\]|\([^)]*\)', '', para)

    return para

def get_random_title():
    return wikipedia.random()

def get_page_summary(title):
    print(title)
    try:
        summ = wikipedia.summary(title)
        if "\\u" in summ:
            return ""
        return summ
    except:
        print("Disambiguation error in {}".format(title))
        return ""

def main():
    pages = []
    for i in range(5000):
        summary = get_page_summary(get_random_title())
        sentences = sent_tokenize(summary)
        pages.append(sentences)

    out = json.dumps(pages)
    with open("sentence_dump.txt", "a") as f:
        f.write(out)

# with open("sentence_dump.txt", "r") as f:
#     pages = json.loads(f.read())

main()


import CanvasAPI
import logging

def get_course(course_id):
    course = CanvasAPI.courses.get(course_id)
    CanvasAPI.util.printer.print_odict(course)

if __name__ == "__main__":
    for row in CanvasAPI.util.file.get_data(["course_id"]):
        try:
            get_course(row[0])
        except Exception as e:
            logging.warning("Error with '{}': {}".format(", ".join(row), e))
            continue
    input("Press enter to close...")


# -*- coding: utf-8 -*-
from setuptools import setup, find_packages

with open('requirements.txt') as f:
	install_requires = f.read().strip().split('\n')

# get version from __version__ variable in token_system/__init__.py
from token_system import __version__ as version

setup(
	name='token_system',
	version=version,
	description='Generating Tokens.',
	author='Monish Lalchandani',
	author_email='lmonish7108@gmail.com',
	packages=find_packages(),
	zip_safe=False,
	include_package_data=True,
	install_requires=install_requires
)


import math

from django.utils import timezone

def make_questions_dict(request, question_set):
    """Makes a JSON_dict with the question data, such as the new like count and owner status."""
    serialized = []
    for q in question_set:
        serialized.append(q.as_safe_dict())
        votes = q.vote_set
        serialized[-1]['votes'] = votes.count()
        if votes.filter(session_id=request.session.session_key).exists():
            serialized[-1]['has_voted'] = True
        else:
            serialized[-1]['has_voted'] = False
        if q.author == request.session.session_key:
            serialized[-1]['owner'] = True
        reports = q.report_set
        serialized[-1]['reports'] = reports.count()
        if reports.filter(session_id=request.session.session_key).exists():
            serialized[-1]['has_reported'] = True
        else:
            serialized[-1]['has_reported'] = False
    return {'data': serialized}

def reddit_sorting_question(votes, start_time, time_now):
    """Sorts the questions based on popularity. Based on the reddit 'Hot' algorithm.

    Parameters
    ----------
    votes : int
        Number of votes.
    start_time : datetime object
        The question's time of creation.
    time_now : datetime object
        The current time.
    """
    return round(math.log(max(1, votes*10), 2)*60-(((time_now-start_time).total_seconds())))

def linear_sorting_question(votes, start_time, time_now):
    """Sorts the questions based on popularity. Linear sort.

    Parameters
    ----------
    votes : int
            Number of votes.
    start_time : datetime object
            The question's time of creation.
    time_now : datetime object
            The current time.
    """
    return round(votes*60-(((time_now-start_time).total_seconds())))

def calculate_question_scores(qsession):
    """Takes a session object and recalculates the scores."""
    for question in qsession.question_set.all():
        votes = question.vote_set.count()
        # here you can choose which score algorithm is to be used
        question.score = reddit_sorting_question(votes, question.time_created, timezone.now())
        question.save()

def cookies_available(request):
    """Return True if the client has cookies enabled."""
    return get_sessionid_cookie(request) is not None

def get_sessionid_cookie(request):
    """Return the sessionid cookie set in the request HTTP header."""
    if 'HTTP_COOKIE' not in request.META:
        return None
    for cookie in request.META['HTTP_COOKIE'].split(";"):
        if cookie == "":
            continue
        key, value = cookie.strip(" ").split("=")
        if key == "sessionid":
            return value
    return None

def report_threshold(active_users):
    if active_users <= 0:
        return 1
    return math.floor(math.log(active_users, 1.6))


import numpy as np
import os
import sys
from collections import defaultdict

def load_initial_data():
  data_path = 'data/trade_data.csv'
  data = None
  if os.path.exists(data_path):
    data = np.loadtxt(data_path, dtype='object', delimiter=',', skiprows=1)
  else:
    print("trade_data.csv is not in data folder", file=sys.stderr)
    return data

  dates = list(map(lambda x: tuple(map(int, x.split('.'))), data[:, 0]))
  values = data[:, 5:6].astype('float')
  result = defaultdict(list)
  for date, value in zip(dates, values):
    result[date].append(value)
  return result, dates

def load_data():
  initial_data, dates = load_initial_data()
  indicators = list(load_indicators())

  if not initial_data:
    return

  result_list = []
  for date in dates:
   result_list.append(list(date) + initial_data[date])
   for indicator, max_len in indicators:
     ind_values = indicator[date]
     if len(ind_values) < max_len:
       ind_values.extend([np.nan for i in range(max_len - len(ind_values))])
     result_list[-1].extend(ind_values)
   result_list[-1] = np.array(result_list[-1])

  result = np.vstack(result_list)
  return result

def convert_date_from_indicator(date):
  date_list = date.split('-')[::-1]
  date_list[2] = date_list[2][2:]
  return tuple(map(int, date_list))

def load_indicators():
  for i in range(10):
    data_path = 'data/indicator{}.csv'.format(i)
    max_len = 0

    data = defaultdict(list)
    if os.path.exists(data_path):
      ind_data = np.loadtxt(data_path, dtype='object', delimiter=',')
      dates = map(convert_date_from_indicator, ind_data[:, 0])
      for i, date in enumerate(dates):
        data[date] = ind_data[i, 1:].astype('float')
        if len(data[date]) > max_len:
          max_len = len(data[date])
    else:
      print('No indicator{}.csv in data'.format(i))
    yield data, max_len

def convert_to_binary(data):
  diffs = data[1:, 3] - data[:-1, 3]
  data[0, 3] = 0
  data[1:, 3] = diffs > 0
  return data

def prepare_timeseries(data, length):
  series_list = []
  targets_list = []
  for start in range(len(data) - 2*length + 1):
    series_list.append(data[start:start+length])
    targets_list.append(data[start+length:start+2*length, 3])

  X = np.array(series_list)
  y = np.vstack(targets_list)
  return X, y


import time
import threading

total = 4

def create_items():
    global total
    for i in range(10):
        time.sleep(2)
        print('added items')
        total += 1
    print('creation is done')

def create_items_2():
    global total
    for i in range(7):
        time.sleep(1)
        print('added items')
        total += 1
    print('creation is done')

def limit_items():
    global total
    while True:
        if total > 5:
            print('overload')
            total -= 3
            print('subtracted 3')
        else:
            time.sleep(1)
            print('waiting')

creator1 = threading.Thread(target=create_items)
creator2 = threading.Thread(target=create_items_2)
limitor = threading.Thread(target=limit_items, daemon=True)  # daemon ends the infinite loop once the main method is over
print(limitor.isDaemon())

creator1.start()
creator2.start()
limitor.start()

creator1.join()
creator2.join()
limitor.join()

print('Ultimate total = {}'.format(total))


# -*- coding: utf-8 -*-

import os
import sys
import pytest
import datetime

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from SocialMemories import Content

class TestContent:

    @pytest.fixture()
    def post_data(self):
        return {
            "message": "Test Message",
            "created_time": "2014-05-02T23:11:33+0000",
            "id": "100005283221676_492510915650769"
            }

    def test_init(self, post_data):
        content = Content(data=post_data)

        assert content.message == 'Test Message'
        assert content.created_time == "2014-05-02T23:11:33+0000"
        assert content.id == "100005283221676_492510915650769"


# InverseOfModular.py
# encoding = UTF-8

# 将 "x^8+x^6+x^5+x^1+1" 形式的字符串转为 110000001 数值的形式
def FomatStrToValue(str):
    x = [0]*(1000+1)

    for i in range(len(str)):
        if str[i] == 'x':
            x[int(str[i+2])] = 1
    if "+1" in str:
        x[0] = 1
    return ArrayToNum(x[::-1])

def ValueToFomatStr(x):
    xn = NumToArray(x)[::-1]
    str = ""
    for i in range(len(xn))[::-1]:
        if xn[i] == 1:
            str += "+x^%d"%(i)
    str = str.replace("x^0", "1")
    return str[1:]

# 把列表转化成为数值
def ArrayToNum(wn):
    if wn == []: # 补充
        return None
    wn = [str(i) for i in wn]
    wn = int(''.join(wn))
    return wn
# 把数值按数字逐个分割成数字，组成列表
def NumToArray(w):
    if w == None: # 补充
        return []
    s = str(w)  # 因为整数是不可迭代的，所以要转成字符串处理
    wn = []
    for ch in s:
        wn.append(eval(ch))
    return wn

def add(x, y):
    if x < y:
        x, y = y, x
    xn, yn = NumToArray(x), NumToArray(y)
    lx, ly = len(xn), len(yn)
    temp = [0] * (lx-ly)
    temp[:lx-ly] = xn[:lx-ly]
    for i in range(ly):
        temp.append(xn[lx-ly+i] ^ yn[i])
    return ArrayToNum(temp)

def multi(x, y):
    xn, yn = NumToArray(x)[::-1], NumToArray(y)[::-1] # reverse()没有返回值
    lx, ly = len(xn), len(yn)
    temp = [0] * ( lx + ly - 1)
    for i in range(lx):
        for j in range(ly):
            temp[i+j] ^= (xn[i] & yn[j]) # 模运算下不考虑进位的问题 # i+j-1
    return ArrayToNum(temp[::-1]) # & -> *; ^ -> +

def div(x, y):
    if x < y:
        return (0, x)
    q, b = [], [] # q 表示 除数， b 表示每次的减数
    xn, yn = NumToArray(x), NumToArray(y)
    lx, ly = len(xn), len(yn)
    lq = lx - ly + 1

    while ArrayToNum(xn) >= y: #len(xn) >= ly and :# 长度大于等于不一定代表能减
        # 缺了等于号！！
        b = []
        q.append(1)
        for i in range(lx):         # 得到最大的减数
            t = yn[i] if i < ly else 0
            b.append(t)
        xn = NumToArray(add(ArrayToNum(xn), ArrayToNum(b))) # 二进制下加法即减法

        for i in range(1, lx - len(xn)):    #得到倍数
            if len(q) < lq:
                q.append(0)
        lx = len(xn)

    return (ArrayToNum(q), ArrayToNum(xn))

def gcd(x, y):
    xn, yn = NumToArray(x), NumToArray(y)
    # 由于之前 div 的缺陷： small % large = 0
    while ArrayToNum(yn) != 0:
        xn, yn = yn, NumToArray(div(ArrayToNum(xn), ArrayToNum(yn))[1])
    return ArrayToNum(xn)

def InverseOfModular(x,m): #这个扩展欧几里得算法求模逆
    if gcd(x, m) != 1:
        return None
    u1, u2, u3 = 1, 0, x
    v1, v2, v3 = 0, 1, m
    while v3 != 0:
        q = div(u3,v3)[0]
        v1, v2, v3, u1, u2, u3 = (add(u1, multi(q,v1))), (add(u2, multi(q,v2))), (add(u3, multi(q,v3))), v1, v2, v3
    return div(u1, m)[1]

if __name__ == "__main__":
    strx = input('请输入一个多项式f(x)(用x^n的形式表示,x也用x^1的形式表示)：')
    x = FomatStrToValue(strx)
    stry = input('请输入另一个多项式g(x)(用x^n的形式表示,x也用x^1的形式表示)：')
    y = FomatStrToValue(stry)
    print("f(x)和g(x)的乘积：")
    print("f(x)×g(x)=%s" % ValueToFomatStr(multi(x, y)))
    print("f(x)和g(x)的带余除法：")
    q, r = div(x, y)
    print("f(x) = %s × g(x) + %s " % (ValueToFomatStr(q), ValueToFomatStr(r)))
    print("f(x)和g(x)的最大公因数：")
    print("gcd(f(x), g(x)) = %s" % ValueToFomatStr(gcd(x, y)) )
    print("f(x)模g(x)的逆元是：")
    print("f(x)^{-1} mod g(x) = %s" % ValueToFomatStr(InverseOfModular(x, y)))
    ''' Test
    print(add(101, 110))

    print(div(1100, 100))
    print(div(1011, 100))
    print(div(1000, 1011))
    print(div(1, 1011))
    print(div(11, 1))

    print("-------gcd------")
    print(gcd(1011, 100))
    print(gcd(100, 1011))

    print(gcd(1010, 100))

    print("-------------")
    print(InverseOfModular(100, 1011))

    print(gcd(100000011, 100011011))
    print(InverseOfModular(100000011, 100011011))
    '''


from math import sqrt

def prime_factors(total):
	primes = []
	composites = [1]

	def is_prime(n):
		nonlocal primes, composites
		if n in primes:
			return True
		if n in composites:
			return False
		for i in [i for i in primes if (i - 2) in range(int(sqrt(n)) - 1)]:
			if n % i == 0:
				composites += [n, 2*n, 3*n, 5*n]
				return False
		primes += [n]
		composites += [2*n, 3*n, 5*n]
		return True

	dictionary = {}

	for i in range(int(sqrt(total)) + 1):
		dictionary[i] = is_prime(i)

	factors = [1]

	for i in [i for i in primes if (i - 2) in range(int(sqrt(total)) - 1)]:
		if total % i == 0:
			factors += [i]
	if len(composites) == 1:
		return total
	else:
		return max(factors)

print(prime_factors(600851475143))


#!/usr/bin/python3

"""
AirBnB Clone
Deploy using Fabric
Upload data to remote server
"""

from fabric.api import *
import os.path

# Set a default env.user if you want, quit # to the next line
# env.user = 'ubuntu'
env.hosts = ['35.237.164.135', '18.234.226.240']

def do_deploy(archive_path):
    """ Distributes an archive to web servers

    Return:
        True on sucess
        False on fails
    """

    # check if archive_path exists
    if (os.path.exists(archive_path) is False):
        return False

    file_name = archive_path.split("/")[-1]  # the last position in split array
    file_basename = file_name.split(".")[0]  # without extension

    dest_path = "/tmp/" + file_name
    uncom_path = "/data/web_static/releases/" + file_basename

    symbol_path = "/data/web_static/current"

    try:
        # upload file
        put(archive_path, dest_path)

        # Uncompress
        run("mkdir -p {}".format(uncom_path))
        run("tar -xzf {} -C {}".format(dest_path, uncom_path))

        # delete uploaded file
        run("rm {}".format(dest_path))

        # move files out of web_static directory
        run("mv {} {}".format(uncom_path + "/web_static/*", uncom_path))
        run("rm -rf {}".format(uncom_path + "/web_static"))

        # Symbolic Link. With overwrite option if exist
        run("rm -rf {}".format(symbol_path))
        run("ln -s {} {}".format(uncom_path, symbol_path))

        print("New version deployed!")

        return True

    except:
        return False


import logging
import requests
import json

from django.template import Context
from django.template.loader import get_template
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.db.models import Q

from ws4redis.publisher import RedisPublisher
from ws4redis.redis_store import RedisMessage
redis_broadcast_publisher = RedisPublisher(facility='ta', broadcast=True)

logger = logging.getLogger(__name__)

class InvalidCourseStringError(ValueError):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        msg = 'Course Strings must contain a number. You gave {}'
        return msg.format(self.value)

def notify(user, courses):
    subject = 'TA Status'

    if courses:
        plaintext = get_template('tas/ta_activation.txt')
        htmly = get_template('tas/ta_activation.html')
    else:
        plaintext = get_template('tas/remove_ta.txt')
        htmly = get_template('tas/remove_ta.html')

    d = Context({'user': user, 'courses': courses})
    text_content = plaintext.render(d)
    html_content = htmly.render(d)

    user.email_user(subject, text_content, html_message=html_content)

def _confirm_a_ta(user, course_strings):
    from tas.models import Course, TA

    # Create query objects. Basically means create a bunch of objects that
    # say "number=number AND postfix=postfix"
    #
    # Q objects:
    # https://docs.djangoproject.com/es/1.9/topics/db/queries/#complex-lookups-with-q-objects
    #
    # OR all of the created Q objects together
    # (number=11 AND postfix='') OR (number=150 AND postfix='IDS')
    course_query = Q()
    for course_string in course_strings.split(' '):
        number, postfix = _split_course_string(course_string)
        q_obj = Q(number=number) & Q(postfix=postfix)
        course_query |= q_obj

    # Run the query to get the courses
    courses = Course.objects.filter(course_query)

    student = user.student
    for course in courses:
        ta_job, _ = TA.objects.get_or_create(student=student, course=course)
        ta_job.active = True
        ta_job.save()

    # Get any existing TA jobs that we didn't just add and set them inactive
    remove_jobs = TA.objects\
        .filter(student=student).exclude(course__in=courses)
    remove_jobs.update(active=False)

    notify(user, courses)

def check_ta(user):
    from tas.models import TA
    try:
        # Because apparently having an '@' in the email gives a 403 back from Tufts
        email = user.email.replace('@', ':')
        url = "http://www.cs.tufts.edu/~molay/compta/isata.cgi/{0}"
        r = requests.get(url.format(email))
        r.raise_for_status()
        course_strings = r.text.strip()
        logger.info('Checked TA status for user. user="%s" status="%s"',
                    user.email, course_strings)
    except:
        logger.exception('Failed to get TA status for %s', user.email)
        return False

    try:
        if course_strings != 'NONE':
            _confirm_a_ta(user, course_strings)

        else:
            remove_jobs = TA.objects.filter(student=user.student, active=True)
            if remove_jobs.exists():
                remove_jobs.update(active=False)
                courses = [job.course for job in remove_jobs.all()]
                notify(user, courses)

            return False
    except Exception:
        # intentionally catch everything. If it failed, log and continue
        logger.exception('Failed to set status for %s. Courses: %s',
                         user.email, course_strings)
        return False

    return True

def get_administrators_for_school(school):
    group_name = get_school_admin_group_name(school.name)
    user_model = get_user_model()
    group_admins = Group.objects\
        .prefetch_related('user_set').get(name=group_name).user_set.all()
    return group_admins | user_model.objects.filter(pk=school.administrator.pk)

def get_school_admin_group_name(school_name):
    return '{} Admins'.format(school_name)

def _split_course_string(course_string):
    """ Split the course string in to a course number and a course postfix
    Expects all strings to be in the format numpostfix. For instance,
    '50CP' and '150IDS' are valid. The postfix is allowed to be empty: '11' is
    a valid course string. The number, however, must be present: 'IDS' is not
    a valid course string. Only the first numbers are parsed as the course
    number: '11A7B12' will be parsed as course_num = 11, postfix = 'A7B12'

    :param str course_string: The course string to parse

    :returns: `(course_num, course_postfix)`

    :raises: InvalidCourseStringError
    """
    course_num = ''
    course_postfix = ''

    count = 0
    for indx, char in enumerate(course_string):
        if not char.isdigit():
            break

        course_num += char
        count += 1
    try:
        course_num = int(course_num)
    except ValueError:
        logger.exception('Got an invalid course string: %s', course_string)
        raise InvalidCourseStringError(course_string)

    course_postfix = course_string[count:]

    return course_num, course_postfix

def publish_message(message_type, data=None, publisher=None):
    redis_publisher = publisher
    if redis_publisher is None:
        redis_publisher = redis_broadcast_publisher

    packet = {
        'type': message_type
    }

    if data is not None:
        packet['data'] = data

    logger.debug('Publishing redis message. message="%s" '
                 'default_publisher="%s"',
                 packet, publisher is None)

    message = RedisMessage(json.dumps(packet))
    redis_publisher.publish_message(message)