# https://dodona.ugent.be/nl/courses/264/series/3260/activities/659392988/#
import functools

class Maan:
    def __init__(self, val):
        if not (isinstance(val, (int, float)) and val >= 0):
            raise AssertionError("ongeldige waarde")
        self.val = int(val)

    def __int__(self):
        return self.val

    def __str__(self):
        return str(self.val)

    def __repr__(self):
        return f"Maan({self.val})"

    def __add__(self, other):
        temp = ""
        if isinstance(other, Maan):
            smallest: int = self.val if len(str(self.val)) < len(
                str(other.val)) else other.val
            largest: int = self.val if len(str(self.val)) >= len(
                str(other.val)) else other.val
        else:
            smallest: int = self.val if len(
                str(self.val)) < len(str(other)) else other
            largest: int = self.val if len(
                str(self.val)) >= len(str(other)) else other
        for _ in range(0, len(str(largest))):
            temp += str(smallest %
                        10) if smallest % 10 > largest % 10 else str(largest % 10)
            smallest //= 10
            largest //= 10

        return Maan(int(temp[::-1]))

    def __radd__(self, other):
        return self + other

    def __mul__(self, other):
        mult = []

        if isinstance(other, Maan):
            smallest: int = self.val if len(str(self.val)) < len(
                str(other.val)) else other.val
            largest: int = self.val if len(str(self.val)) >= len(
                str(other.val)) else other.val
        else:
            smallest: int = self.val if len(
                str(self.val)) < len(str(other)) else other
            largest: int = self.val if len(
                str(self.val)) >= len(str(other)) else other
        for el in str(smallest)[::-1]:
            temp = "0" * len(mult)
            for k in str(largest)[::-1]:
                temp += el if el < k else k

            mult.append(Maan(int(temp[::-1])))
        return functools.reduce(lambda a, b: a + b, mult)

    def __rmul__(self, other):
        return self * other

    def __pow__(self, power):
        if isinstance(power, Maan):
            power = power.val
        temp = self
        for _ in range(0, power - 1):
            temp *= self
        return temp

    def __rpow__(self, other):
        return Maan(other) ** self


#Funtion
#-Calling function
#-Defining function
#-Importing fucntion, Returning values and variables,scope

#from __future__ import print_ function
x=10
y=20
z=x+y
print(z)
a=int(input("Enter a multiple of ten:"))
b=a/10
print(a,"divided by ten is ",b)


"""
This is..
Welcome to your very own [drumroll]

_Behavior Modification Stimulus Toolkit_

i.e. a package designed to produce stimuli
designed to produce behavior modification.

TBDetermined

_Neural Feedback Training (NFT)_

For starters, here, will wrap
* espeak
* xmessage
to issue you commands according
to a timer and/or randomness.
You may also want to learn
to add text to pics or videos
to carry the commands.

Most of what will interest you here
is the data structure(s) containing
the commands and how they are issued.

Try to divide Stimuli into
* work
* hobby
* break
 ***
"""

import time
import multiprocessing as mp
import datetime as dt

#
# example of trimming a video
#
# ffmpeg -i ${in}.mp4 -ss 00:00:45 -to 00:02:50 -c:v copy -c:a copy ${out}.mp4
#

#
# example of extracting audio
#
# ffmpeg -i input.mp4 output.wav
#

###
# all this is super-buggy.
# * message timer a one-call that's-all
# * add espeak to message time
# * multimedia kickoffs
# * desktop-switching...
#   ... set a timer, run a task
#    (where tasks are composable)

def _desktop_message(text):
    p = subps.Popen(['xmessage', text])

# todo: consider stdlib threading.Timer
class Timer:
    """
    This is a countdown.
    Call a countup something else,
      a Watch, maybe.
    """

    def __init__(self,
                 dur_min,
                 text='hi there',
                 subps_args=[]):
        self._dur_min = dur_min
        self._text = text
        self._subps_args = subps_args
        self._start = dt.datetime.now()
        self._has_acted = False

    def min_left(self):
        time_delta = (dt.datetime.now() -
                      self._start)
        return (
            time_delta.total_seconds() /
            60.0)

    def poll(self):
        if self._has_acted:
            return 'already'
        if (self.min_left() <
            self._dur_min):
            return 'running'
        if self._text != '':
            _desktop_message(self._text)
        if len(self._subps_args) > 0:
            self._sub_proc = subps.Popen(
                self._subps_args,
            )
        self._has_acted = True
        return 'now'

__timers = []
__timer_heartbeat_proc = None

def set_message_timer(dur_min, text):
    __timers.append(Timer(
        dur_min,
        text=text,
    ))

def _timer_heartbeat_main():
    for timer in __timers:
        action = timer.poll()
    time.sleep(60)

def start_timer_heartbeat():
    if __timer_heartbeat_proc is not None:
        if __timer_heartbeat_proc.is_alive():
            __timer_heartbeat_proc.terminate()
        __timer_heartbeat_proc.join()
    __timer_heartbeat_proc = mp.Process(
        _timer_heartbeat_main,
    )
    __timer_heartbeat_proc.start()


"""
Ported to Python 3.
"""
import time
from urllib.parse import quote as urlquote

from hyperlink import DecodedURL, URL
from twisted.web import (
    http,
    resource,
)
from twisted.web.util import redirectTo, Redirect
from twisted.python.filepath import FilePath
from twisted.web.template import (
    Element,
    XMLFile,
    renderer,
    renderElement,
    tags,
)

import allmydata # to display import path
from allmydata.util import log, jsonbytes as json
from allmydata.interfaces import IFileNode
from allmydata.web import (
    filenode,
    directory,
    unlinked,
    status,
)
from allmydata.web import storage
from allmydata.web.common import (
    abbreviate_size,
    WebError,
    exception_to_child,
    get_arg,
    MultiFormatResource,
    SlotsSequenceElement,
    get_format,
    get_mutable_type,
    render_exception,
    render_time_delta,
    render_time,
    render_time_attr,
    add_static_children,
)
from allmydata.web.private import (
    create_private_tree,
)
from allmydata import uri

class URIHandler(resource.Resource, object):
    """
    I live at /uri . There are several operations defined on /uri itself,
    mostly involved with creation of unlinked files and directories.
    """

    def __init__(self, client):
        super(URIHandler, self).__init__()
        self.client = client

    @render_exception
    def render_GET(self, req):
        """
        Historically, accessing this via "GET /uri?uri=<capabilitiy>"
        was/is a feature -- which simply redirects to the more-common
        "GET /uri/<capability>" with any other query args
        preserved. New code should use "/uri/<cap>"
        """
        uri_arg = req.args.get(b"uri", [None])[0]
        if uri_arg is None:
            raise WebError("GET /uri requires uri=")

        # shennanigans like putting "%2F" or just "/" itself, or ../
        # etc in the <cap> might be a vector for weirdness so we
        # validate that this is a valid capability before proceeding.
        cap = uri.from_string(uri_arg)
        if isinstance(cap, uri.UnknownURI):
            raise WebError("Invalid capability")

        # so, using URL.from_text(req.uri) isn't going to work because
        # it seems Nevow was creating absolute URLs including
        # host/port whereas req.uri is absolute (but lacks host/port)
        redir_uri = URL.from_text(req.prePathURL().decode('utf8'))
        redir_uri = redir_uri.child(urlquote(uri_arg))
        # add back all the query args that AREN'T "?uri="
        for k, values in req.args.items():
            if k != b"uri":
                for v in values:
                    redir_uri = redir_uri.add(k.decode('utf8'), v.decode('utf8'))
        return redirectTo(redir_uri.to_text().encode('utf8'), req)

    @render_exception
    def render_PUT(self, req):
        """
        either "PUT /uri" to create an unlinked file, or
        "PUT /uri?t=mkdir" to create an unlinked directory
        """
        t = str(get_arg(req, "t", "").strip(), "utf-8")
        if t == "":
            file_format = get_format(req, "CHK")
            mutable_type = get_mutable_type(file_format)
            if mutable_type is not None:
                return unlinked.PUTUnlinkedSSK(req, self.client, mutable_type)
            else:
                return unlinked.PUTUnlinkedCHK(req, self.client)
        if t == "mkdir":
            return unlinked.PUTUnlinkedCreateDirectory(req, self.client)
        errmsg = (
            "/uri accepts only PUT, PUT?t=mkdir, POST?t=upload, "
            "and POST?t=mkdir"
        )
        raise WebError(errmsg, http.BAD_REQUEST)

    @render_exception
    def render_POST(self, req):
        """
        "POST /uri?t=upload&file=newfile" to upload an
        unlinked file or "POST /uri?t=mkdir" to create a
        new directory
        """
        t = str(get_arg(req, "t", "").strip(), "ascii")
        if t in ("", "upload"):
            file_format = get_format(req)
            mutable_type = get_mutable_type(file_format)
            if mutable_type is not None:
                return unlinked.POSTUnlinkedSSK(req, self.client, mutable_type)
            else:
                return unlinked.POSTUnlinkedCHK(req, self.client)
        if t == "mkdir":
            return unlinked.POSTUnlinkedCreateDirectory(req, self.client)
        elif t == "mkdir-with-children":
            return unlinked.POSTUnlinkedCreateDirectoryWithChildren(req,
                                                                    self.client)
        elif t == "mkdir-immutable":
            return unlinked.POSTUnlinkedCreateImmutableDirectory(req,
                                                                 self.client)
        errmsg = ("/uri accepts only PUT, PUT?t=mkdir, POST?t=upload, "
                  "and POST?t=mkdir")
        raise WebError(errmsg, http.BAD_REQUEST)

    @exception_to_child
    def getChild(self, name, req):
        """
        Most requests look like /uri/<cap> so this fetches the capability
        and creates and appropriate handler (depending on the kind of
        capability it was passed).
        """
        # this is in case a URI like "/uri/?uri=<valid capability>" is
        # passed -- we re-direct to the non-trailing-slash version so
        # that there is just one valid URI for "uri" resource.
        if not name:
            u = DecodedURL.from_text(req.uri.decode('utf8'))
            u = u.replace(
                path=(s for s in u.path if s),  # remove empty segments
            )
            return Redirect(u.to_uri().to_text().encode('utf8'))
        try:
            node = self.client.create_node_from_uri(name)
            return directory.make_handler_for(node, self.client)
        except (TypeError, AssertionError) as e:
            log.msg(format="Failed to parse cap, perhaps due to bug: %(e)s",
                    e=e, level=log.WEIRD)
            raise WebError(
                "'{}' is not a valid file- or directory- cap".format(name)
            )

class FileHandler(resource.Resource, object):
    # I handle /file/$FILECAP[/IGNORED] , which provides a URL from which a
    # file can be downloaded correctly by tools like "wget".

    def __init__(self, client):
        super(FileHandler, self).__init__()
        self.client = client

    @exception_to_child
    def getChild(self, name, req):
        if req.method not in (b"GET", b"HEAD"):
            raise WebError("/file can only be used with GET or HEAD")
        # 'name' must be a file URI
        try:
            node = self.client.create_node_from_uri(name)
        except (TypeError, AssertionError):
            # I think this can no longer be reached
            raise WebError("%r is not a valid file- or directory- cap"
                           % name)
        if not IFileNode.providedBy(node):
            raise WebError("%r is not a file-cap" % name)
        return filenode.FileNodeDownloadHandler(self.client, node)

    @render_exception
    def render_GET(self, req):
        raise WebError("/file must be followed by a file-cap and a name",
                       http.NOT_FOUND)

class IncidentReporter(MultiFormatResource):
    """Handler for /report_incident POST request"""

    @render_exception
    def render(self, req):
        if req.method != b"POST":
            raise WebError("/report_incident can only be used with POST")

        log.msg(format="User reports incident through web page: %(details)s",
                details=get_arg(req, "details", ""),
                level=log.WEIRD, umid="LkD9Pw")
        req.setHeader("content-type", "text/plain; charset=UTF-8")
        return b"An incident report has been saved to logs/incidents/ in the node directory."

SPACE = u"\u00A0"*2

