""" Perform get_iplayer commands. """

import ast
import logging
import os

from get_iplayer_downloader import search_cache, settings
from get_iplayer_downloader.tools import command, command_queue, config, string

logger = logging.getLogger(__name__)

####

RADIO_DOWNLOAD_PATH = settings.get_config().get("radio", "download-path")
TV_DOWNLOAD_PATH = settings.get_config().get("tv", "download-path")

# Labels for disabled filters
ALL_CATEGORIES_LABEL = "Categories"
ALL_CHANNELS_LABEL = "Channels"
SINCE_FOREVER_LABEL = "Since"

# Indices of a key-value pair
KEY_INDEX = 0
VALUE_INDEX = 1

####

_GET_IPLAYER_PROG = "get_iplayer"

#_SINCE_HOUR_MARGIN = 6
_SINCE_HOUR_MARGIN = string.str2int(settings.get_config().get(config.NOSECTION, "since-margin-hours", fallback=6))

_COMPACT_TOOLBAR = string.str2bool(settings.get_config().get(config.NOSECTION, "compact-tool-bar"))
_ALL_CATEGORIES_LABEL = ALL_CATEGORIES_LABEL if _COMPACT_TOOLBAR else ""
_ALL_CHANNELS_LABEL = ALL_CHANNELS_LABEL if _COMPACT_TOOLBAR else ""
_SINCE_FOREVER_LABEL = SINCE_FOREVER_LABEL if _COMPACT_TOOLBAR else ""
#_SINCE_FUTURE_LABEL = "Future"

####

# List of key-value pairs
#SINCE_LIST = [[0, _SINCE_FOREVER_LABEL], [1, _SINCE_FUTURE_LABEL],
SINCE_LIST = [[0, _SINCE_FOREVER_LABEL],
#              [  4, "4 hours"], [8, "8 hours"], [12, "12 hours"], [16, "16 hours"], [20, "20 hours"],
#              [ 24 + _SINCE_HOUR_MARGIN, "1 day" ],  [ 48 + _SINCE_HOUR_MARGIN, "2 days"],
              [  2, "2 hours"],  [  4, "4 hours"],  [6, "6 hours"],  [8, "8 hours"], [10, "10 hours"],
              [ 12, "12 hours"], [14, "14 hours"], [16, "16 hours"], [18, "18 hours"], [20, "20 hours"],
              [ 24 + _SINCE_HOUR_MARGIN, "1 day" ],  [ 48 + _SINCE_HOUR_MARGIN, "2 days"],
              [ 72 + _SINCE_HOUR_MARGIN, "3 days"],  [ 96 + _SINCE_HOUR_MARGIN, "4 days"],
              [120 + _SINCE_HOUR_MARGIN, "5 days"],  [144 + _SINCE_HOUR_MARGIN, "6 days"],
              [168 + _SINCE_HOUR_MARGIN, "7 days"]]

#30 DAYS EPISODE AVAILABILITY
#SINCE_LIST = [[0, _SINCE_FOREVER_LABEL],
#              [  4, "4 hours"], [8, "8 hours"], [12, "12 hours"], [16, "16 hours"], [20, "20 hours"],
#              [ 24 + _SINCE_HOUR_MARGIN, "1 day" ],  [ 48 + _SINCE_HOUR_MARGIN, "2 days"],
#              [ 72 + _SINCE_HOUR_MARGIN, "3 days"],  [ 96 + _SINCE_HOUR_MARGIN, "4 days"],
#              [120 + _SINCE_HOUR_MARGIN, "5 days"],  [144 + _SINCE_HOUR_MARGIN, "6 days"],
#              [168 + _SINCE_HOUR_MARGIN, "1 week"],  [336 + _SINCE_HOUR_MARGIN, "2 weeks"],
#              [504 + _SINCE_HOUR_MARGIN, "3 weeks"], [672 + _SINCE_HOUR_MARGIN, "4 weeks"]]

class Preset:
    # "preset-file": filename in folder ~/.get_iplayer/presets
    RADIO = settings.get_config().get("radio", "preset-file")
    TV = settings.get_config().get("tv", "preset-file")

class ProgType:
    ##ALL = "all"
    #ALL = "radio,tv"
    RADIO = "radio"
    TV = "tv"
    CH4 = "ch4"
    ITV = "itv"

####

# List of key-value pairs
#NOTE Cannot extend a constant list: RADIO = [[None, "Genre"]].extend(...)
#WORKAROUND see get_iplayer_gui.py (at least in Python 2.7)
#  RADIO = [[None, "Genre"]]    -->    #RADIO = [["", "Genre"]]

class Channels:
    RADIO = _ALL_CHANNELS_LABEL + "," + settings.get_config().get("radio", "channels")
    TV = _ALL_CHANNELS_LABEL + "," + settings.get_config().get("tv", "channels")
    CH4 = _ALL_CHANNELS_LABEL
    ITV = _ALL_CHANNELS_LABEL

class Categories:
    #@staticmethod
    def _merge_keys(key_value_list):
        key_list = [row[KEY_INDEX] for row in key_value_list]
        keys = ""
        for i, key in enumerate(key_list):
            #if i == 0 or not key:
            if not key:
                # Skip predefined or user-defined "all" filters
                continue
            keys += key
            if (i < len(key_list) - 1):
                keys += ","

        # Use set to avoid duplicates
        key_set = set(keys.split(","))
        keys = ",".join(key_set)

        return keys

    # No filter list
    ALL = [["", _ALL_CATEGORIES_LABEL]]

    # The filter lists below consists of all categories in the first item, followed by the categories separately

    RADIO = ast.literal_eval(settings.get_config().get("radio", "categories"))
    # Prepend
    RADIO.insert(0, [_merge_keys(RADIO), _ALL_CATEGORIES_LABEL])

    TV = ast.literal_eval(settings.get_config().get("tv", "categories"))
    # Prepend
    TV.insert(0, [_merge_keys(TV), _ALL_CATEGORIES_LABEL])