class Root(MultiFormatResource):

    addSlash = True

    def __init__(self, client, clock=None, now_fn=None):
        """
        Render root page ("/") of the URI.

        :client allmydata.client._Client: a stats provider.
        :clock: unused here.
        :now_fn: a function that returns current time.

        """
        super(Root, self).__init__()
        self._client = client
        self._now_fn = now_fn

        self.putChild(b"uri", URIHandler(client))
        self.putChild(b"cap", URIHandler(client))

        # Handler for everything beneath "/private", an area of the resource
        # hierarchy which is only accessible with the private per-node API
        # auth token.
        self.putChild(b"private", create_private_tree(client.get_auth_token))

        self.putChild(b"file", FileHandler(client))
        self.putChild(b"named", FileHandler(client))
        self.putChild(b"status", status.Status(client.get_history()))
        self.putChild(b"statistics", status.Statistics(client.stats_provider))
        self.putChild(b"report_incident", IncidentReporter())

        add_static_children(self)

    @exception_to_child
    def getChild(self, path, request):
        if not path:
            # Render "/" path.
            return self
        if path == b"helper_status":
            # the Helper isn't attached until after the Tub starts, so this child
            # needs to created on each request
            return status.HelperStatus(self._client.helper)
        if path == b"storage":
            # Storage isn't initialized until after the web hierarchy is
            # constructed so this child needs to be created later than
            # `__init__`.
            try:
                storage_server = self._client.getServiceNamed("storage")
            except KeyError:
                storage_server = None
            return storage.StorageStatus(storage_server, self._client.nickname)

    @render_exception
    def render_HTML(self, req):
        return renderElement(req, RootElement(self._client, self._now_fn))

    @render_exception
    def render_JSON(self, req):
        req.setHeader("content-type", "application/json; charset=utf-8")
        intro_summaries = [s.summary for s in self._client.introducer_connection_statuses()]
        sb = self._client.get_storage_broker()
        servers = self._describe_known_servers(sb)
        result = {
            "introducers": {
                "statuses": intro_summaries,
            },
            "servers": servers
        }
        return json.dumps(result, indent=1) + "\n"

    def _describe_known_servers(self, broker):
        return list(
            self._describe_server(server)
            for server
            in broker.get_known_servers()
        )

    def _describe_server(self, server):
        status = server.get_connection_status()
        description = {
            u"nodeid": server.get_serverid(),
            u"connection_status": status.summary,
            u"available_space": server.get_available_space(),
            u"nickname": server.get_nickname(),
            u"version": None,
            u"last_received_data": status.last_received_time,
        }
        version = server.get_version()
        if version is not None:
            description[u"version"] = version[b"application-version"]

        return description

class RootElement(Element):

    loader = XMLFile(FilePath(__file__).sibling("welcome.xhtml"))

    def __init__(self, client, now_fn):
        super(RootElement, self).__init__()
        self._client = client
        self._now_fn = now_fn

    _connectedalts = {
        "not-configured": "Not Configured",
        "yes": "Connected",
        "no": "Disconnected",
        }

    @renderer
    def my_nodeid(self, req, tag):
        tubid_s = "TubID: "+self._client.get_long_tubid()
        return tags.td(self._client.get_long_nodeid(), title=tubid_s)

    @renderer
    def my_nickname(self, req, tag):
        return tag(self._client.nickname)

    def _connected_introducers(self):
        return len([1 for cs in self._client.introducer_connection_statuses()
                    if cs.connected])

    @renderer
    def connected_introducers(self, req, tag):
        return tag(str(self._connected_introducers()))

    @renderer
    def connected_to_at_least_one_introducer(self, req, tag):
        if self._connected_introducers():
            return "yes"
        return "no"

    @renderer
    def connected_to_at_least_one_introducer_alt(self, req, tag):
        state = self.connected_to_at_least_one_introducer(req, tag)
        return self._connectedalts.get(state)

    @renderer
    def services(self, req, tag):
        ul = tags.ul()
        try:
            ss = self._client.getServiceNamed("storage")
            stats = ss.get_stats()
            if stats["storage_server.accepting_immutable_shares"]:
                msg = "accepting new shares"
            else:
                msg = "not accepting new shares (read-only)"
            available = stats.get("storage_server.disk_avail")
            if available is not None:
                msg += ", %s available" % abbreviate_size(available)
            ul(tags.li(tags.a("Storage Server", href="storage"), ": ", msg))
        except KeyError:
            ul(tags.li("Not running storage server"))

        if self._client.helper:
            stats = self._client.helper.get_stats()
            active_uploads = stats["chk_upload_helper.active_uploads"]
            ul(tags.li("Helper: %d active uploads" % (active_uploads,)))
        else:
            ul(tags.li("Not running helper"))

        return tag(ul)

    @renderer
    def introducer_description(self, req, tag):
        connected_count = self._connected_introducers()
        if connected_count == 0:
            return tag("No introducers connected")
        elif connected_count == 1:
            return tag("1 introducer connected")
        else:
            return tag("%s introducers connected" % (connected_count,))

    @renderer
    def total_introducers(self, req, tag):
        return tag(str(len(self._get_introducers())))

    # In case we configure multiple introducers
    @renderer
    def introducers(self, req, tag):
        ix = self._get_introducers()
        if not ix:
            return tag("No introducers")
        return tag

    def _get_introducers(self):
        return self._client.introducer_connection_statuses()

    @renderer
    def helper_furl_prefix(self, req, tag):
        try:
            uploader = self._client.getServiceNamed("uploader")
        except KeyError:
            return tag("None")
        furl, connected = uploader.get_helper_info()
        if not furl:
            return tag("None")
        # trim off the secret swissnum
        (prefix, _, swissnum) = furl.rpartition("/")
        return tag("%s/[censored]" % (prefix,))

    def _connected_to_helper(self):
        try:
            uploader = self._client.getServiceNamed("uploader")
        except KeyError:
            return "no" # we don't even have an Uploader
        furl, connected = uploader.get_helper_info()

        if furl is None:
            return "not-configured"
        if connected:
            return "yes"
        return "no"

    @renderer
    def helper_description(self, req, tag):
        if self._connected_to_helper() == "no":
            return tag("Helper not connected")
        return tag("Helper")

    @renderer
    def connected_to_helper(self, req, tag):
        return tag(self._connected_to_helper())

    @renderer
    def connected_to_helper_alt(self, req, tag):
        return tag(self._connectedalts.get(self._connected_to_helper()))

    @renderer
    def known_storage_servers(self, req, tag):
        sb = self._client.get_storage_broker()
        return tag(str(len(sb.get_all_serverids())))

    @renderer
    def connected_storage_servers(self, req, tag):
        sb = self._client.get_storage_broker()
        return tag(str(len(sb.get_connected_servers())))

    @renderer
    def services_table(self, req, tag):
        rows = [ self._describe_server_and_connection(server)
                 for server in self._services() ]
        return SlotsSequenceElement(tag, rows)

    @renderer
    def introducers_table(self, req, tag):
        rows = [ self._describe_connection_status(cs)
                 for cs in self._get_introducers() ]
        return SlotsSequenceElement(tag, rows)

    def _services(self):
        sb = self._client.get_storage_broker()
        return sorted(sb.get_known_servers(), key=lambda s: s.get_serverid())

    @staticmethod
    def _describe_server(server):
        """Return a dict containing server stats."""
        peerid = server.get_longname()
        nickname =  server.get_nickname()
        version = server.get_announcement().get("my-version", "")

        space = server.get_available_space()
        if space is not None:
            available_space = abbreviate_size(space)
        else:
            available_space = "N/A"

        return {
            "peerid": peerid,
            "nickname": nickname,
            "version": version,
            "available_space": available_space,
        }

    def _describe_server_and_connection(self, server):
        """Return a dict containing both server and connection stats."""
        srvstat = self._describe_server(server)
        cs = server.get_connection_status()
        constat = self._describe_connection_status(cs)
        return dict(list(srvstat.items()) + list(constat.items()))

    def _describe_connection_status(self, cs):
        """Return a dict containing some connection stats."""
        others = cs.non_connected_statuses

        if cs.connected:
            summary = cs.summary
            if others:
                hints = "\n".join(["* %s: %s\n" % (which, others[which])
                                for which in sorted(others)])
                details = "Other hints:\n" + hints
            else:
                details = "(no other hints)"
        else:
            details = tags.ul()
            for which in sorted(others):
                details(tags.li("%s: %s" % (which, others[which])))
            summary = [cs.summary, details]

        connected = "yes" if cs.connected else "no"
        connected_alt = self._connectedalts[connected]

        since = cs.last_connection_time

        if since is not None:
            service_connection_status_rel_time = render_time_delta(since, self._now_fn())
            service_connection_status_abs_time = render_time_attr(since)
        else:
            service_connection_status_rel_time = "N/A"
            service_connection_status_abs_time = "N/A"

        last_received_data_time = cs.last_received_time

        if last_received_data_time is not None:
            last_received_data_abs_time = render_time_attr(last_received_data_time)
            last_received_data_rel_time = render_time_delta(last_received_data_time, self._now_fn())
        else:
            last_received_data_abs_time = "N/A"
            last_received_data_rel_time = "N/A"

        return {
            "summary": summary,
            "details": details,
            "service_connection_status": connected,
            "service_connection_status_alt": connected_alt,
            "service_connection_status_abs_time": service_connection_status_abs_time,
            "service_connection_status_rel_time": service_connection_status_rel_time,
            "last_received_data_abs_time": last_received_data_abs_time,
            "last_received_data_rel_time": last_received_data_rel_time,
        }

    @renderer
    def incident_button(self, req, tag):
        # this button triggers a foolscap-logging "incident"
        form = tags.form(
            tags.fieldset(
                tags.input(type="hidden", name="t", value="report-incident"),
                "What went wrong?"+SPACE,
                tags.input(type="text", name="details"), SPACE,
                tags.input(type="submit", value=u"Save \u00BB"),
            ),
            action="report_incident",
            method="post",
            enctype="multipart/form-data"
        )
        return tags.div(form)

    @renderer
    def rendered_at(self, req, tag):
        return tag(render_time(time.time()))

    @renderer
    def version(self, req, tag):
        return tag(allmydata.__full_version__)

    @renderer
    def import_path(self, req, tag):
        return tag(str(allmydata))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author: Fang Zhang <thuzhf@gmail.com>

import sys,os,json,gzip,math,time,datetime,random,copy
import functools,itertools,requests,pickle,configparser
import argparse,logging,uuid,shutil,collections
from urllib.parse import urlparse, parse_qs
from collections import defaultdict as dd
import multiprocessing as mp
import numpy as np
import regex as re
re.DEFAULT_VERSION = re.VERSION1

from FastKATE.utils.logger import simple_logger
logger = simple_logger(__name__, 'FastKATE/log')
logger.setLevel(logging.INFO)
from gensim.models import Word2Vec

from flask import Flask,request,jsonify
app = Flask(__name__)

from nltk.stem import WordNetLemmatizer
lemmatize = WordNetLemmatizer().lemmatize
lemmatize('')

taxonomy = None
w2v_model = None
msfos_data = None
acm_ccs_data = None