####

class SinceListIndex:
    FOREVER = 0
    #FUTURE = 1

class SearchResultColumn:
    DOWNLOAD = 0
    PID = 1
    INDEX = 2
    SERIES = 3
    EPISODE = 4
    CATEGORIES = 5
    CHANNELS = 6
    THUMBNAIL_SMALL = 7
    AVAILABLE = 8
    DURATION = 9

    # Additional data derived from fields above in this class
    LOCATE_SEARCH_TERM = 10

####

def precheck(quiet=False):
    log_output = ""

    # Check required program(s)
    # Call get_iplayer directly, instead of wrapping it in "shell code", to check whether it is installed or not
    process_output =  command.run(_GET_IPLAYER_PROG + " --usage", quiet=True, temp_pathname=settings.TEMP_PATHNAME)
    #TODO not Linux specific ("not found")
    if quiet and "not found" in process_output:
        # command.run() already logs the error (logger.warning())
        log_output += "WARNING:{0}".format(process_output)

    # Check get_iplayer preset files
    if not string.str2bool(settings.get_config().get(config.NOSECTION, "disable-presets")):
        pathname = os.path.join(os.path.expanduser("~"), ".get_iplayer", "presets")
        for preset in [Preset.RADIO, Preset.TV]:
            filename = os.path.join(pathname, preset)
            if not os.path.exists(filename):
                msg = "preset file {0} does not exist".format(filename)
                logger.warning(msg)
                log_output += "WARNING:{0}".format(msg)

    return log_output

#NOTE Logging is not fully initialized yet
#check_preset_files()

####

def categories(search_text, preset=None, prog_type=None):
    """ Run get_iplayer --list=categories.
        Return table with columns: categories, categories (key-value pair).
    """

    cmd = _GET_IPLAYER_PROG
    if preset:
        cmd += " --preset=" + preset
    if prog_type:
        cmd += " --type=" + prog_type
    cmd += " --list=categories --nocopyright"
    if search_text:
        cmd += " \"" + search_text + "\""

    process_output = command.run(cmd, quiet=True)

    lines = process_output.splitlines()
    output_lines = []
    for line in lines:
        # Skip empty or message lines
        if line and line[0] and not line.startswith("INFO:") and not line.startswith("Matches:"):
            # Strip the count number from the categories name
            categories_key = line.rsplit(" ", 1)[0].rstrip()
            categories_value = categories_key
            output_lines.append([categories_key, categories_value])

    return output_lines

def channels(search_text, preset=None, prog_type=None, compact=False):
    """ Run get_iplayer --list=channel. @compact is False: strip leading "BBC " substring.
        Return comma-separated list of channels.
    """

    cmd = _GET_IPLAYER_PROG
    if preset:
        cmd += " --preset=" + preset
    if prog_type:
        cmd += " --type=" + prog_type
    cmd += " --list=channel --nocopyright"
    if search_text:
        cmd += " \"" + search_text + "\""

    process_output = command.run(cmd, quiet=True)

    lines = process_output.splitlines()
    first_value = True
    output_line = ""
    for line in lines:
        # Skip empty or message lines
        if line and line[0] and not line.startswith("INFO:") and not line.startswith("Matches:"):
            if first_value:
                first_value = False
            else:
                output_line += ","
            if compact and line.startswith("BBC "):
                # Remove leading "BBC " substring
                line = line[len("BBC "):]
            # Strip the count number from the channel name
            output_line += line.rsplit(" ", 1)[0].rstrip()

    return output_line