@app.route('/topics')
def topics():
    start_t = time.time()

    area_name = request.args.get('area', 'artificial_intelligence')
    area_name = normalize_name_for_querying_vector_model(area_name)
    context = request.args.get('context', 'computer_science')
    context = normalize_name_for_querying_vector_model(context)
    k = request.args.get('k', 10, int)
    depth = request.args.get('depth', 3, int)
    weighting_mode = request.args.get('weighting_mode', 0, int)
    use_category_structure = request.args.get('use_category_structure', 1, int)
    use_all_next_depth_subcats = request.args.get('use_all_next_depth_subcats', 0, int)
    use_msfos = request.args.get('use_msfos', 1, int)
    use_acm_ccs = request.args.get('use_acm_ccs', 1, int)
    # use_mcg = request.args.get('use_mcg', 0, int)
    # logger.debug('area_name: {}, k: {}'.format(area_name, k))

    ranked_scores = []
    if not use_category_structure:
        try:
            if context:
                ranked_scores = w2v_model.most_similar(positive=[area_name, context], topn=k)
            else:
                ranked_scores = w2v_model.most_similar(positive=[area_name], topn=k)
        except Exception as e:
            logger.debug(e)
    # elif not use_msfos and not use_mcg:
    else:
        if not use_all_next_depth_subcats:
            subcats = subcats_not_more_than_depth(area_name, depth, taxonomy)
            if use_msfos:
                subcats_from_msfos = subcats_not_more_than_depth_from_msfos(area_name, depth, msfos_data)
                for i in range(len(subcats_from_msfos)):
                    subcats[i].update(subcats_from_msfos[i])
            if use_acm_ccs:
                subcats_from_acm_ccs = subcats_not_more_than_depth_from_acm_ccs(area_name, depth, acm_ccs_data)
                for i in range(len(subcats_from_acm_ccs)):
                    subcats[i].update(subcats_from_acm_ccs[i])
        else: # deprecated
            subcats = get_subcats(area_name, taxonomy)
        logger.debug('subcats: {}'.format(subcats))

        weights = []
        for d in range(len(subcats)):
            weight_for_depth_d = weight_for_depth(d, weighting_mode)
            if weight_for_depth_d <= 0:
                break
            weights.append(weight_for_depth_d)
        logger.debug('weights: {}'.format(weights))

        for d in range(len(subcats)): # normalize_name_for_querying_vector_model and convert subcats[d] (from set) to list
            tmpcats = subcats[d]
            subcats[d] = []
            for c in tmpcats:
                subcats[d].append(normalize_name_for_querying_vector_model(c))
        logger.debug('subcats_normalized: {}'.format(subcats))

        scores = {}
        for d in range(len(subcats) - 1): # excluding root
            tmpcats = subcats[d + 1]
            for c in tmpcats:
                tmp_score = 0
                for d in range(len(weights)):
                    tmpcats2 = subcats[d]
                    for c2 in tmpcats2:
                        try:
                            if context:
                                tmp_score += w2v_model.n_similarity([c], [c2, context]) * weights[d]
                            else:
                                tmp_score += w2v_model.n_similarity([c], [c2]) * weights[d]
                        except Exception as e:
                            logger.debug(e)
                scores[c] = tmp_score
        ranked_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)[:k]

    # return jsonify(ranked_scores)
    end_t = time.time()
    t = end_t - start_t
    r = {'area': area_name, 'result': ranked_scores, 'time': t}
    return jsonify(r)

def weight_for_depth(d, weighting_mode):
    if weighting_mode == 1:
        return math.exp(4 - d)
    else: # this means 'root takes all weight'
        if d == 0:
            return 1
        else:
            return 0

def normalize_name_for_querying_vector_model(name):
    tmp = name.split('_')
    for i in range(len(tmp)):
        tmp[i] = lemmatize(tmp[i])
    name = '_'.join(tmp)
    return name

def load_pkl_file(infile):
    if not os.path.isfile(infile) or not os.path.getsize(infile):
        return None
    logger.info('loading data from {}...'.format(infile))
    with open(infile, 'rb') as f:
        data = pickle.load(f)
    logger.info('data loaded.')
    return data

def subcats_not_more_than_depth_from_msfos(area, depth, msfos_data):
    subcats = [set([area])]
    for i in range(depth):
        tmpcats = set()
        for j in subcats[-1]:
            if j in msfos_data:
                # tmp = [i[0] for i in msfos_data[j]['children']]
                # tmpcats.update(tmp)
                tmpcats.update(msfos_data[j])
        subcats.append(tmpcats)
    return subcats

def subcats_not_more_than_depth_from_acm_ccs(area, depth, data):
    subcats = [set([area])]
    for i in range(depth):
        tmpcats = set()
        for j in subcats[-1]:
            if j in data:
                tmpcats.update(data[j])
        subcats.append(tmpcats)
    return subcats

def subcats_not_more_than_depth(area, depth, taxonomy):
    subcats = [set([area])]
    for i in range(depth):
        tmpcats = set()
        for j in subcats[-1]:
            if j in taxonomy:
                tmpcats.update(taxonomy[j]['subcats'])
        subcats.append(tmpcats)
    return subcats

def subcats_and_subpages_not_more_than_depth(area, depth, taxonomy):
    subcats = [set([area])]
    subpages = []
    for i in range(depth):
        tmpcats = set()
        tmppages = set()
        for j in subcats[-1]:
            tmpcats.update(taxonomy[j]['subcats'])
            tmppages.update(taxonomy[j]['subpages'])
        subcats.append(tmpcats)
        subpages.append(tmppages)
    return subcats, subpages

def load_vector_model(vector_model):
    logger.info('loading vector model from {}...'.format(vector_model))
    w2v_model = Word2Vec.load(vector_model)
    logger.info('model loaded.')
    return w2v_model

def get_subcats(area, taxonomy):
    hierachy = [set(["area_of_computer_science"])]
    for i in range(10):
        tmpcats = set()
        for j in hierachy[-1]:
            if j in taxonomy:
                tmpcats.update(taxonomy[j]['subcats'])
        hierachy.append(tmpcats)

    #drop the duplicates
    for i in range(10):
        for j in range(i):
            hierachy[i] -= hierachy[j]

    subcats = [set([area])]
    for i in range(len(hierachy)):
        if area in hierachy[i]:
            break
    for j in range(i+1, len(hierachy)):
        subcats.append(hierachy[j])

    subcats2 = [set([area])]
    for i in range(len(subcats)-1):
        tmp = subcats[i+1]
        for j in range(i+1):
            tmp -= subcats[j]
        subcats2.append(tmp)
    return subcats2

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('wikidata_dir', help='the directory of wikipedia dumps that you have downloaded')
    args = parser.parse_args()

    taxonomy_infile = os.path.join(args.wikidata_dir, 'taxonomy_lemmatized.pkl')
    vector_model_infile = os.path.join(args.wikidata_dir, 'topic_embeddings.model')
    msfos_infile = '' # ignored for the moment
    acm_ccs_infile = '' # ignored for the moment

    global taxonomy
    global w2v_model
    global msfos_data
    global acm_ccs_data
    taxonomy = load_pkl_file(taxonomy_infile)
    w2v_model = load_vector_model(vector_model_infile)
    msfos_data = load_pkl_file(msfos_infile)
    acm_ccs_data = load_pkl_file(acm_ccs_infile)

    app.run(host='0.0.0.0', port=15400, threaded=True)
    # app.run(host='127.0.0.1', port=15401, threaded=True)

if __name__ == '__main__':
    start_t = time.time()
    main()
    end_t = time.time()
    t = end_t - start_t
    print('Time elapsed: {:.4f} minutes'.format(t / 60.))


# from geopy import location
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="locationfinder")
# enter the specified latitude and longitude
# Latitude = "1.2921"
# Longitude = "36.8219"
def get_details(coordinates):
# Location = geolocator.reverse(Latitude+ ","+Longitude)
    Location = geolocator.reverse(coordinates,exactly_one=True)
    address = Location.raw['address']
    #traverse the data
    city_name = address.get('city')
    state_name = address.get('state')
    country_name = address.get('country')
    return city_name, state_name, country_name
print(get_details("1.2921, 36.8219"))


import os
import time
import unittest
from unittest.mock import Mock
from threading import Thread
from shutil import rmtree

from src.scanner import FileScanner
from utils.settings import Settings

"""
    Testing thread to run scanner in separate thread to test
"""
class TestThread(Thread):
    def __init__(self, scanner):
        super(TestThread, self).__init__()
        self.scanner = scanner

    def run(self):
        self.scanner.run()

class TestScanner(unittest.TestCase):

    def setUp(self):
        # Set up testing directory
        self.test_dir = os.path.relpath("testFileDir", start=os.curdir)
        if not os.path.exists(self.test_dir):
            os.mkdir(self.test_dir)

        # Setup test file
        with open(os.path.join(self.test_dir, 'test.txt'), 'w') as f:
            f.write("Hello world!")
        f.close()

        # Setup event handler and file scanner
        Settings.client_dir = self.test_dir  # File scanner to watch testing directory
        dummy_handler = Mock()
        self.scanner = FileScanner(dummy_handler)
        self.thread = TestThread(self.scanner)

    def test_create(self):
        # Scanner should detect when a file is created
        self.thread.start()
        time.sleep(1)
        with open(os.path.join(self.test_dir, 'create.txt'), 'w') as f:
            f.write("Hello world!")
        time.sleep(Settings.scanner_interval + 1)
        self.scanner.handler.handle_create.assert_called()

    def test_update(self):
        # Scanner should detect when a file is updated
        self.thread.start()
        time.sleep(1)
        with open(os.path.join(self.test_dir, 'test.txt'), 'w') as f:
            f.write("New content")
        time.sleep(Settings.scanner_interval + 1)
        self.scanner.handler.handle_update.assert_called()

    def test_delete(self):
        # Scanner should detect when a file is deleted
        self.thread.start()
        time.sleep(1)
        file_path = os.path.join(self.test_dir, 'test.txt')
        os.remove(file_path)
        self.assertFalse(os.path.exists(file_path))
        time.sleep(Settings.scanner_interval + 1)
        self.scanner.handler.handle_delete.assert_called()

    def tearDown(self):
        self.scanner.running = False
        rmtree(self.test_dir)
        self.thread.join()


import discord
import os
import asyncio
import time

client = discord.Client()

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)

guildids = ["519451035836874763"]
channelids = ["519490720583778307", "520494704442212382", "519491305324281857"]

@client.event
async def on_message(message):
    if message.author.bot:
        return
    if message.channel.id not in channelids and message.server.id in guildids:
        def check(message):
            return message.content
        spam = await client.wait_for_message(author=message.author, channel= message.channel,check=check, timeout=1)
        spam1 = await client.wait_for_message(author=message.author, check=check, timeout=1, channel= message.channel)
        spam2 = await client.wait_for_message(author=message.author, check=check, timeout=1, channel= message.channel)
        await client.delete_message(spam)
        await client.delete_message(spam1)
        await client.delete_message(spam2)
    else:
      return

client.run(os.environ['Token'])


#This code will fetch the weather details for the given city name.
#It will make use of geopy module to get the location details.
#It will make use of weatherapi.com to get the current weather details of the city.

from geopy.geocoders import Nominatim
from constants import *
import requests
import streamlit as st
import pandas as pd

url = "https://weatherapi-com.p.rapidapi.com/current.json"
headers = {
	"X-RapidAPI-Key": f"{API_KEY}",
	"X-RapidAPI-Host": "weatherapi-com.p.rapidapi.com"
}

def get_location_lat_lon(city_name):
    '''
    This function will return the latitude and longitude of the given city name.
    '''
    geolocator = Nominatim(user_agent="MyApp")
    location = geolocator.geocode(f"{city_name}")
    if location != None:
        return location.latitude, location.longitude
    else:
        st.warning("Error Occured: Please Enter the City Name Again")
        st.stop()

def get_weather_data(url, headers, lat, lon):
    '''
    This function will return the weather details of the given latitude and longitude.
    '''
    querystring = {"q": f"{lat},{lon}"}
    response = requests.get(url, headers=headers, params=querystring)
    if response.status_code == 200:
        return response.json()
    else:
        st.error("Error Occured: Please try Again")
        st.stop()

def get_location_details(location):
    '''
    This function will return the location details of the given latitude and longitude.
    '''
    location_data = ''
    for k, v in location.items():
        if "epoch" in k:
            continue
        elif k in CHANGABLE_KEY_ITEMS and type(CHANGABLE_KEY_ITEMS[k]) == list:
            st.write(f"{CHANGABLE_KEY_ITEMS[k][0].title()}: {v} {CHANGABLE_KEY_ITEMS[k][1]}")
            location_data += f"{CHANGABLE_KEY_ITEMS[k][0]} is {v} {CHANGABLE_KEY_ITEMS[k][1]} and "
        elif k in CHANGABLE_KEY_ITEMS and type(CHANGABLE_KEY_ITEMS[k]) == str:
            st.write(f"{CHANGABLE_KEY_ITEMS[k].title()}: {v}")
            location_data += f"{CHANGABLE_KEY_ITEMS[k]} is {v} and "
        else:
            st.write(f"{k.capitalize()}: {v}")
            location_data += f"{k} is {v} and "
    st.title("Location Summary")
    st.write(location_data[:-5])