def search(search_text, preset=None, prog_type=None,
           channels=None, exclude_channels=None,
           categories=None, exclude_categories=None,
           since=0, future=False):
    """ Run get_iplayer (--search).
        Return search result in a table with columns listed in SearchResultColumn.
        If cached search results are present, return that instead.
    """

    output_lines = search_cache.get(prog_type)
    if output_lines is not None:
        # Skip 'get_iplayer --search' when search results have been cached
        return output_lines

    ####

    # PERL_UNICODE=S : avoid "Wide character in print" warning/error messages
    #cmd = _GET_IPLAYER_PROG
    cmd = "PERL_UNICODE=S " + _GET_IPLAYER_PROG
    #if not preset:
    #    #cmd += " --type=all"
    #    cmd += " --type=" + ProgType.ALL
    #else:
    if preset:
        cmd += " --preset=" + preset
    if prog_type:
        cmd += " --type=" + prog_type
    if channels:
        cmd += " --channel=\"" + channels + "\""
    if exclude_channels:
        cmd += " --exclude-channel=\"" + exclude_channels + "\""
    if categories:
        cmd += " --category=\"" + categories + "\""
    if exclude_categories:
        cmd += " --exclude-category=\"" + exclude_categories + "\""
    if since:
        cmd += " --since=" + str(since)
    if future:
        cmd += " --future"
    cmd += " --listformat=\"<pid>|<index>|<name>|<episode> ~ <desc>|<categories>|<channel>|<thumbnail>|<available>|<duration>\""
    # --fields: perform the same search as with "--long" plus on "pid"
    cmd += " --fields=\"name,episode,desc,pid\" --nocopyright"
    if search_text:
        # Simple exclude search option
        if search_text.startswith("-"):
            cmd += " --exclude=\"" + search_text[1:] + "\""
        else:
            cmd += " \"" + search_text + "\""
    else:
        # Wildcard search
        cmd += " \".*\""

    process_output = command.run(cmd)

    # Convert the process output lines directly to lists, matching the GtkTreeStore model data. Do not create intermediate data/interfaces
    lines = process_output.splitlines()
    output_lines = []
    title_prev = None
    level = 0
    copy = False
    for line in lines:
        if not "|" in line:
            # Skip (log) message lines
            continue;

        #NOTE with "def __len__()" in a metaclass: l = line.split("|", len(SearchResultColumn) - 1)
        l = line.split("|", 11 - 1)     # , len(SearchResultColumn) - 1)

        # Make sure the line array contains at least 11 items (avoid IndexError exception)
        # This better than catching IndexError exceptions below, which currently will discard the whole episode line
        # TODO sanitize process_output.
        #      An episode description sometimes contain a newline character or a | character.
        #      Split() will only split the first line
        for unused in range(len(l), 11):     # , len(SearchResultColumn.attributes))
            l.extend([''])
        #ALTERNATIVE catch exceptions

        # Skip empty lines
        if l[0]:
            # Match string containing only spaces
            #ALTERNATIVE
            #1) all(c in " " for c in l)
            #2) p = re.compile('[ -]+$'); p.match(l)
            #3) re.match("^[ ]+$", l)
            if level == 0 and l[2] != title_prev:
                # Going from series level (parent/root/level 0) to episode level (child/leave/level 1)
                level = 1
                copy = True
#                if title_prev:
                # Add series line
                try:
                    output_lines.append([False, None, None, l[2], None, l[4], l[5], l[6], l[7], l[8], l[2]])
                except IndexError:    # as exc:
                    pass
            elif level == 1 and l[2] != title_prev:
               # Going from episode level (child/leave/level 1) to series level (parent/root/level 0)
               level = 0
               copy = False

            if level == 1 and copy:
                # Add an episode line
                try:
                    if l[3].startswith(" ~ "):
                        # No episode title
                        output_lines.append([False, l[0], l[1], None, l[3][len(" ~ "):], l[4], l[5], l[6], l[7], l[8], None])
                    elif l[3].endswith(" ~ "):
                        # No episode description
                        output_lines.append([False, l[0], l[1], None, l[3][:len(l[3])-len(" ~ ")], l[4], l[5], l[6], l[7], l[8], None])
                    else:
                        output_lines.append([False, l[0], l[1], None, l[3], l[4], l[5], l[6], l[7], l[8], None])
                except IndexError:    # as exc:
                    pass

            title_prev = l[2]

    return output_lines

def get(search_term_list, pid=True, pvr_queue=False, preset=None, prog_type=None,
        alt_recording_mode=False, dry_run=False, force=False, output_path=None,
        categories=None, future=False):
    """ Run get_iplayer --get, get_iplayer --pid or get_iplayer --pvrqueue.
        If @pid is true, then @search_term_list contains pids.
        Return tuple: launched boolean, process output string.
    """

    if preset == Preset.RADIO:
        output_path = RADIO_DOWNLOAD_PATH
    elif preset == Preset.TV:
        output_path = TV_DOWNLOAD_PATH
    else:
        output_path = None

    #WORKAROUND Preset can be None: disable-presets is true AND data models and configuration are based on presets, not on programme types
    #if preset and string.str2bool(settings.get_config().get(preset, "run-in-terminal")):
    #    terminal_prog = settings.get_config().get(config.NOSECTION, "terminal-emulator")
    #else:
    #    terminal_prog = None
    preset_fallback = None
    if preset:
        preset_fallback = preset
    else:
        # Determine preset from programme type
        if prog_type == ProgType.RADIO:
            preset_fallback = Preset.RADIO
        elif prog_type == ProgType.TV:
            preset_fallback = Preset.RADIO
    if prog_type and string.str2bool(settings.get_config().get(preset_fallback, "run-in-terminal")):
            terminal_prog = settings.get_config().get(config.NOSECTION, "terminal-emulator")
    else:
        terminal_prog = None

    if alt_recording_mode:
        if prog_type == ProgType.CH4:
            alt_radio_modes = ""
            alt_tv_modes = "flashnormal"
        elif prog_type == ProgType.ITV:
            alt_radio_modes = ""
            alt_tv_modes = "itvnormal,itvhigh,itvlow"
        else:
            alt_radio_modes = settings.get_config().get(Preset.RADIO, "recording-modes")
            alt_tv_modes = settings.get_config().get(Preset.TV, "recording-modes")

    #cmd = "( for i in"
    #for search_term_row in search_term_list:
    #    cmd += " " + search_term_row[SearchTermColumn.PID_OR_INDEX]
    #cmd += "; do " + _GET_IPLAYER_PROG
    cmd = ""
    for i, search_term in enumerate(search_term_list):
        cmd += _GET_IPLAYER_PROG + " --hash"
        if preset:
            cmd += " --preset=" + preset
        #WORKAROUND Preset can be None: disable-presets is true AND models and configuration are based on presets, not on programme types
        #    if alt_recording_mode:
        #        if preset == Preset.RADIO and alt_radio_modes:
        #            #cmd += " --modes=\"" + alt_radio_modes + "\""
        #            cmd += " --radiomode=\"" + alt_radio_modes + "\""
        #        elif preset == Preset.TV and alt_tv_modes:
        #            #cmd += " --modes=\"" + alt_tv_modes + "\""
        #            cmd += " --tvmode=\"" + alt_tv_modes + "\""
        if alt_recording_mode:
            if preset_fallback == Preset.RADIO and alt_radio_modes:
                #cmd += " --modes=\"" + alt_radio_modes + "\""
                cmd += " --radiomode=\"" + alt_radio_modes + "\""
            elif preset_fallback == Preset.TV and alt_tv_modes:
                #cmd += " --modes=\"" + alt_tv_modes + "\""
                cmd += " --tvmode=\"" + alt_tv_modes + "\""

        if prog_type:
            cmd += " --type=" + prog_type
        cmd += " --nocopyright"
        if force:
            cmd += " --force --overwrite"
        if output_path:
            cmd += " --output=\"" + output_path + "\""

        #if pvr_queue or future:
        if pvr_queue:
            if not preset:
                return False
            # Must explicitly specify programme type and PID on the command line when in pvr queue mode
            cmd += " --pvrqueue --pid="
            #cmd += " --pvr-exclude=" + ",".join(exclude_search_term_list)
        elif pid:
            cmd += " --pid="
        else:
            cmd += " --get "
        ##cmd += "\"$i\" ; done"
        #cmd += "$i; done )"
        if search_term:
            #TEMP if search_term is a PID and the PID is numeric,
            #     then add a leading non-digit character to the PID
            #     so that get_iplayer will not assume the search_term to be an index
            if " " not in search_term and prog_type in [Channels.CH4, Channels.ITV]:
                search_term = " " + search_term

            # search_term_list could be a set of episode indices, so don't surround them with quotes
            cmd += search_term

        if (i < len(search_term_list) - 1):
            #cmd += "; "
            cmd += "; echo '----'; "

    if pvr_queue or dry_run:
        launched = True
        process_output = command.run(cmd, dry_run=dry_run, temp_pathname=settings.TEMP_PATHNAME)
    else:
        #CommandQueue.CommandQueue().run(...)
        launched = command_queue.run(cmd, temp_pathname=settings.TEMP_PATHNAME,
                                     terminal_prog=terminal_prog, terminal_title="get_iplayer get")
        process_output = None

    return (launched, process_output)