def get_current_weather_details(current):
    '''
    This function will return the current weather details of the given latitude and longitude.
    '''
    current_data = ''
    for k, v in current.items():
        if "epoch" in k or type(v) == dict:
            continue
        elif k in CHANGABLE_KEY_ITEMS and type(CHANGABLE_KEY_ITEMS[k]) == list:
            st.write(f"{CHANGABLE_KEY_ITEMS[k][0].title()}: {v} {CHANGABLE_KEY_ITEMS[k][1]}")
            current_data += f"{CHANGABLE_KEY_ITEMS[k][0]} is {v} {CHANGABLE_KEY_ITEMS[k][1]} and "
        elif k in CHANGABLE_KEY_ITEMS and type(CHANGABLE_KEY_ITEMS[k]) == str:
            st.write(f"{CHANGABLE_KEY_ITEMS[k].title()}: {v}")
            current_data += f"{CHANGABLE_KEY_ITEMS[k]} is {v} and "
        else:
            st.write(f"{k.capitalize()}: {v}")
            current_data += f"{k} is {v} and "
    st.title("Current Weather Summary")
    st.write(current_data[:-5])

if __name__ == "__main__":
    st.title("Weather Forecast App")
    city_name = st.text_input("Please Enter the City Name:",key=1)
    state = st.button("Go!..")
    if state:
        lat,lon = get_location_lat_lon(city_name)
        st.write("Hey There! You have entered the city name as: ", city_name)
        st.write("Fetching the Weather Details for the City: ", city_name)
        my_weather_data = get_weather_data(url, headers, lat, lon)
        st.map(pd.DataFrame(my_weather_data["location"],index=[0]))
        st.image(f'https:{my_weather_data["current"]["condition"]["icon"]}',caption=f"Current Weather in {city_name.capitalize()} is {my_weather_data['current']['condition']['text']}")
        st.title("Location Details")
        get_location_details(my_weather_data["location"])
        st.json(my_weather_data["location"])
        st.title("Current Weather Details")
        get_current_weather_details(my_weather_data["current"])
        st.json(my_weather_data["current"])


import sys
input = sys.stdin.readline

n = int(input())
l = [0 for _ in range(n)]
for i in range(n):
    s, e, w = map(int, input().split())
    l[i] = w

if n <= 2:
    print(max(l))
    exit(0)

l[2] += l[0]
for i in range(3, n):
    l[i] = max(l[i-2], l[i-3]) + l[i]

print(max(l))


import bs4,requests,webbrowser,os
from tkinter import *
import wckToolTips

# r=requests.get('http://www.androidauthority.com/feed')
r=requests.get('https://www.androidcentral.com/rss.xml')

r.raise_for_status()
b=bs4.BeautifulSoup(r.text,'xml')

os.chdir(r'c:\users\tiwari\desktop')
f=open('androidcen_xml.txt','w')
f.write(b.prettify())
f.close()
# print('__________________________CAtegory_______________________')
# cat=b.find_all('category')
# for i in cat:
# 	print(i.text)
# print('__________________________________________________________')
# print('_________________________description______________________')
# desc=b.find_all('description')
# for i in desc:
# 	print(i.text)
# print('___________________________________________________________')
# __________________title tag consist of imp article_______________
ti=b.find_all('title')
# _________________________________________________________________

# ___________________all links_______________________________
link=b.find_all('link')
# _________________________________________________________________

# print('_________________________publication date____________________________')
# pub=b.find_all('pubDate')
# for i in pub:
# 	print(i.text)
# print('_______________________________________________________________________')
def but(event):
	bu=event.widget
	for i in b.find_all('item'):
		if i.title.text==bu['text']:
			webbrowser.open(i.link.text)

def ent(event):
	bu=event.widget
	bu['fg']='red'

def lea(event):
	bu=event.widget
	bu['fg']='black'

def but1(event):
	for j in f.winfo_children():
		j.destroy()
	c1=0
	for i in ti:
		l2=Label(f,text=i.text)
		l2.bind('<Button-1>',but)
		l2.bind('<Enter>',ent)
		l2.bind('<Leave>',lea)
		l2.grid(row=0+c1,column=0)
		c1+=1

def addurl():
	v1=StringVar()
	t=Toplevel(root)
	t.title('Add RSS URL')
	Label(t,text='add url here').grid(row=0,column=0)
	e1=Entry(t,textvariable=v1).grid(row=0,column=1)
	b1=Button(t,text='Add').grid(row=1,column=0)

root=Tk()
root.title('RSS READER')
l1=Label(root,text=ti[0].text)
l1.grid(row=1,column=0)

Button(root,text='ADD',command=addurl).grid(row=0,column=0)

ti.pop(0)
l1.bind('<Enter>',ent)
l1.bind('<Button-1>',but1)
if len(b.description.text)>0:
	wckToolTips.register(l1,b.description.text)
f=Frame(root)
f.grid(row=2,column=0)

# c1=0
# for i in ti:
# 	l2=Label(f,text=i.text)
# 	l2.bind('<Button-1>',but)
# 	l2.bind('<Enter>',ent)
# 	l2.bind('<Leave>',lea)
# 	l2.grid(row=0+c1,column=0)
# 	c1+=1
root.mainloop()


#Client Credentials Grant method
import config
import http.client
import json

connection = http.client.HTTPSConnection('www.com')
headers = {"Content-type":"application/x-www-form-urlencoded"}
body='grant_type=client_credentials&client_id=%s&client_secret=%s'%(config.client_id, config.client_secret )

#POST
print("getting token")
connection.request('POST', '/api/v2/oauth2/token.json', body, headers)
print("token ok")
responsepost = connection.getresponse()
result=json.loads(responsepost.read().decode("utf-8"))
token=result['access_token']

#GET
print("getting stats")
connection._send_request('GET', '/api/v2/campaigns.json',[], {"Authorization":"Bearer " + token})

responseget = connection.getresponse()
result=json.loads(responseget.read().decode("utf-8"))
print(result['items'])
print(responseget.read())


import datetime

def get_overdue_dates():
    datesList = []

    date = datetime.datetime.now()

    month = int(date.strftime("%m"))
    day = int(date.strftime("%d"))
    year = int(date.strftime("%Y"))

    today = {"month": month, "day": day, "year": year}

    oneDay = get_one_day_back(today)

    datesList.append(oneDay["string"])

    twoDays = get_one_day_back(oneDay)
    datesList.append(twoDays["string"])

    threeDays = get_one_day_back(twoDays)
    datesList.append(threeDays["string"])
    # print(datesList)

    return datesList

def get_yesterday():
    date = datetime.datetime.now()

    month = int(date.strftime("%m"))
    day = int(date.strftime("%d"))
    year = int(date.strftime("%Y"))

    today = {"month": month, "day": day, "year": year}
    yesterday = get_one_day_back(today)
    yesterdayString = yesterday["string"]

    return yesterdayString

def get_one_day_back(date):
    shortMonths = [4, 6, 9, 11]
    month = date["month"]
    day = date["day"]
    year = date["year"]

    if day == 1:
        if month == 1:
            newMonth = 12
            newYear = year - 1
            newDay = 31
        else:
            newYear = year
            newMonth = month - 1
            if newMonth == 2:
                newDay = 28
            elif newMonth in shortMonths:
                newDay = 30
            else:
                newDay = 31
    else:
        newDay = day - 1
        newMonth = month
        newYear = year

    dateDict = {"month": newMonth, "day": newDay, "year": newYear}
    dateString = get_date_string(dateDict)
    dateDict['string'] = dateString

    return dateDict

def get_date_string(date):
    month = date["month"]
    day = date["day"]
    year = date["year"]

    if month < 10:
        stringMonth = '0' + str(month)
    else:
        stringMonth = str(month)
    if day < 10:
        stringDay = '0' + str(day)
    else:
        stringDay = str(day)

    dateString = stringMonth + '/' + stringDay + '/' + str(year)

    return dateString

def get_tomorrows_date():
    date = datetime.datetime.now()

    month = int(date.strftime("%m"))
    day = int(date.strftime("%d"))
    year = int(date.strftime("%Y"))

    today = {"month": month, "day": day, "year": year}
    tomorrow = get_one_day_forward(today)
    tomorrowString = get_date_string(tomorrow)

    return tomorrowString

def get_due_date(days):
    date = datetime.datetime.now()

    hour = int(date.strftime("%H"))
    month = int(date.strftime("%m"))
    day = int(date.strftime("%d"))
    year = int(date.strftime("%Y"))
    am = True

    if hour >= 12:
        am = False

    due_date = {"month": month, "day": day, "year": year}
    if am:
        i = 1
    else:
        i = 0
    while i < days:
        due_date = get_one_day_forward(due_date)
        i += 1

    due_date_string = get_date_string(due_date)

    return due_date_string

def get_one_day_forward(today):
    shortMonths = [4, 6, 9, 11]
    month = today['month']
    day = today['day']
    year = today['year']

    if day >= 28:
        if month == 2:
            newMonth = 3
            newDay = 1
            newYear = year
        elif month in shortMonths and day == 30:
            newMonth = month + 1
            newDay = 1
            newYear = year
        elif day == 31:
            if month == 12:
                newMonth = 1
                newDay = 1
                newYear = year + 1
            else:
                newMonth = month + 1
                newDay = 1
        else:
            newMonth = month
            newDay = day + 1
    else:
        newMonth = month
        newDay = day + 1
        newYear = year

    tomorrow = {"month": newMonth, "day": newDay, "year": newYear}

    return tomorrow

def get_today_string():
    date = datetime.datetime.now()
    month = date.strftime("%m")
    day = date.strftime("%d")
    year = date.strftime("%Y")
    today = month + "/" + day + "/" + year

    return today

def check_equipment_return(equipment):
    if equipment == 'true':
        returned = True
    else:
        returned = False

    return returned

def get_skier_code(height, weight, age, skier_type):
    skier_code_key = 1
    skier_code_dict = {1: "A", 2: "B", 3: "C", 4: "D", 5: "E", 6: "F",
                       7: "G", 8: "H", 9: "I", 10: "J", 11: "K", 12: "L",
                       13: "M", 14: "N", 15: "O", 16: "P"}
    weight_dict = {1: [22, 29], 2: [30, 38], 3: [39, 47], 4: [48, 56], 5: [57, 66],
                   6: [67, 78], 7: [79, 91], 8: [92, 107], 9: [108, 125], 10: [126, 147],
                   11: [148, 174], 12: [175, 209], 13: [210, 500]}
    height_dict = {8: [0, 58], 9: [59, 61], 10: [62, 65], 11: [66, 70], 12: [71, 76], 13: [77, 150]}

    for i in range(1, 16):
        if weight_dict[i][0] <= weight <= weight_dict[i][1]:
            skier_code_key = i
            break
        if i > 7:
            if height_dict[i][0] <= height <= height_dict[i][1]:
                skier_code_key = i
                break

    if age <= 9 or age >= 50:
        skier_code_key -= 1

    skier_code_key += (skier_type-1)

    return skier_code_dict[skier_code_key]