def info(pid, search_term, preset=None, prog_type=None, proxy_disabled=False, future=False):
    """ Run 'get_iplayer --info [--pid=<pid>] [<search term>]'.
        Return table with columns: series title, episode title plus description.
    """

    #if not pid:
    #    return ""

    # Only useful from outside the UK:
    #     If proxy_disabled is true then info retrieval may be faster but the info
    #     will not contain proper values for "modes" and "tvmodes" (the available TV download file sizes)

    cmd = _GET_IPLAYER_PROG + " --info"
    if preset:
        cmd += " --preset=" + preset
    if prog_type:
        cmd += " --type=" + prog_type
    if proxy_disabled:
        cmd += " --proxy=0"
    if future:
        cmd += " --future"
    cmd += " --nocopyright"
    cmd += " --thumbsize=512"

    # --fields: perform the same search as with --long plus on PID
    #cmd += " --fields=\"name,episode,desc,pid\"
    cmd += " --pid=" + pid
    if search_term:
        cmd += " --long" + " \"" + search_term + "\""

    process_output = command.run(cmd)

    lines = process_output.splitlines()
    output_lines = []
    for line in lines:
        # Skip empty or message lines
        if line and line[0] and not line.startswith("INFO:") and not line.startswith("Matches:"):
            l = line.split(":", 1)
            # Match key-value pairs
            if len(l) == 2 and l[1]:
                output_lines.append([l[0], l[1].lstrip()])

    return output_lines

def refresh(preset=None, prog_type=None, channels=None, exclude_channels=None, force=False, future=False):
    """ Run get_iplayer --refresh. Return error code. """

    if search_cache.has_cache(prog_type):
        # Skip 'get_iplayer --refresh' when search results have been cached
        return

    ####

    #if not preset:
    #    #preset = Preset.RADIO + "," + Preset.TV
    #    preset = "all"

    cmd = _GET_IPLAYER_PROG + " --refresh"
    if future:
        cmd += " --refresh-future"
    if channels:
        #cmd += " --channel=\"" + channel + "\""
        cmd += " --refresh-include=\"" + channels + "\""
    if exclude_channels:
        #cmd += " --exclude-channel=\"" + exclude_channel + "\""
        cmd += " --refresh-exclude=\"" + exclude_channels + "\""
    #if preset:
    #    cmd += " --preset=" + preset
    if prog_type:
        cmd += " --type=" + prog_type
    if force:
        cmd += " --force"
    cmd += " --nocopyright"

    if preset is None:
        ret1 = command.run(cmd + " --preset=" + Preset.RADIO, temp_pathname=settings.TEMP_PATHNAME)
        ret2 = command.run(cmd + " --preset=" + Preset.TV, temp_pathname=settings.TEMP_PATHNAME)
        return ret2 if ret2 != 0 else ret1
    else:
        return command.run(cmd + " --preset=" + preset)


import pandas as pd
import numpy as np
import pickle

qualifying = pd.read_csv("data/qualifying.csv")
qualifying = qualifying.replace('\\N', np.nan)  # replace \N by NaN

def time_in_miliseconds(x):
    """
    Takes a string with mm:ss.ms
    and returns minutes, seconds, ms and value in ms.
    """
    try:
        minute = int(x.split(":")[0])
        seconds = int(x.split(":")[1].split(".")[0])
        miliseconds = int(x.split(":")[1].split(".")[1])
        best_in_mili = minute * 60000 + seconds * 1000 + miliseconds
        return [minute, seconds, miliseconds, best_in_mili]
    except:
        return [np.NaN, np.NaN, np.NaN, np.NaN]

# translate times to ms
# applies function to all rows of best_qualy and returns one column per list object (expand)
# but we keep just the last
for q in ['q1', 'q2', 'q3']:
    qualifying[q + ("_ms")] = qualifying.apply(
        lambda x: time_in_miliseconds(x[q]), axis=1, result_type='expand')[3]

# min valid qualy time
qualifying['best_qualy_ms'] = qualifying.apply(
    lambda x: min(x.q1_ms, x.q2_ms, x.q3_ms), axis=1)

# min per group.
# returns a series with the group as index
min_qualy_by_race = qualifying.groupby('raceId')['best_qualy_ms'].min()

# percentage  difference to the min of the race qualy
# filling with 0.1 if don't have qualy time. Totally arbitrary for now
qualifying['dif_to_min_perc'] = qualifying.apply(lambda x: (
    x.best_qualy_ms - min_qualy_by_race[x.raceId])/min_qualy_by_race[x.raceId], axis=1).fillna(0.1)

# export
pickle.dump(qualifying, open("working/qualifying.p", "wb"))


def solution(a,b):
    sum = 0
    minimum = b*b
    for i in range(1,b):
        if i*i >= a and i*i<=b:
           sum += i*i
           if minimum >= i*i:
               minimum = i*i
           else:
               minimum = minimum
    if(sum==0):
        print(-1)
    else:
        print(sum)
        print(minimum)

M = int(input())
N = int(input())
solution(M,N)


import random
import os
from dateutil.parser import parse
from datetime import timedelta
from sqlalchemy.sql import text
from dacc import models, db
from dacc import insertion

APPS = ["ecolyo"]

def generate_groups(measure_definition):
    group1 = None
    group2 = None
    group3 = None

    fake_group_values = ["fake1", "fake2", "fake3"]

    if measure_definition.name == "connection-count-daily":
        group1_val = random.choice(["mobile", "desktop"])
        group1 = {"device": group1_val}
    elif measure_definition.name == "konnector-event-daily":
        group1_val = random.choice(["grdf", "edf", "egl"])
        group2_val = random.choice(["connexion", "refresh"])
        group3_val = random.choice(["success", "error"])

        group1 = {"slug": group1_val}
        group2 = {"event_type": group2_val}
        group3 = {"status": group3_val}

    elif measure_definition.name == "energy-consumption-daily":
        group1_val = random.choice(["electricity", "water", "gas"])
        group1 = {"energy_type": group1_val}

    else:
        if measure_definition.group1_key is not None:
            group1 = {
                measure_definition.group1_key: random.choice(fake_group_values)
            }
        if measure_definition.group2_key is not None:
            group2 = {
                measure_definition.group2_key: random.choice(fake_group_values)
            }
        if measure_definition.group1_key is not None:
            group3 = {
                measure_definition.group3_key: random.choice(fake_group_values)
            }
    return (group1, group2, group3)

def generate_random_raw_measures(
    n_measures,
    n_days,
    starting_day,
    measure_name,
    created_by=None,
    group1=None,
    group2=None,
    group3=None,
):
    try:
        measures = []
        starting_day = parse(starting_day)
        days = [starting_day + timedelta(days=i) for i in range(n_days)]
        defs = models.MeasureDefinition.query.all()
        if not defs:
            print("Please insert measures definition first.")
            return

        for i in range(n_measures):
            if measure_name is None:
                m_def = random.choice(defs)
                _measure_name = m_def.name
            else:
                _measure_name = measure_name
                m_def = models.MeasureDefinition.query_by_name(measure_name)
                if m_def is None:
                    print("Measure not found: {}".format(measure_name))
                    return

            measure = {
                "measureName": _measure_name,
                "value": random.randint(0, 100),
                "startDate": random.choice(days).isoformat(),
                "createdBy": created_by or random.choice(APPS),
            }

            if group1:
                measure["group1"] = group1
            if group2:
                measure["group2"] = group2
            if group3:
                measure["group3"] = group3
            _group1 = None
            _group2 = None
            _group3 = None
            if group1 is None and group2 is None and group3 is None:
                _group1, _group2, _group3 = generate_groups(m_def)
            if _group1:
                measure["group1"] = _group1
            if _group2:
                measure["group2"] = _group2
            if _group3:
                measure["group3"] = _group3

            measures.append(measure)
        return measures
    except Exception as e:
        print("Exception during fixture insertion: " + repr(e))

def insert_random_raw_measures(
    n_measures,
    n_days,
    starting_day,
    measure_name=None,
    created_by=None,
    group1=None,
    group2=None,
    group3=None,
):
    measures = generate_random_raw_measures(
        n_measures,
        n_days,
        starting_day,
        measure_name,
        created_by,
        group1,
        group2,
        group3,
    )
    if not measures:
        return
    for measure in measures:
        insertion.insert_raw_measure(measure)
        print("Raw measure inserted : {}".format(measure))