def get_din(skier_code, sole_length):
    sole_dict = {1: [0, 250], 2: [251, 270], 3: [271, 290], 4: [291, 310], 5: [311, 330], 6: [331, 500]}
    index = 1
    for i in range(1, 6):
        if sole_dict[i][0] <= sole_length <= sole_dict[i][1]:
            index = i
            break
    din = 0

    if skier_code == "A":
        din = 0.75
    elif skier_code == "B":
        b_dict = {1: 1, 2: 1, 3: 0.75, 4: 1.25, 5: 1.5, 6: 1.75}
        din = b_dict[index]
    elif skier_code == "C":
        c_dict = {1: 1.5, 2: 1.25, 3: 1.0, 4: 1.25, 5: 1.5, 6: 1.75}
        din = c_dict[index]
    elif skier_code == "D":
        d_dict = {1: 1.75, 2: 1.5, 3: 1.5, 4: 1.25, 5: 1.5, 6: 1.75}
        din = d_dict[index]
    elif skier_code == "E":
        e_dict = {1: 2.25, 2: 2.0, 3: 1.75, 4: 1.5, 5: 1.5, 6: 1.75}
        din = e_dict[index]
    elif skier_code == "F":
        f_dict = {1: 2.75, 2: 2.5, 3: 2.25, 4: 2.0, 5: 1.75, 6: 1.75}
        din = f_dict[index]
    elif skier_code == "G":
        g_dict = {1: 3.50, 2: 3.0, 3: 2.75, 4: 2.5, 5: 2.25, 6: 2.0}
        din = g_dict[index]
    elif skier_code == "H":
        h_dict = {1: 3.5, 2: 3.5, 3: 3.0, 4: 3.0, 5: 2.75, 6: 2.5}
        din = h_dict[index]
    elif skier_code == "I":
        i_dict = {1: 4.5, 2: 4.5, 3: 4.0, 4: 3.5, 5: 3.5, 6: 3.0}
        din = i_dict[index]
    elif skier_code == "J":
        j_dict = {1: 5.5, 2: 5.5, 3: 5.0, 4: 4.5, 5: 4.0, 6: 3.5}
        din = j_dict[index]
    elif skier_code == "K":
        k_dict = {1: 6.5, 2: 6.5, 3: 6.0, 4: 5.5, 5: 5.0, 6: 4.5}
        din = k_dict[index]
    elif skier_code == "L":
        l_dict = {1: 7.5, 2: 7.5, 3: 7.0, 4: 6.50, 5: 6.0, 6: 5.5}
        din = l_dict[index]
    elif skier_code == "M":
        m_dict = {1: 8.5, 2: 8.5, 3: 8.5, 4: 8.0, 5: 7.0, 6: 6.5}
        din = m_dict[index]
    elif skier_code == "N":
        n_dict = {1: 10.0, 2: 10.0, 3: 10.0, 4: 9.5, 5: 8.5, 6: 8.0}
        din = n_dict[index]
    elif skier_code == "O":
        o_dict = {1: 11.5, 2: 11.5, 3: 11.5, 4: 11.0, 5: 10.0, 6: 9.5}
        din = o_dict[index]
    elif skier_code == "P":
        p_dict = {1: 13.0, 2: 13.0, 3: 13.0, 4: 13.0, 5: 12.0, 6: 11.5}
        din = p_dict[index]

    return din

if __name__ == "__main__":
    skier_code = get_skier_code(71, 215, 20, 3)
    sole_length = 325
    print(skier_code, sole_length)
    print(get_din(skier_code, sole_length))


import csv

FILENAME = 'scores.csv'

def list_data(students):
    for i in range(1, len(students)):
        student = students[i]
        print(str(i)+
              ".STUD ID: "+str(student[0])+
                  "\tSTUD NAME: "+student[1]+
                  "\tM1: " + str(student[2]) +
                  "\tM2: " + str(student[3]) +
                  "\tM3: " + str(student[4]) +
                  "\tM4: " + str(student[5]) +
                  "\tM5: " + str(student[6]) +
                  "\tTOTAL: " + str(student[7]) +
                  "\tAVERAGE: " + str(student[8])
                  )

def search_student(students):
    name_search = input("Name: ")
    found = False
    for student in students:
        if name_search.lower() == student[1].lower():
            print("SUCCESSFULLY FOUND "+name_search)
            found = True
            print(
                  "STUD ID: "+student[0]+
                  "\tSTUD NAME: "+student[1]+
                  "\tM1: " + student[2] +
                  "\tM2: " + student[3] +
                  "\tM3: " + student[4] +
                  "\tM4: " + student[5] +
                  "\tM5: " + student[6] +
                  "\tTOTAL: " + student[7] +
                  "\tAVERAGE: " + student[8]
                  )
    if not found:
        print("STUDENT NOT FOUND")

def calc_tot_avg(total):
    return round(total/5, 2)

def write_student(students):
    student = []
    stud_id = input("Student ID: ")
    stud_name = input("Student Name: ")
    m1 = int(input("M1: "))
    m2 = int(input("M2: "))
    m3 = int(input("M3: "))
    m4 = int(input("M4: "))
    m5 = int(input("M5: "))
    total = m1+m2+m3+m4+m5
    avg = calc_tot_avg(total)
    student.append(stud_id)
    student.append(stud_name)
    student.append(m1)
    student.append(m2)
    student.append(m3)
    student.append(m4)
    student.append(m5)
    student.append(total)
    student.append(avg)
    students.append(student)
    try:
        with open(FILENAME,'w') as write_file:
            writer = csv.writer(write_file)
            writer.writerows(students)
    except FileNotFoundError:
        print("FILE NOT FOUND, please check the File Name")
    except Exception:
        print("Sry, UNKNOWN EXCEPTION while Writing.")
    print(stud_name+" was Successfully added.\n")

def read_student():
    stud = []
    try:
        with open(FILENAME,'r') as read_file:
            reader = csv.reader(read_file)
            for row in reader:
                stud.append(row)
    except FileNotFoundError:
        print("FILE NOT FOUND, please check the File Name")
    except Exception:
        print("Sry, UNKNOWN EXCEPTION")
    return stud

def menu():
    print("\nCOMMAND MENU")
    print("list - display all scores.")
    print("add - add new student score record.")
    print("search - fetch a student score record.")
    print("exit - EXIT.")
    print('\n')

def main():
    print('Student Score Program')
    menu()
    stud_list = read_student()
    while True:
        command = input('\nCOMMAND: ').lower()
        if command == 'list':
            list_data(stud_list)
        elif command == 'add':
            write_student(stud_list)
        elif command == 'search':
            search_student(stud_list)
        elif command == 'exit':
            print('\nBye.')
            break
        else:
            print("INVALID INPUT")

if __name__ == '__main__':
    main()

ASSIGNMENTS/PYTHON/Py Assignment/25-10-21/CSV - Stud Mark Data/main_scores.py


import math
import numpy as np
from scipy.stats import norm

#The class node holds info about the data points
class Node:
    def __init__(self, coordinates, clusterNum, numDim):
        self.coordinates = coordinates
        self.probabilities = [[] for x in xrange(clusterNum)]
        for i in xrange(clusterNum):
            for j in xrange(numDim):
                self.probabilities[i].append(0)
            # cluster = [0] * numDim
        self.probabilities_unorm = [0] * clusterNum
        self.probabilities_norm = [0] * clusterNum
        self.L = 0
        self.logL = 0

    #Does the math to check what is the probability that this nodes belongs to the given cluster
    def probFrom(self, clusters):

        # calculate probability that node is in this cluster per dimension
        for cluster in clusters:
            for i in xrange(cluster.numDim):
                # calculate probability for this cluster for this dimension
                mean = cluster.mean[i]
                # print"COORD: ",self.coordinates[i]
                # print"MEAN CALC: ",mean," CLUSTER",cluster.id
                stddev = math.sqrt(cluster.variance[i])
                # calculate Z value
                # z = (self.coordinates[i] - mean)/stddev
                # calculate prob from z value, mean, and stddev
                p_norm = norm(mean,stddev).cdf(self.coordinates[i])
                if self.coordinates[i] > mean:
                    p_norm = 1 - p_norm
                if p_norm == 0.0:
                    p_norm = 1*10**-300
                # update probabilities list
                self.probabilities[cluster.id][i] = p_norm
                # print "PNORM: ",p_norm
            # print "PNORMS: ",self.probabilities[cluster.id]

        # calculate probability that node is from cluster (unorm)
        for cluster in clusters:
            probability = 1
            for i in xrange(cluster.numDim):
                probability *= self.probabilities[cluster.id][i]
            probability *= cluster.probability
            if probability == 0.0:
                probability = 1 * 10 ** -300
            self.probabilities_unorm[cluster.id] = probability
        # print"PROB UNORM: ",self.probabilities_unorm

        # normalize probabilities
        sumP = 0
        self.probabilities_norm = []
        for prob in self.probabilities_unorm:
            sumP += prob
        for prob in self.probabilities_unorm:
            prob_norm = prob/sumP
            self.probabilities_norm.append(prob_norm)
        # print"PROB NORM: ",self.probabilities_norm

    def calculateNodeL(self):
        likelihood = 0
        log_likelihood = 0
        #calculate likelihood
        for prob in self.probabilities_unorm:
            likelihood += prob
        self.L = likelihood
        #calculate log likelihood
        self.logL = np.log(self.L)

    """
            # OLD MATH
            # dist = 0
            # for i in xrange(cluster.numDim):
            #     dist += (cluster.mean[i] - self.coordinates[i])**2
            #
            # probMath = math.exp(-1 / (2*cluster.variance) * dist**2)
            # probMath = 0
            # self.probabilities[cluster.id] = probMath

        # Take the summation of all of the probabilities
        #FORMULA BASed on the pos,
        sumN = 0.0
        for prob in self.probabilities:
            sumN += prob

        # Normalize all of the probabilities
        for i in xrange(len(self.probabilities)):
            self.probabilities[i] = self.probabilities[i]/sumN
    """


import json
import boto3

dynamodb = boto3.resource('dynamodb')
client = boto3.client('dynamodb')

def get_distance(source, destination):
    print('get_distance, source = ' + str(source) + ' to ' + str(destination))
    tableGraph = dynamodb.Table('Graph')
    response = tableGraph.get_item(
        Key={
            'source': source,
            'destination': destination
        }
    )
    print(response)
    return response['Item']['distance']

def lambda_handler(event, context):
    print('received request: ' + str(event))
    source_input = event['currentIntent']['slots']['source']
    destination_input = event['currentIntent']['slots']['destination']
    dist = get_distance(source_input, destination_input)
    response = {
        "dialogAction": {
            "type": "Close",
            "fulfillmentState": "Fulfilled",
            "message": {
                "contentType": "SSML",
                "content": dist
            },
        }
    }
    print('result = ' + str(response))
    return response


from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from coordinate import Coordinate

class SciPk(QObject):
    def __init__(self):
        QObject.__init__(self)
        self.coords = []
        self.title = None

    def read(self,  file):
        """
        Reads formated data file and populate coordinate object.

        Following example show reading data from a formatted data input file.
        This is produced when catalogue is passed through strip script
        1 2010/08/03 11:05:04.70 DJA 128.77 2.39 15.0 15054272 4.9 5.0 6.6 5.4 5.1
        """
        try:
            first = True
            for line in open(file):
                if first:
                    self.title = line[4:]
                    first = False
                    continue

                self.data_val = line[11:21]
                self.agency_val = line[34:40]
                self.agency_val  = self.agency_val.strip()

                coord = Coordinate(line[0:9])
                coord.setDate(self.data_val)
                coord.setTime(line[22:33])
                coord.setAgency(self.agency_val)
                coord.setX(line[41:50])
                coord.setY(line[51:61])
                coord.setDepth(line[63:68])
                coord.setEventID(line[70:78])
                coord.setMagMw(line[80:84])
                coord.setMagM(line[86:90])
                coord.setMagMB(line[92:96])
                coord.setMagME(line[98:102])
                coord.setMagML(line[104:108])
                coord.setMagMLv(line[110:114])
                coord.setMagMS(line[116:120])
                coord.setMagMb(line[122:126])
                coord.setMagMjma(line[128:132])
                coord.setMagMs(line[134:138])
                coord.setMagMs1(line[140:144])
                coord.setMagMs7(line[146:150])
                coord.setMagMsz(line[152:156])
                coord.setMagMwp(line[158:162])
                coord.setMagmB(line[164:168])
                coord.setMagmb(line[170:174])
                coord.setMagmb1(line[176:180])
                coord.setMagmb1mx(line[182:186])
                coord.setMagmbtmp(line[188:192])
                coord.setMagmslmx(line[194:198])

                self.coords.append(coord)

            return True

        except IOError:
            QMessageBox.critical(None, "Import", str("Could not open file!"))
            return  None

    def getAttributeList(self):
        attrList = [
                        QgsField("EventId",  QVariant.String),
                        QgsField("X Coordinate",  QVariant.Double),
                        QgsField("Y Coordinate",  QVariant.Double),
                        QgsField("Magnitude",  QVariant.String),
                        QgsField("Depth",  QVariant.String),
                        QgsField("Agency",  QVariant.String),
                        QgsField("DateTime",  QVariant.String)
                    ]
        return attrList

    def getFeatures(self, datalist, agencyName, magType):
        """
        populates Qgis data with QGis attribute mapping detail
        """
        features = []
        if magType:
            self.cmdstr = "coord.getMag" + str(magType) + "()"

        for coord in datalist:
            mag = eval(self.cmdstr)
            if ( not mag.isspace() and coord.getAgency() == agencyName):
                date_time = coord.getDate() + ":" + coord.getTime()

                try:
                    feat = QgsFeature()
                    feat.setGeometry( QgsGeometry.fromPoint(QgsPoint(float(coord.getX()),  float(coord.getY()))) )

                    feat.setAttributeMap( { 0 : QVariant(str(coord.getEventID())),
                                                        1 : QVariant(float(coord.getX())),
                                                        2 : QVariant(float(coord.getY())),
                                                        3 : QVariant(mag),
                                                        4 : QVariant(str(coord.getDepth())),
                                                        5 : QVariant(str(coord.getAgency())),
                                                        6 : QVariant(str(date_time)) })
                    features.append(feat)
                except ValueError:
                    continue
        return features

    def getCoords(self):
        return self.coords