def insert_from_fixture_file(file_name):
    try:
        file_path = os.path.join(os.path.dirname(__file__), file_name)
        with open(file_path, "r") as f:
            query = text(f.read())
            print("Insert from fixture...")
            print(query)
            db.session.execute(query)
    except Exception as e:
        print("Exception during fixture insertion: " + repr(e))

def insert_raw_measures_from_file():
    insert_from_fixture_file("raw_measures.sql")

def insert_measures_definition_from_file():
    insert_from_fixture_file("measures_definition.sql")

def insert_aggregation_dates_from_file():
    insert_from_fixture_file("aggregation_dates.sql")


import socket
import cv2
import numpy
from select import *
from _thread import *

def recvall(sock, count):
    buf = b''
    while count:
        newbuf = sock.recv(count)
        if not newbuf: return None
        buf += newbuf
        count -= len(newbuf)
    return buf

def threaded(client_socket, addr):

    print('Connected by :', addr[0], ':', addr[1]) # addr[0] 클라이언트 주소, addr[1] 접속한 클라이언트 포트

    n = 0
    while True:

        try:

            data = client_socket.recv(1024)        #client로 부터 1을 받음

            if not data:
                print('Disconnected by ' + addr[0],':',addr[1])
                break

            message = '2'
            client_socket.send(message.encode())

            length = recvall(client_socket,16)

            stringData = recvall(client_socket, int(length))
            data = numpy.frombuffer(stringData, dtype="uint8")

            decimg = cv2.imdecode(data,1)
            cv2.imshow('Image', decimg)
            cv2.imwrite('images/test.jpg',decimg)
            n += 1

            key = cv2.waitKey(1)
            if key == 27:                #esc누르면 종료
                break

        except ConnectionResetError as e:

            print('Disconnected by ' + addr[0],':',addr[1])
            break

    client_socket.close()

HOST = '127.0.0.1'
PORT = 9999

server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('', PORT))

server_socket.listen()

print('server start')
socketList = [server_socket]

while True:

    print('wait')

    try:
        read_socket, write_socket, error_socket = select(socketList, [], [], 1)

        for sock in read_socket:
            if sock == server_socket:
                client_socket, addr = server_socket.accept()
                start_new_thread(threaded, (client_socket, addr,))
    except KeyboardInterrupt:
        break

server_socket.close()


# -*- coding = utf-8 -*-
# Time: 2022/4/8 22:23
# Author: Mr Wu
# File: 7.变量的作用域.py
# Software: PyCharm

# 变量的作用域
# 1.程序代码能访问该变量的区域
# 2.根据变量的有效范围可分为：
# <1> 局部变量：
#        在函数内定义并使用的变量，只在函数内部有效，局部变量使用global声明，这个变量就会变成全局变量
def fun(a,b):
    c=a+b
# c,就称为局部变量，因为c是在函数体内进行定义的变量。a,b函数的形参，作用范围也是函数内部，相当于局部变量
    print(c)
# print(c)  # 报错，因为a超出了起作用的范围(超出了作用域)
# print(c)  # 报错，因为c超出了起作用的范围(超出了作用域)
fun(10,20)

# <2> 全局变量：
#        函数体外定义的变量，可作用于函数内外
name = '杨老师'  # name的作用范围为函数内部和外部都可以使用-->称为全局变量
print(name)
def fun():
    print(name)
fun()

# <3> global：把局部变量变为全局变量
def fun():
    global age  # 把局部变量变为全局变量
    age = 20
    print(age)
fun()
print(age)

8.函数/7.变量的作用域.py


import os

from cinn_for_imaging.datasets.fast_mri.data_util import FastMRIDataModule
from cinn_for_imaging.datasets.lodopab.data_util import LoDoPaBDataModule

import matplotlib.pyplot as plt
import matplotlib
import torch
import torch.nn as nn
from dival.util.torch_utility import TorchRayTrafoParallel2DAdjointModule
from odl.tomo.analytic import fbp_filter_op
from odl.contrib.torch import OperatorModule
from tqdm import tqdm

class FBPModule(torch.nn.Module):
    """
    Torch module of the filtered back-projection (FBP).

    Methods
    -------
    forward(x)
        Compute the FBP.

    """

    def __init__(self, ray_trafo, filter_type='Hann',
                 frequency_scaling=1.):
        super().__init__()
        self.ray_trafo = ray_trafo
        filter_op = fbp_filter_op(self.ray_trafo,
                          filter_type=filter_type,
                          frequency_scaling=frequency_scaling)
        self.filter_mod = OperatorModule(filter_op)
        self.ray_trafo_adjoint_mod = (
            TorchRayTrafoParallel2DAdjointModule(self.ray_trafo))

    def forward(self, x):
        x = self.filter_mod(x)
        x = self.ray_trafo_adjoint_mod(x)
        return x

#%% setup the dataset
dataset_mri = FastMRIDataModule(num_data_loader_workers=os.cpu_count(),
                            batch_size=1)
dataset_mri.prepare_data()
dataset_mri.setup()

#%% setup the LoDoPaB dataset
dataset_ct = LoDoPaBDataModule(impl='astra_cuda', sorted_by_patient=True,
                            num_data_loader_workers=8, batch_size=1)
dataset_ct.prepare_data()
dataset_ct.setup()
ray_trafo = dataset_ct.ray_trafo

fbp = FBPModule(ray_trafo)
ray_trafo_op = OperatorModule(ray_trafo)