import csv
import json
csvFileP = "colour.csv"
JsonFileP = "Jcolour.json"

animal = {}
with open(csvFileP)as csvF:
    csvReader = csv.DictReader(csvF)
    for csvRows in csvReader:
        Colour = csvRows['Colour']
        animal[Colour] = csvRows

with open('JsonFileP', 'w') as jsonF:
    jsonF.write(json.dumps(animal, indent=4))


#!/usr/bin/env python3
# Author: Pekka Marjamäki - Suolenkainen
# https://github.com/suolenkainen/economy

## workorder.py
## TODO: Description

import os, copy
from src.utilities import conf_data_to_attribute_list, distance_calculator

"""
Required attributes
- owner (the workorder are owned by the last settlement it was in)
- destination
- required haul method
- worker
- price
- amount
- capacity per item
- haul fee
"""

# workorder file properties
path = os.path.join(os.path.dirname(__file__), "..\\resources")
path = os.path.normpath(path)

# This is a utility class to create object within this module instead of utility module
class workorder_object:
    def __init__(self, data):
        #create an object in workorder module
        for attr in data:

            # Add attributes to object
            setattr(self, attr[0], attr[1])

# Fetch configuration data for the creation of work orders
def fetch_conf_data():

    # Fetch conf text
    conf = open(os.path.join(path, "workorders.conf"), "r")
    text = conf.readlines()

    return text

# Fetch attribute-list
def attribute_list(workorder):

    list = conf_data_to_attribute_list(workorder)

    return list

## Creates workorder objects where the files were used before
def create_workorders_from_configures():

    # Fetch configuration data
    lines = fetch_conf_data()

    # All workorders in the file
    workorders = []

    # set attributes to object based on the file
    for workorder in lines:

        # Create object from workorder data using "workorder_object" class
        data = attribute_list(workorder)
        obj = workorder_object(data)
        workorders.append(obj)

    return workorders

## Combine buying and selling orders
def combine_workorders(ord_objects):

    ## Combining has divided into part-functions
    selling, buying = sort_buy_sell(ord_objects)
    complete_orders, buying = finish_transactions(selling, buying, ord_objects)

    return complete_orders, buying

def sort_buy_sell(ord_objects):
    selling = []
    buying = []

    # Divide the selling and buying into their of lists and return them sorten by having the most expensive selling to cheapest buying
    for order in ord_objects:
        if order.sell == True:
            selling.append(order)
        else:
            buying.append(order)
    selling = sorted(selling, key=lambda d: d.price, reverse=True)
    buying = sorted(buying, key=lambda d: d.price)

    return selling, buying

def finish_transactions(selling, buying, ord_objects):

    # Pairing sell and purchase orders so that the most expensive item is sold first to the least paying settlement and then increasing in price
    complete_orders = []
    order = 0
    while len(selling) > 0:
        sold = selling[order]
        if sold.processed in ["sold", "finished"]:
            complete_orders.append(sold)
            order += 1
            if order >= len(selling):
                buying.extend(selling)
                break
            continue
        if buying == []:
            deal = False
        for request in buying:
            if sold.processed in ["sold", "finished"]:
                continue
            deal = False

            # Matching the products
            if sold.product == request.product:
                deal = sales_calculator(sold.price, request.price)
                break
            else:
                continue
        order += 1

        #when deal is formed, the deal is put into a list of completed transactions. If some of the goods are not sold or remaining in the order, a new order is created
        if deal:
            complete_order, newsale, newbuy, old_request = match_orders(sold, request, len(ord_objects))
            sold = complete_order
            # ord_objects.remove(request)
            complete_orders.append( selling.pop( selling.index( complete_order ) ) )
            buying.extend(newbuy)
            selling.extend(newsale)

            #when adding and removing items from lists, they are sorted again
            buying = sorted(buying, key=lambda d: d.price)
            selling = sorted(selling, key=lambda d: d.price, reverse=True)
            order = 0
            if len(buying) == 0 or len(selling) == 0:
                buying.extend(selling)
                selling = []
                break
        if len(selling) == 0 or order >= len(selling):
            buying.extend(selling)
            break

    return complete_orders, buying

## If we create new orders on the fly, how do we handle identifiers?
def match_orders(seller, buyer, index):
    # If workorders match each other, the seller order is updated and buy-order is removed
    if seller.amount == buyer.amount:
        seller.destination = buyer.owner
        seller.processed = "combined"
        buyer.processed = "finished"
        return seller, [], [], buyer

    # If seller has more than buyer is willing to buy, a new order will be created for the surplus
    if seller.amount > buyer.amount:
        new_order = copy.deepcopy(seller)
        seller.destination = buyer.owner
        seller.amount = buyer.amount
        seller.processed = "combined"
        buyer.processed = "finished"
        new_order.amount -= buyer.amount
        new_order.destination = -1
        new_order.id = index
        new_order.processed = "free"
        return seller, [new_order], [], buyer

    # If buyer wants to buy more than seller has to sell, a new order will be created for the lacking amount
    if seller.amount < buyer.amount:
        new_order = copy.deepcopy(buyer)
        seller.destination = buyer.owner
        seller.processed = "combined"
        buyer.processed = "finished"
        new_order.amount -= seller.amount
        new_order.destination = -1
        new_order.id = index
        new_order.processed = "free"
        return seller, [], [new_order], buyer

# This function checks if a transaction forms a deal
def sales_calculator(asked, payed):

    #Checking that transaction is made within range of reason (5%)
    # If the selling price is just a little less than required, the price is reduced a bit by seller
    # If asked price is less than what the buyer is willing to pay, then the deal is made
    if asked == payed:
        return True
    if asked > payed:
        if asked <= payed*1.05 or asked/1.05 <= payed:
            return True
    elif asked < payed:
        return True

    return False

## Add distance to transactions
def transactions_distance(transactions, sett_objects):

    # loop through workorders and find the settlements
    for order in transactions:
        if order.destination == -1:
            continue
        ord_settlement1 = order.owner
        for stlm1 in sett_objects:
            if stlm1.id == ord_settlement1:
                s_coordx = stlm1.coordx
                s_coordy = stlm1.coordy
        ord_settlement2 = order.destination
        for stlm2 in sett_objects:
            if stlm2.id == ord_settlement2:
                d_coordx = stlm2.coordx
                d_coordy = stlm2.coordy

        # send the settlement info to distance calculator
        order.distance, order.angle = distance_calculator((s_coordx, s_coordy), (d_coordx, d_coordy))

if __name__ == '__main__':

    ord_objects = create_workorders_from_configures()
    for o in ord_objects:
        print(o.__dict__)


from functools import wraps
from flask import g, redirect, url_for

def login_required(func):
    #保留func的信息
    @wraps(func)
    #func(a,b,c)
    # func(1,2,c=3), 1,2 --> args, c=3 --> kwargs
    def inner(*arg, **kwargs):
        if g.user:   #如果是登录的用户
            return func(*arg, **kwargs)
        else:   #如果没登录，跳转到登录界面
            return redirect(url_for("auth.login"))
    return inner

#如何理解装饰器呢？
#@login_required
#def public_question(question_id):
#   pass
#  ---等同于--
# login_required(public_question)(question_id)
# login_required(public_question)这是一个函数，返回的是inner，然后把question_id传进inner再做判断


# https://judge.softuni.bg/Contests/Compete/Index/1839#6

def age_assignment(*args, **kwargs):
    result = {}
    for key, value in kwargs.items():
        for person in args:
            if key == person[0]:
                result[person] = value

    return result

print(age_assignment("Peter", "George", G=26, P=19))
print(age_assignment("Amy", "Bill", "Willy", W=36, A=22, B=61))

05. Functions Advanced/Exercise/07. Age Assignment.py


from tabulate import tabulate
import os
# %matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
from gensim.models.word2vec import Word2Vec
from collections import Counter, defaultdict
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.naive_bayes import BernoulliNB, MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
from sklearn.cross_validation import cross_val_score
from sklearn.cross_validation import StratifiedShuffleSplit

# TRAIN_SET_PATH = "20ng-no-stop.txt"
# TRAIN_SET_PATH = "r52-all-terms.txt"
TRAIN_SET_PATH = "all_user_tweets_1.txt"
# TRAIN_SET_PATH = "r8.txt"
GLOVE_6B_50D_PATH = "glove.6B.50d.txt"

encoding="utf-8"

X, y = [], []

with open("Categorized_User_Polarity.txt") as inp:
    for line in inp:
        # print (line)
        values    = line.split("\t") # id, polarity
        user_id   = values[0]
        user_file = "tokens_lines/" + user_id
        if os.path.isfile(user_file): # not all user IDs had tweets in the master tweet file
            y.append(int(values[1])) # save the polarity
            with open(user_file, 'r') as inp: # save the
                X.append(inp.read().split())

                	# X.append(line.split())
# with open(TRAIN_SET_PATH, "r") as infile:
#     for line in infile:
#         label, text = line.split("\t")
#         # texts are already tokenized, just split on space
#         # in a real case we would use e.g. spaCy for tokenization
#         # and maybe remove stopwords etc.
#         X.append(text.split())
#         y.append(label)
# print(X)
# print(y)
X, y = np.array(X), np.array(y)
print ("total examples %s" % len(y))

with open(GLOVE_6B_50D_PATH, "rb") as lines:
    wvec = {line.split()[0].decode(encoding): np.array(line.split()[1:],dtype=np.float32)
               for line in lines}

glove_small = {}
all_words = set(w for words in X for w in words)
with open(GLOVE_6B_50D_PATH, "rb") as infile:
    for line in infile:
        parts = line.split()
        word = parts[0].decode(encoding)
        if (word in all_words):
            nums=np.array(parts[1:], dtype=np.float32)
            glove_small[word] = nums

print(len(all_words))

svc = Pipeline([("count_vectorizer", CountVectorizer(analyzer=lambda x: x)), ("linear svc", SVC(kernel="linear"))])
svc_tfidf = Pipeline([("tfidf_vectorizer", TfidfVectorizer(analyzer=lambda x: x)), ("linear svc", SVC(kernel="linear"))])

class MeanEmbeddingVectorizer(object):
    def __init__(self, word2vec):
        self.word2vec = word2vec
        if len(word2vec)>0:
            self.dim=len(word2vec[next(iter(glove_small))])
        else:
            self.dim=0

    def fit(self, X, y):
        return self

    def transform(self, X):
        return np.array([
            np.mean([self.word2vec[w] for w in words if w in self.word2vec]
                    or [np.zeros(self.dim)], axis=0)
            for words in X
        ])

# and a tf-idf version of the same
class TfidfEmbeddingVectorizer(object):
    def __init__(self, word2vec):
        self.word2vec = word2vec
        self.word2weight = None
        if len(word2vec)>0:
            self.dim=len(word2vec[next(iter(glove_small))])
        else:
            self.dim=0

    def fit(self, X, y):
        tfidf = TfidfVectorizer(analyzer=lambda x: x)
        tfidf.fit(X)
        # if a word was never seen - it must be at least as infrequent
        # as any of the known words - so the default idf is the max of
        # known idf's
        max_idf = max(tfidf.idf_)
        self.word2weight = defaultdict(
            lambda: max_idf,
            [(w, tfidf.idf_[i]) for w, i in tfidf.vocabulary_.items()])

        return self

    def transform(self, X):
        return np.array([
                np.mean([self.word2vec[w] * self.word2weight[w]
                         for w in words if w in self.word2vec] or
                        [np.zeros(self.dim)], axis=0)
                for words in X
            ])

etree_glove_small = Pipeline([("glove vectorizer", MeanEmbeddingVectorizer(glove_small)),
                        ("extra trees", ExtraTreesClassifier(n_estimators=200))])
etree_glove_small_tfidf = Pipeline([("glove vectorizer", TfidfEmbeddingVectorizer(glove_small)),
                        ("extra trees", ExtraTreesClassifier(n_estimators=200))])

svc_embedding = Pipeline([("tfidf_glove_vectorizer", TfidfEmbeddingVectorizer(glove_small)), ("linear svc", SVC(kernel="linear"))])

all_models = [
    ("svc", svc),
    ("svc_tfidf", svc_tfidf),
    ("glove_small", etree_glove_small),
    ("glove_small_tfidf", etree_glove_small_tfidf),
    ("svc_glove_small", svc_embedding),
]

unsorted_scores = [(name, cross_val_score(model, X, y, cv=3).mean()) for name, model in all_models]
scores = sorted(unsorted_scores, key=lambda x: -x[1])

print (tabulate(scores, floatfmt=".4f", headers=("model", 'score')))


# -*- coding: utf-8 -*-
"""
Created on Thu Mar 11 11:41:17 2021
Function parameters:
    argument: dataframe with missing values
    return value: imputed data

@author: Ashish
"""
import pandas as pd
import numpy as np

# custom function
def summarize_missing(df):
    # Null counts
    s1 = df.isnull().sum().rename('No. Missing')

    s2 = pd.Series(data=[df.index[m].tolist() for m in [df[col].isnull() for col in df.columns]],
                   index=df.columns,
                   name='Index')
    # Other way, probably overkill
    #s2 = (df.isnull().replace(False, np.NaN).stack().reset_index()
    #         .groupby('level_1')['level_0'].agg(list)
    #         .rename('Index'))

    return pd.concat([s1, s2], axis=1, sort=False)

# raw data
raw_data = {'first_name': ['Jason', np.nan, 'Tina', 'Jake', 'Amy'],
        'last_name': ['Miller', np.nan, 'Ali', 'Milner', 'Cooze'],
        'age': [42, np.nan, 36, 24, 73],
        'sex': ['m', np.nan, 'f', 'm', 'f'],
        'preTestScore': [4, np.nan, np.nan, 2, 3],
        'postTestScore': [25, np.nan, np.nan, 62, 70]}
df = pd.DataFrame(raw_data, columns = ['first_name', 'last_name', 'age', 'sex', 'preTestScore', 'postTestScore'])
print("data with missing values\n",df)

miss_vals = summarize_missing(raw_data)
print(miss_vals)


import random
from django.shortcuts import render

from appArtGallery.models import *

def pageMain(request):
    list = Pieza.objects.all()
    join = Pieza.objects.select_related('artista')
    dic = []
    dic2 = []
    categoria = Categoria.objects.all()
    for l in list:
        dic.append(l)

    for l2 in list:
        dic2.append(l2)

    select = random.sample(dic, 3)
    select2 = random.sample(dic2, 3)

    return render(request, 'index.html', {'list': select, 'list2': select2, 'category': categoria})


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

from os.path import join
from shutil import rmtree
from tempfile import mkdtemp
from testcase import TestCase

class TestDir(TestCase):

    def touch(self, dir_, name):
        with open(join(dir_, name), "w") as fp:
            pass

    def run_open_test(self, expected):
        tmp_dir = mkdtemp()
        try:
            for e in expected:
                self.touch(tmp_dir, e)
            self._test("""Dir.open(\"{tmp_dir}\") do |dir|
  dir.each(&print)
end""".format(**locals()), "".join([".", ".."] + expected))
        finally:
            rmtree(tmp_dir)

    for i, testee in enumerate([[], ["foo"], ["foo", "bar"]]):
        exec("""def test_open{index}(self):
    self.run_open_test({testee})""".format(index=10 * i, testee=testee))

# vim: tabstop=4 shiftwidth=4 expandtab softtabstop=4


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec  9 12:02:58 2022