num_test_images = 10

"""
for i, batch in tqdm(zip(range(num_test_images),dataset_mri.train_dataloader()),
                        total=num_test_images):

    rec = batch[0]
    gt = batch[1]
    masked_kspace = batch[2]

    print(rec.shape, gt.shape, masked_kspace.shape)

    fig, (ax1, ax2, ax3) = plt.subplots(1,3)
    current_cmap = plt.get_cmap('gray').copy()#matplotlib.cm.get_cmap().copy()
    current_cmap.set_bad(color='black')
    ax1.imshow(rec[0][0], cmap="gray")
    ax2.imshow(gt[0][0], cmap="gray")
    ax3.imshow(20*torch.log(torch.abs(torch.view_as_complex(masked_kspace)[0][0])), cmap=current_cmap,interpolation='none')
    ax1.axis("off")
    ax2.axis("off")
    ax3.axis("off")
    plt.show()
"""

for i, batch in tqdm(zip(range(num_test_images),dataset_ct.train_dataloader()),
                        total=num_test_images):

    y, x = batch
    print(x.shape, y.shape)
    fbp_reco = fbp(y)
    fig, (ax1, ax2, ax3) = plt.subplots(1,3)

    ax1.imshow(x[0][0], cmap="gray")
    ax2.imshow(y[0][0], cmap="gray")
    ax3.imshow(fbp_reco[0][0], cmap="gray")

    #ax3.imshow(20*torch.log(torch.abs(torch.view_as_complex(masked_kspace)[0][0])), cmap=current_cmap,interpolation='none')
    ax1.axis("off")
    ax2.axis("off")
    ax3.axis("off")
    plt.show()


from django.conf.urls import patterns, include, url

urlpatterns = patterns('livros.views',
    url(r'^adicionar/$', 'livroAdicionar'),
    url(r'^editar/(?P<pk>\d+)/$', 'livroEditar'),
    url(r'^salvar/$', 'livroSalvar'),
    url(r'^pesquisar/$', 'livroPesquisar'),
    url(r'^excluir/(?P<pk>\d+)/$', 'livroExcluir'),
    url(r'^$', 'livroListar'),
)


# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

from ansible.errors import AnsibleError

def error(msg, ignore=False):
    """Raise error unless errors should be ignored."""
    if ignore:
        return None
    else:
        raise AnsibleError(msg)

def get(data, path):
    """
    Recursively get the value of the key path `path` in `data`.

    Path should be a list of string keys. For each item in the path, a lookup
    will be performed.

    If the data is a dict, a normal key lookup will be performed.

    If the data is a list and the key is convertible to a number, the index
    will be returned. If the data is a list and the key is '*', the rest of
    the key path will be obtained from each item in the list.

    Parameters:
    `data` -- Nested dict or list.
    `path` -- List of string keys.
    """
    if len(path) <= 0:
        return data

    key, rest = path[0], path[1:]
    if isinstance(data, dict):
        return get(data[key], rest)
    elif isinstance(data, list):
        if key == '*':
            return [get(d, rest) for d in data]
        else:
            try:
                index = int(key)
            except:
                error("'%s' is not numeric index for list '%s'" % (key, data))
            return get(data[index], rest)
    else:
        raise AnsibleError("expected list or dict, got '%s'" % data)

def lookup(data, key, skip):
    """Look up the key path `key` in `data`.

    Parameters:
    `data` -- Nested dict or list.
    `key`  -- String path separated by '.'.
    `skip` -- Return none instead of raising errors when key path does not
              exist in `data`.
    """
    path = key.split(".")
    try:
        return get(data, path)
    except KeyError:
        error("could not find '%s' in '%s'" % (key, data), skip)
    except IndexError:
        error("index '%s' out of bounds in '%s'" % (key, data), skip)

def dictmap(items, schema, skip_absent=False):
    """
    Remap items into a dictionary described by `schema`.

    This constructs a dictionary for each item, based on the dictionary
    `schema`. Each path in the schema will be replaced by a lookup for that
    path.

    Parameters:
    `items`       -- A list of items.
    `schema`      -- A dictionary with names and paths.
    `skip_absent` -- If set to 'True', skips all instances that are missing
                     key or index values. If set to False, a partial object
                     will be return with only the matching values. Defaults to
                     False.
    """
    result = []
    for item in items:
        thing = {}
        for k, v in schema.items():
            value = lookup(item, v, skip_absent)
            if value is None and skip_absent:
                thing = None
                break
            thing[k] = value
        if thing is not None:
            result.append(thing)
    return result

class FilterModule(object):

    """Custom Megalomaniacs Ansible filters."""

    def filters(self):
        """Return available filter functions mapping."""
        return {
            'dictmap': dictmap,
        }


import re

with open('../input/maximallain.txt','r') as f :
	lines = f.readlines()

lines = sorted(lines)
main_dict = {}
id_temp = -1

for line in lines :
	info = re.compile("\W+").split(line)

	if info[6] == 'Guard':
		if id_temp != -1 :
			main_dict[id_temp]['count'] += count_temp

		#Stocke l'id
		id_temp = info[7]
		count_temp = 0

		if id_temp not in main_dict.keys():
			main_dict[id_temp] = {'count' : 0, 'details' : dict(zip([i for i in range(60)],[0 for i in range(60)]))}
		else :
			main_dict[id_temp]['count'] += 1

	elif info[6] == 'falls' :
		min_temp = int(info[5])
	else :
		for i in range(min_temp, int(info[5])):
			main_dict[id_temp]['details'][i] += 1
			count_temp += 1