@author: johnmorgan
"""

# longest common subsequence, copied
def lcs(A, B):
    a, b = len(A), len(B)
    x = [[0] * (b + 1) for _ in range(a + 1)]
    for i in reversed(range(a)):
        for j in reversed(range(b)):
            if A[i] == B[j]:
                x[i][j] = x[i + 1][j + 1] + 1
            else:
                x[i][j] = max(x[i + 1][j], x[i][j + 1])
    return x[0][0]

# print(lcs("hieroglyphology", "michaelangelo"))

# longest increasing subsequence, copied
def lis(A):
    a = len(A)
    x = [1] * a
    for i in reversed(range(a)):
        for j in range(i, a):
            if A[j] > A[i]:
                x[i] = max(x[i], 1 + x[j])
    return max(x)

# print(lis("carbohydrate"))

# max_subarray_sum suffix version, copied
def max_subarray_sum(A):
    x = [None for _ in A]
    x[0] = A[0]
    for k in range(1, len(A)):
        x[k] = max(A[k], A[k] + x[k - 1])
    print(x)
    return max(x)

# A = [-9, 1, -5, 4, 3, -6, 7, 8, -2]
# print(max_subarray_sum(A))

def max_subarray_sum_prefix(A):
    last_idx = len(A) - 1
    x = [None for _ in A]
    x[last_idx] = A[last_idx]
    for k in reversed(range(last_idx)):
        x[k] = max(A[k], A[k] + x[k + 1])
    return max(x)

# A = [-9, 1, -5, 4, 3, -6, 7, 8, -2]
# print(max_subarray_sum_prefix(A))


import random
from discord.ext import commands

#(*args) 傳入多個參數->list
#(**kwargs) 傳入多個參數->dict
#'value' in dict 偵測dict內是否有value
#len(list) 查詢list內的個數

#json開啟法1
#with open('.../XXX.json','r') as f:
#    data= json.load(f)
#json開啟法2
#data = json.load(open('.../XXX.json','r'))

#json寫入法
#1.mode='r'讀一遍關掉，再mode='r+'或mode='w'開啟dump進去
#2.mode='r+'開啟，先data = json.load(jfile)，最後用json.seek(0)後再dump

#json mode
#'r'=讀取 'w'=寫入(開啟檔案時會先清除內容) 'r+'=讀寫(開啟檔案時不會清除內容)

#jfile.seek(0)
#指標移至檔案開頭

#list
#s3=s1&s2 # 交集︰取兩個集合中，相同的資料
#s3=s1|s2 # 聯集︰取兩個合中的所有資料，但不重複取
#s3=s1-s2 # 差集︰從 s1 中，減去和 s2 重疊的部分
#s3=s1^s2 # 反交集︰取兩個集合中，重複的部分

#s=set("Hello") # 把字串中的字母折拆成集合
#dic={x:x*2 for x in [3,4,5]} # 從列表的資料中產生字典

#async -> await

def is_number(n):
    try:
        float(n)
        import unicodedata
        unicodedata.numeric(n)
        return True
    except (TypeError, ValueError):
        return False

def random_color(max=255):
    if max > 255:
        raise ValueError("max must below 256")
    color = []
    for i in range(3):
        color.append(random.randint(0,max))
    return color

class Counter(dict):
    '''如果讀不到資料補0避免keyerror'''
    def __missing__(self,key):
        return 0

class find:
    '''arg=要檢測的內容(名稱#0000,id,mention...)'''
    @staticmethod
    async def user(ctx,arg:str):
        if arg:
            try:
                member = await commands.MemberConverter().convert(ctx,str(arg))
            except commands.MemberNotFound:
                member = None
        else:
            member = None
        return member

    @staticmethod
    async def channel(ctx,arg:str):
        if arg:
            try:
                channel = await commands.TextChannelConverter().convert(ctx,str(arg))
            except commands.ChannelNotFound:
                channel = None
        else:
            channel = None
        return channel

    @staticmethod
    async def role(ctx,arg:str):
        if arg:
            try:
                role = await commands.RoleConverter().convert(ctx,str(arg))
            except commands.RoleNotFound:
                role = None
        else:
            role = None
        return role

    @staticmethod
    async def user2(ctx,arg:str):
        try:
            user = await commands.UserConverter().convert(ctx,str(arg))
        except commands.UserNotFound:
            user = None
        return user

    @staticmethod
    async def emoji(ctx,arg:str):
        try:
            emoji = await commands.EmojiConverter().convert(ctx,str(arg))
        except commands.EmojiNotFound:
            emoji = None
        return emoji

    @staticmethod
    async def guild(ctx,arg:str):
        try:
            guild = await commands.GuildConverter().convert(ctx,str(arg))
        except commands.GuildNotFound:
            guild = None
        return guild

    @staticmethod
    async def role(ctx,arg:str):
        try:
            role = await commands.RoleConverter().convert(ctx,str(arg))
        except commands.RoleNotFound:
            role = None
        return role


def fibonacci_sequence(limit):
    """Function will print all Fibonacci numbers less than or
    equal to the given limit, which will be a positive integer.
    """

    n = 1
    m = 1
    x = n + m
    sequence = []
    if m == 1:
        n = 1
        x = n + m
        sequence.append(n)
        sequence.append(m)
        sequence.append(x)

    n = 1
    m = 2
    while x < limit:
        if m > 1:
            x = n + m
        if x < limit:
            sequence.append(x)
        n = m
        m = x

    print(sequence)

limit = int(input("Enter a positive integer: "))
fibonacci_sequence(limit)


from Test_take_pic import *

class Drawing(MyWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(Drawing, self).__init__(parent)
        self.rect = None

    # 重写绘制函数
    def paintEvent(self, event):
        # 初始化绘图工具
        qp = QPainter()
        # 开始在窗口绘制
        qp.begin(self)
        # 自定义画点方法
        if self.rect:
            self.drawRect(qp)
        # 结束在窗口的绘制
        qp.end()

    def drawRect(self, qp):
        # 创建红色，宽度为4像素的画笔
        pen = QPen(Qt.red, 4)
        qp.setPen(pen)
        qp.drawRect(*self.rect)

    # 重写三个时间处理
    def mousePressEvent(self, event):
        print("mouse press")
        self.rect = (event.x(), event.y(), 0, 0)

    def mouseReleaseEvent(self, event):
        print("mouse release")

    def mouseMoveEvent(self, event):
        start_x, start_y = self.rect[0:2]
        self.rect = (start_x, start_y, event.x() - start_x, event.y() - start_y)
        self.update()

thstop = False
brgFrame = None

# 上面的这个来控制进程结束
def showcamre():
    # 参数0代表系统第一个摄像头,第二就用1 以此类推
    cap = cv2.VideoCapture(0)
    # 设置显示分辨率和FPS ,不设置的话会非常卡
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 800)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 600)
    cap.set(cv2.CAP_PROP_FPS, 20)
    while cap.isOpened():
        if thstop:
            return
        ret, frame = cap.read()
        if not ret:
            continue
        # 水平翻转,很有必要
        frame = cv2.flip(frame, 1)
        # opencv 默认图像格式是rgb qimage要使用BRG,这里进行格式转换,不用这个的话,图像就变色了,困扰了半天,翻了一堆资料
        brgFrame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
        # mat-->qimage
        qimg = QImage(brgFrame.data, brgFrame.shape[1], brgFrame.shape[0], QImage.Format_RGB888)
        demo.setpic(qimg)

if __name__ == '__main__':
    app = QApplication(sys.argv)

    demo = Drawing()
    demo.show()
    # 全屏显示
    # ex.showFullScreen()
    # 使用线程,否则程序卡死
    th = Thread(target=showcamre)
    th.start()
    app.exec_()
    # 退出的时候,结束进程,否则,关不掉进程
    thstop = True


Year = input('Input Year Of Birth: ')
Month = int(input('Input Month Of Birth (Number): '))
Day = int(input('Input Day Of Birth: '))
Century = Year[:2] + Year[4:]
Year = Year[:0] + Year[2:]
Year = int(Year)
Century = int(Century)
type(Year)
if Month > 2:
    Month -= 2
else:
    Month += 10

Week = (Day+(2.6*Month-0.2)-2*Century+Year+(Year/4)+(Century/4))%7

if Week >= 6:
    Week = 'Saturday'

elif Week >= 5:
    Week = 'Friday'

elif Week >= 4:
    Week = 'Thursday'

elif Week >= 3:
    Week = 'Wednesday'

elif Week >= 2:
    Week = 'Tuesday'

elif Week >= 1:
    Week = 'Monday'

else:
    Week = 'Sunday'

print(Week)


from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
import json
import re
import requests
import os
import lxml
import urllib.request

def envi_standards():
    # 确定root，从标准文本的首页开始工作。
    root = 'http://kjs.mee.gov.cn/hjbhbz/bzwb/'
    # 1 标定分类，确定每个分类的列表，例如水、气标准中的内容；
    website = requests.get(root).text
    soup = BeautifulSoup(website)
    url_list = []
    stop = 0
    # 爬取网站中侧栏的标题，并且将标题中的内容贴到root的后面，形成新的网址；
    for link in soup.find_all('a'):
        ful_list = link.get("href")
        if ful_list is None or len(ful_list) > 12 or len(ful_list) < 5 or "../" in ful_list:
            pass
        else:
            url_list.append(ful_list)
    lst_data =[]
    finf = './(.*?)/'
    for sample in url_list:
        u = re.compile(finf).findall(sample)
        lst_data.append(u[0])
    # 列表lst_data中就是形成的标签；

    # 2 爬去分类下各个页面下page中的url；
    def find_url(soup,lst):
        for link in soup.find_all('a'):
            fullurl = link.get('href')
            if fullurl is None or len(fullurl) <=20 or 'http' in fullurl or 'https' in fullurl:
                pass
            else:
                lst.append(fullurl)
        return lst
    # 定义函数，查找href的网址内容；
    # 确定了每一个类别标签之后，可以进行页面url的重新组合，并且形成网址，打开之后逐页进行打开并读取网址中的地址，
    url_final = []
    for lst in lst_data:
        urls = []
        root_first_url = root + lst
        first_site = requests.get(root_first_url).text
        soup_first = BeautifulSoup(first_site)
        urls = find_url(soup_first,urls)
        for i in range(2,20):
            root_second_url = root_first_url + '/index_' + str(i) + '.shtml'   # 每个类别不超过20页，可以可以进行逐页的读取，逐页组成网址；
            root_second_site = requests.get(root_second_url).text
            root_second_soup = BeautifulSoup(root_second_site)
            if root_second_soup.find_all('Not Found') is True:
                pass
            else:
                urls = find_url(root_second_soup,urls)
        for samples in urls:
            if '../' in samples:
                x = samples.replace('../','')
                final = root_first_url + '/' + x
                url_final.append(final)
            elif './' in samples:
                y = samples.replace('./','')
                final = root_first_url + '/' + y
                url_final.append(final)
            else:
                pass
    # 形成网址链接的数据库，然后对每页中的pdf链接进行读取；

    # 3 解析url 读取pdf链接，并将title 读取，并行组成以url 为key，标题为value的字典；
    pdfs = {}
    for pdf in url_final:
        second_site = requests.get(pdf).text
        soup_second = BeautifulSoup(second_site)
        for luck in soup_second.find_all('a'):
            fullurl_pdf = luck.get('href')
            if fullurl_pdf is None:
                pass
            elif fullurl_pdf.endswith('.pdf'):
                if "./" in fullurl_pdf:
                    xx = fullurl_pdf.replace('./','')
                    dd =  '(.*?)/t.'
                    ddd = re.compile(dd).findall(pdf)
                    dddd = ddd[0]
                    final_pdf = dddd + '/' + xx
                    z = '<p>(.*?)</p>'
                    got_title = requests.get(pdf).content.decode("utf-8")
                    title = re.compile(z).findall(got_title)[0]
                    pdfs.setdefault(title,final_pdf)
    return pdfs
    # 形成pdf的链接的汇总；可以对列别中的内容进行逐页的下载；

# 4 将组成的pdf url逐个下载到本地文件夹，并用value进行命名；
def getpdf(folder_path, lists):
    if not os.path.exists(folder_path):
        print("Selected folder not exist, try to create it.")
        os.makedirs(folder_path)
    for title,url in lists.items():
        print("Try downloading file: {}".format(title))
        filename = title
        filepath = folder_path + '/' + filename + '.pdf'
        if os.path.exists(filepath):
            print("File have already exist. skip")
        else:
            try:
                urllib.request.urlretrieve(url, filename=filepath)
            except Exception as e:
                print("Error occurred when downloading file, error message:")
                print(e)

if __name__ == "__main__":
    lists = envi_standards()
    root = '输入需要保存的文件夹名称'
    getpdf(root,lists)

爬取环保标准pdf.py

爬取环保标准pdf.py


d = [[0]*252 for _ in range(252)]
d[1][1] = 1
for i in range(1,252):
    for j in range(1,252):
        if i==1 and j==1:continue
        d[i][j] = d[i-1][j] + d[i][j-1]

def solution(width, height, diagonals):
    answer = 0
    for x,y in diagonals:
        answer += d[x][y+1]*d[width-x+1][height-y+2]
        answer += d[x+1][y]*d[width-x+2][height-y+1]
        answer %= 10000019
    return answer

solution(250,250,[[1,1],[2,2]])

Python/PROGRAMMERS/2022 SK ICT Faimily/problem3.py


import numpy as np

#预测精度评价指标
class evalueationIndex(object):
    def __init__(self,t_预测值,t_真实值):
        '''
        :param t_预测值:
        :param t_真实值:

        1．预测误差 e
        2．百分误差 PE
        3．平均误差 ME
        4．平均绝对误差 MAE
        5．平均绝对百分对误差 MAPE
        6．均方差 MSE
        7．误差标准差 SDE
        8．均方误差　RMSE

        res：查看是否计算结果成功

        '''

        self.res=False

        真实值 = np.array(t_真实值)
        预测值 = np.array(t_预测值)
        if(真实值.size != 预测值.size):
            return

        obj_size = 真实值.size

        # 预测误差,是个list
        self.e = 真实值-预测值
        # 绝对预测误差，是个list
        self.AE = self.e.__abs__()
        # 平均预测误差，是个值
        self.ME = self.e.sum()/obj_size
        #平均绝对预测误差，是个值
        self.MAE = self.AE.sum()/obj_size

        # 百分误差
        self.PE = self.e/真实值
        # 绝对百分误差
        self.APE = self.PE.__abs__()
        # 平均百分误差
        self.MPE = self.PE.sum() / obj_size
        # 平均绝对百分误差  可以用来衡量一个模型预测结果的好坏，计算公式如下
        self.MAPE = self.APE.sum()/obj_size

        # 均方差
        self.MSE = (self.e**2).sum()/obj_size
        # 均方误差 均方根误差是用来衡量观测值同真值之间的偏差。标准误差 对一组测量中的特大或特小误差反映非常敏感，所以，标准误差能够很好地反映出测量的精密度。
        self.RMSE = np.sqrt(self.MSE)
        # 误差标准差 观测值与其平均数偏差的平方和的平方根。标准差是用来衡量一组数自身的离散程度。
        self.SDE = self.RMSE

        self.res = True
        return
    def show(self):
        print("MAE:%f MPE:%f MAPE:%f MSE:%f RMSE:%f"%(self.MAE,self.MPE,self.MAPE,self.MSE,self.RMSE))

def test_EEvalueationIndex():
    X = [2112.40,2215.50,2479.50,2628.50,2857.00,3144.40,3430.70,3841.50,4499.30,5260.10,4584.00,5268.80,5723.80,5820.70,6125.40,6333.90]
    yl = [2074.46,2314.11,2388.03,2697.11,2816.11,3076.24,3394.35,3691.20,4151.94,4896.27,5698.20,4624.40,5778.79,6207.55,6188.02,6581.81]
    a = EvalueationIndex( yl, X)
    print(a.e)
    print(a.PE)

    print(a.AE)
    print(a.APE)

    print(a.ME, a.MPE, a.MAE, a.MAPE, a.SDE)

#Main Run Thread
if __name__=='__main__':
    test_EEvalueationIndex()


import sys
input = sys.stdin.readline
com=int(input())
edge=int(input())
vertexes={}
answer=0
visited=[False]*(com+1)

def DFS(now):
    global visited, answer
    visited[now] = True
    if vertexes.get(now) is not None:
        for near in vertexes.get(now):  # 인접 정점 확인
            if visited[near] == False:  # 방문아직 안했다면
                answer+=1   # 감염 추가
                DFS(near)

for i in range(edge):
    N,M= map(int, input().split())
    # 딕셔너리에 없으면 새로 만들고 이미 key 있으면 추가
    if vertexes.get(N) is None:
        vertexes[N]=[M]
    else:
        vertexes[N].append(M)

    if vertexes.get(M) is None:
        vertexes[M]=[N]
    else:
        vertexes[M].append(N)

DFS(1)
print(answer)


import streamlit as st
import base64
import requests
from PIL import Image
import io

#################################
#needful functions

#to resize images
# def image_resizer(image1, image2):
#   #first image
#   #second image will be resized bbased on image1 dimension
#   img1 = Image.open(image1)
#   size1 = img1.size[0]
#   size2 = img1.size[1]

#   #resizing the second image
#   img2 = Image.open(image2)
#   img3 = img2.resize((size1, size2))
#   img3.show()
#   return img3

#to get predictions
def get_prediction(image_data):
  #replace your image classification ai service URL
  url = 'https://askai.aiclub.world/5b3725b5-7b58-4028-b9fd-7e94f6b3a6c9'
  r = requests.post(url, data=image_data)
  response = r.json()['predicted_label']
  return response

#################################
#creating the web app

#title for the web app
st.title("Classify if the space is free or busy")

#subheader
st.subheader("About the projct..")
#write elements
st.write("**This web app will help you find if the parking space is empty or free**")

#showing cats images
st.image("busy.jpg", caption = "Busy space")

#showing dogs images
st.image("free.jpg", caption = "Free space")

#file uploading and prediction part

image = st.file_uploader(label="Upload an image",accept_multiple_files=False, help="Upload an image to classify them")
if image:
    #converting the image to bytes
    img = Image.open(image)

    #image to be predicted
    st.image(img, caption = "Image to be predicted")

    #converting the image to bytes
    buf = io.BytesIO()
    img.save(buf,format = 'JPEG')
    byte_im = buf.getvalue()

    #converting bytes to b64encoding
    payload = base64.b64encode(byte_im)

    #file details
    file_details = {
      "file name": image.name,
      "file type": image.type,
      "file size": image.size
    }

    #write file details
    st.write(file_details)

    #predictions
    response = get_prediction(payload)

    #prediction label
    st.markdown("This parking spot is **{}** ".format(response.split('s')[0]))