max_count = 0
max_id = 0

for key, value in main_dict.items():
	print(max_count, value['count'])
	if value['count'] > max_count :
		max_id = key
		max_count = value['count']

max_min = 0
print(main_dict[max_id])
for key, value in main_dict[max_id]['details'].items() :
	print(value)
	if value > max_min :
		max_min = key

print(max_id)
print(max_min)
print(int(max_id)*int(max_min))


from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, Http404
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required

from .models import Topic, Entry, Booklist, Book
from .forms import TopicForm, EntryForm, BooklistForm

# Create your views here.

def index(request):
    """The home page for Learning Log."""
    return render(request, 'learning_logs/index.html')

@login_required
def topics(request):
    """Show all topics"""
    topics = Topic.objects.filter(owner=request.user).order_by('date_added')
    context = {'topics': topics}
    return render(request, 'learning_logs/topics.html', context)

@login_required
def topic(request, topic_id):
    """Show a single topic and all its entries."""
    topic = get_object_or_404(Topic, id=topic_id)
    # Make sure the topic belongs to the current user.
    if topic.owner != request.user:
        raise Http404

    entries = topic.entry_set.order_by('-date_added')
    context = {'topic': topic, 'entries': entries}
    return render(request, 'learning_logs/topic.html', context)

@login_required
def new_topic(request):
    """Add a new topic."""
    if request.method != 'POST':
        # No data submitted; create a blank form.
        form = TopicForm()
    else:
        # POST data submitted; process data.
        form = TopicForm(request.POST)
        if form.is_valid():
            new_topic = form.save(commit=False)
            new_topic.owner = request.user
            new_topic.save()
            return HttpResponseRedirect(reverse('learning_logs:topics'))

    context = {'form': form}
    return render(request, 'learning_logs/new_topic.html', context)

@login_required
def new_entry(request, topic_id):
    """Add a new entry for a particular topic."""
    # topic = get_object_or_404(Topic, id=topic_id)
    topic = Topic.objects.get(id=topic_id)

    if request.method != 'POST':
        # No data submitted; create a blank form.
        if check_topic_owner(request, topic_id):
            form = EntryForm()
        else:
            raise Http404
    else:
        # POST data submitted; process data.
        form = EntryForm(data=request.POST)
        new_entry = form.save(commit=False)
        new_entry.topic = topic
        if form.is_valid():
            if check_topic_owner(request, topic_id):
                new_entry.save()
                return HttpResponseRedirect(reverse('learning_logs:topic',
                                                    args=[topic_id]))
            else:
                raise Http404

    context = {'topic': topic, 'form': form}
    return render(request, 'learning_logs/new_entry.html', context)

@login_required
def edit_entry(request, entry_id):
    """Edit an existing entry."""
    entry = get_object_or_404(Entry, id=entry_id)
    #topic = get_object_or_404(Topic, id=entry.topic.id)
    topic = entry.topic
    topic_id = entry.topic.id

    if topic.owner != request.user:
        raise Http404

    if request.method != 'POST':
        # Initial rquest; pre-fill form with the current entry.
        form = EntryForm(instance=entry)
    else:
        # POST data submitted; process data.
        form = EntryForm(instance=entry, data=request.POST)
        if form.is_valid():
            if check_topic_owner(request, topic_id):
                form.save()
                return HttpResponseRedirect(reverse('learning_logs:topic',
                                                    args=[topic.id]))
            else:
                raise Http404

    context = {'entry': entry, 'topic': topic, 'form': form}
    return render(request, 'learning_logs/edit_entry.html', context)

def check_topic_owner(request, topic_id):
    """get user for a particular topic."""
    topic = Topic.objects.get(id=topic_id)
    if topic.owner == request.user:
        return True
    else:
        return False

def search(request):
    """Show search results."""
    if request.method != 'GET':
        raise Http404
    else:
        q = request.GET.get('searchquery', '')
        # api_url = 'http://openlibrary.org/search.json?title=' + q
        context = {'query': q}
        return render(request, 'learning_logs/search.html', context)

@login_required
def booklists(request):
    """Show all booklists"""
    booklists = Booklist.objects.filter(
        owner=request.user).order_by('date_added')
    context = {'booklists': booklists}
    return render(request, 'learning_logs/booklists.html', context)

@login_required
def books(request, booklist_id):
    """Show books for the given Booklist."""
    return render(request, 'learning_logs/index.html')

@login_required
def new_booklist(request):
    """Add a new booklist."""
    if request.method != 'POST':
        # No data submitted; create a blank form.
        form = BooklistForm()
    else:
        # POST data submitted; process data.
        form = BooklistForm(request.POST)
        if form.is_valid():
            new_booklist = form.save(commit=False)
            new_booklist.owner = request.user
            new_booklist.save()
            return HttpResponseRedirect(reverse('learning_logs:booklists'))

    context = {'form': form}
    return render(request, 'learning_logs/new_booklist.html', context)


#To calculate average score of player

#variable declaration

game_a=49
game_b=102
game_c=10
game_d=13
game_e=34

total_runs=game_a+game_b+game_c+game_d+game_e
avg_score = (total_runs/5)
print("Total runs= " + str(total_runs))
print("Average =" + str(total_runs/5))

#calculate run rate

runs_scored=102
overs_played=6*6
runrate=runs_scored/overs_played
print(runrate)