vowels = {'a', 'e', 'i', 'o', 'u'}
naughty_strings = {"ab", "cd", "pq", "xy"}

def three_vowels(name):
    vowel_count = 0
    for c in name:
        if c in vowels:
            vowel_count += 1
    return vowel_count >= 3

def twice_in_a_row(name):
    n = len(name)
    for i in range(1, n):
        if name[i] == name[i - 1]:
            return True
    return False

def no_naughty_strings(name):
    n = len(name)
    for i in range(2, n+1):
        if name[i-2:i] in naughty_strings:
            return False
    return True

# takes a name and returns whether it is nice or naughty
def is_nice(name):
    return three_vowels(name) and twice_in_a_row(name) and no_naughty_strings(name)

samples_and_solutions = {
    "ugknbfddgicrmopn": True,
    "aaa": True,
    "jchzalrnumimnmhp": False,
    "haegwjzuvuyypxyu": False,
    "dvszwmarrgswjxmb": False
}

for name, niceness in samples_and_solutions.items():
    print(is_nice(name) == niceness)

strings = None
with open('input.txt') as f:
    strings = f.read()
assert(strings)
strings = strings.split('\n')
strings = strings[:-1]

nice_count = 0

for name in strings:
    if is_nice(name):
        nice_count += 1

print(nice_count)

names_and_niceness = {
    "qjhvhtzxzqqjkmpb": True,
    "xxyxx": True,
    "uurcxstgmygtbstg": False,
    "ieodomkazucvgmuy": False
}

def pair_without_overlapping(name):
    seen = set()
    n = len(name)
    for i in range(2, n+1):
        pair = name[i-2:i]
        prev_pair = None
        if i >= 3:
            prev_pair = name[i-3:i-1]
        if pair in seen and prev_pair and prev_pair != pair:
            return True
        seen.add(pair)
    return False

def repeat_with_one_inbetween(name):
    n = len(name)
    for i in range(2, n):
        if name[i] == name[i - 2]:
            return True
    return False

def is_new_nice(name):
    return pair_without_overlapping(name) and repeat_with_one_inbetween(name)

for name, niceness in names_and_niceness.items():
    print(is_new_nice(name) == niceness)

nice_count = 0

for name in strings:
    if is_new_nice(name):
        nice_count += 1

print(nice_count)


# Задача 16: Требуется вычислить, сколько раз встречается некоторое число X в массиве A[1..N].
# Пользователь в первой строке вводит натуральное число N – количество элементов в массиве.
# В последующих  строках записаны N целых чисел Ai. Последняя строка содержит число X

# *Пример:*

# 5
#     1 2 3 4 5
#     3
#     -> 1

import subprocess
import os
import random

subprocess.call('clear' if os.name =='posix' else 'cls', shell=True)    # Очистка консоли

n = int(input("Введи число N: "))

if n < 1:
    print()
    print("Необходимо ввести число больше нуля!")
    print
else:
    Ai = [] # Создание пустого списка

    money = range(n)
    sum = 0
    otvet = 0

    for i in money:
        Ai.append(int(random.random() * 10))

print(Ai)

x = int(input("Введи искомое число X: "))

if n < 1:
    print()
    print("Необходимо ввести число больше нуля!")
    print
else:
    for i in money:
        if Ai[i] == x:
            sum += 1

print("Ответ: " + str(sum))

Урок_3/Задача 16.py

Задача 16.py


from typing import Any, Dict, List, Type, TypeVar, Union

import attr

from ..models.fire_multiple_action_form_contentlet_item import FireMultipleActionFormContentletItem
from ..types import UNSET, Unset

T = TypeVar("T", bound="FireMultipleActionForm")

@attr.s(auto_attribs=True)
class FireMultipleActionForm:
    """
    Attributes:
        comments (Union[Unset, str]):
        assign (Union[Unset, str]):
        publish_date (Union[Unset, str]):
        publish_time (Union[Unset, str]):
        expire_date (Union[Unset, str]):
        expire_time (Union[Unset, str]):
        never_expire (Union[Unset, str]):
        where_to_send (Union[Unset, str]):
        filter_key (Union[Unset, str]):
        timezone_id (Union[Unset, str]):
        iwant_to (Union[Unset, str]):
        contentlet (Union[Unset, List[FireMultipleActionFormContentletItem]]):
    """

    comments: Union[Unset, str] = UNSET
    assign: Union[Unset, str] = UNSET
    publish_date: Union[Unset, str] = UNSET
    publish_time: Union[Unset, str] = UNSET
    expire_date: Union[Unset, str] = UNSET
    expire_time: Union[Unset, str] = UNSET
    never_expire: Union[Unset, str] = UNSET
    where_to_send: Union[Unset, str] = UNSET
    filter_key: Union[Unset, str] = UNSET
    timezone_id: Union[Unset, str] = UNSET
    iwant_to: Union[Unset, str] = UNSET
    contentlet: Union[Unset, List[FireMultipleActionFormContentletItem]] = UNSET
    additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)

    def to_dict(self) -> Dict[str, Any]:
        comments = self.comments
        assign = self.assign
        publish_date = self.publish_date
        publish_time = self.publish_time
        expire_date = self.expire_date
        expire_time = self.expire_time
        never_expire = self.never_expire
        where_to_send = self.where_to_send
        filter_key = self.filter_key
        timezone_id = self.timezone_id
        iwant_to = self.iwant_to
        contentlet: Union[Unset, List[Dict[str, Any]]] = UNSET
        if not isinstance(self.contentlet, Unset):
            contentlet = []
            for contentlet_item_data in self.contentlet:
                contentlet_item = contentlet_item_data.to_dict()

                contentlet.append(contentlet_item)

        field_dict: Dict[str, Any] = {}
        field_dict.update(self.additional_properties)
        field_dict.update({})
        if comments is not UNSET:
            field_dict["comments"] = comments
        if assign is not UNSET:
            field_dict["assign"] = assign
        if publish_date is not UNSET:
            field_dict["publishDate"] = publish_date
        if publish_time is not UNSET:
            field_dict["publishTime"] = publish_time
        if expire_date is not UNSET:
            field_dict["expireDate"] = expire_date
        if expire_time is not UNSET:
            field_dict["expireTime"] = expire_time
        if never_expire is not UNSET:
            field_dict["neverExpire"] = never_expire
        if where_to_send is not UNSET:
            field_dict["whereToSend"] = where_to_send
        if filter_key is not UNSET:
            field_dict["filterKey"] = filter_key
        if timezone_id is not UNSET:
            field_dict["timezoneId"] = timezone_id
        if iwant_to is not UNSET:
            field_dict["iwantTo"] = iwant_to
        if contentlet is not UNSET:
            field_dict["contentlet"] = contentlet

        return field_dict

    @classmethod
    def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:
        d = src_dict.copy()
        comments = d.pop("comments", UNSET)

        assign = d.pop("assign", UNSET)

        publish_date = d.pop("publishDate", UNSET)

        publish_time = d.pop("publishTime", UNSET)

        expire_date = d.pop("expireDate", UNSET)

        expire_time = d.pop("expireTime", UNSET)

        never_expire = d.pop("neverExpire", UNSET)

        where_to_send = d.pop("whereToSend", UNSET)

        filter_key = d.pop("filterKey", UNSET)

        timezone_id = d.pop("timezoneId", UNSET)

        iwant_to = d.pop("iwantTo", UNSET)

        contentlet = []
        _contentlet = d.pop("contentlet", UNSET)
        for contentlet_item_data in _contentlet or []:
            contentlet_item = FireMultipleActionFormContentletItem.from_dict(contentlet_item_data)

            contentlet.append(contentlet_item)

        fire_multiple_action_form = cls(
            comments=comments,
            assign=assign,
            publish_date=publish_date,
            publish_time=publish_time,
            expire_date=expire_date,
            expire_time=expire_time,
            never_expire=never_expire,
            where_to_send=where_to_send,
            filter_key=filter_key,
            timezone_id=timezone_id,
            iwant_to=iwant_to,
            contentlet=contentlet,
        )

        fire_multiple_action_form.additional_properties = d
        return fire_multiple_action_form

    @property
    def additional_keys(self) -> List[str]:
        return list(self.additional_properties.keys())

    def __getitem__(self, key: str) -> Any:
        return self.additional_properties[key]

    def __setitem__(self, key: str, value: Any) -> None:
        self.additional_properties[key] = value

    def __delitem__(self, key: str) -> None:
        del self.additional_properties[key]

    def __contains__(self, key: str) -> bool:
        return key in self.additional_properties


#!/usr/bin/env python3
# -*- coding utf-8 -*-

import openai
import yaml

'''
api调用演示

# for windows
set PATH=D:/NeoLang/Python/Python310_x64;%PATH%
python -m venv venv
venv\\Scripts\\activate
pip install -r requirements.txt
python test01.py

# for linux
python -m venv venv
. venv/bin/activate
pip install -r requirements.txt
python test01.py
'''

def get_api_key():
    with open("config.yaml", "r", encoding="utf-8") as yaml_file:
        yaml_data = yaml.safe_load(yaml_file)
        openai.api_key = yaml_data["openai"]["api_key"]

def generate_prompt(gender):
    return """Suggest three names for a Chinese boy who love cars.

Baby: Boy
Names: Tom, Jerry, Henrry
Baby: Girl
Names: Alice, Alma, Ann
Baby: {}
Names:""".format(gender)

if __name__ == '__main__':
    get_api_key()
    gender = "Boy"
    response = openai.Completion.create(
            model="text-davinci-003",
            prompt=generate_prompt(gender),
            temperature=0.6,
        )

    print(response)

'''
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "text": " Auton, Moton, Driven"
    }
  ],
  "created": 1679718420,
  "id": "cmpl-6xpmW7Kmmq7AepquRHEvQw62N3mkC",
  "model": "text-davinci-003",
  "object": "text_completion",
  "usage": {
    "completion_tokens": 8,
    "prompt_tokens": 45,
    "total_tokens": 53
  }
}
'''


import torch

class TopKPredictionFilter:

    def __init__(self, k: int, prediction_mode='prob'):
        """
        Args:
            k: k predictions with highest confidence
            prediction_mode: can be 'indices' or 'prob', indicating whether the predictions are a set of class indices or predicted probabilities.
        """
        assert k >= 0
        assert prediction_mode == 'prob' or prediction_mode == 'indices', f"Prediction mode {prediction_mode} is not supported!"

        self.prediction_mode = prediction_mode
        self.k = k

    def filter(self, predictions, return_mode='vec'):
        """ Return k class predictions with highest confidence.
        Args:
            predictions:
                when 'prediction_mode' is 'prob', refers to predicted probabilities of N samples belonging to C classes. Shape (N, C)
                when 'prediction_mode' is 'indices', refers to indices of M highest confidence of C classes in descending order, for each of the N samples. Shape (N, M)
            return_mode: can be 'indices' or 'vec', indicating whether return value is a set of class indices or 0-1 vector

        Returns:
            k labels with highest probabilities, for each sample
        """

        k = min(predictions.shape[1], self.k)

        if self.prediction_mode == 'prob':
            if k == 0:
                top_k_pred_indices = torch.tensor([[] for i in range(predictions.shape[1])], dtype=int)
            elif k == 1:
                top_k_pred_indices = torch.argmax(predictions, axis=1)
                top_k_pred_indices = top_k_pred_indices.reshape((-1, 1))
            else:
                top_k_pred_indices = torch.topk(predictions, k=k, dim=1).indices
        else:
            top_k_pred_indices = predictions[:, :k]

        if return_mode == 'indices':
            return list(top_k_pred_indices)
        else:
            preds = torch.zeros_like(predictions, dtype=int)
            row_index = torch.arange(predictions.shape[0]).repeat_interleave(k)
            col_index = top_k_pred_indices.reshape((1, -1))
            preds[row_index, col_index] = 1

            return preds


import sys
import math
from scipy.interpolate import spline
from scipy.ndimage.filters import gaussian_filter1d
import matplotlib
import matplotlib.pyplot as plt
import datetime
import matplotlib.ticker as mticker
import copy
import numpy as np
import matplotlib.dates as mdates

def safeLog(a):
  if (a == 0):
    return -1E5
  else:
    return math.log(a)

def smoothPlot(ax, x, y, major, should_label, logX, logY):
  ysmoothed = gaussian_filter1d(y, sigma=1.5)
  if (logX):
    ax.set_xscale("log")
  if (logY):
    ax.set_yscale("log")
  if (should_label):
    ax.plot(x, ysmoothed, label=major)
  else:
    ax.plot(x, ysmoothed, color=[0.9, 0.9, 0.9])

def getSlopeData(hashData, applyLog, dayDist):
  logData = {}
  for key in hashData:
    logData[key] = []
    for idx in range(len(hashData[key])):
      curr = hashData[key][idx]
      if (applyLog):
        logData[key].append(safeLog(curr))
      else:
        logData[key].append(curr)

  slopeData = {}
  for key in logData:
    slopeData[key] = []
    for idx in range(0, len(logData[key])):
      slope = 0
      for idx2 in range(0, dayDist+1):
        if ((idx-idx2 >= 0) and (logData[key][idx-idx2] > -1E5)):
          slope = logData[key][idx]-logData[key][idx-idx2]
      slopeData[key].append(slope)

  return (slopeData)

def majorSort(e):
  return e[1][-1]

def getLabeledShown(data):
  sortedMajors = [(k, v) for k, v in data.items()]
  sortedMajors.sort(reverse=True, key=majorSort)
  sortedMajors = [k for (k, v) in sortedMajors]

  mandatory = ["Massachusetts", "Germany", "US", "Middlesex", "Suffolk"]
  totalLabeled = 7
  totalShown = 2*totalLabeled
  labeled_majors = []
  shown_majors = []
  for man in mandatory:
    if (man in sortedMajors):
      labeled_majors.append(man)
      shown_majors.append(man)
  for idx in range(len(sortedMajors)):
    if ((sortedMajors[idx] not in labeled_majors) and (len(labeled_majors) < totalLabeled)):
      labeled_majors.append(sortedMajors[idx])
    if ((sortedMajors[idx] not in shown_majors) and (len(shown_majors) < totalShown)):
      shown_majors.append(sortedMajors[idx])
  labeled_majors.reverse()
  shown_majors.reverse()
  return (labeled_majors, shown_majors)

def showSingleData(CSC, deathsData, data_date, data_secs):
  deathsDailyData = getSlopeData(deathsData, False, 1)
  (labeledMajors, shownMajors) = getLabeledShown(deathsDailyData)
  fig, axs = plt.subplots(1, 1)

  max_length = 0
  for major in shownMajors:
    max_length = max(max_length, len(deathsData[major]))

  base = datetime.datetime.today()
  date_list = [base - datetime.timedelta(days=max_length-x) for x in range(max_length)]

  max_val = 0
  for major in shownMajors:
    max_val = max(max_val, np.max(deathsDailyData[major]))
  for major in shownMajors:
    smoothPlot(axs, date_list, deathsDailyData[major], major, major in labeledMajors, False, False)
  locator = mdates.AutoDateLocator()
  formatter = mdates.AutoDateFormatter(locator)
  axs.xaxis.set_major_locator(locator)
  axs.xaxis.set_major_formatter(formatter)
  axs.set_ylim(0, max_val)
  axs.set_title("Daily deaths")

  plt.suptitle(CSC+" COVID-19 stats, Date:"+data_date)

  fig.tight_layout(pad=1.0)
  fig.autofmt_xdate()
  plt.grid()
  plt.subplots_adjust(top=0.85)
  plt.savefig("/var/www/html/"+CSC+"_"+data_secs+".png")
  plt.close()
  print("Image saved.")

def showData(CSC, confirmedData, deathsData, data_date, data_secs):
  confirmedDailyData = getSlopeData(confirmedData, False, 7)
  (labeledConfirmedMajors, shownConfirmedMajors) = getLabeledShown(confirmedDailyData)
  fig, axs = plt.subplots(1, 2)

  max_length = 0
  for major in shownConfirmedMajors:
    max_length = max(max_length, max(len(confirmedData[major]), len(deathsData[major])))

  for major in shownConfirmedMajors:
    smoothPlot(axs[0], range(max_length-len(confirmedDailyData[major]), max_length), confirmedDailyData[major], major, major in labeledConfirmedMajors, False, False)
  axs[0].set_title("Confirmed")
  axs[0].legend(loc='best')

  deathsDailyData = getSlopeData(deathsData, False, 7)
  (labeledDeathsMajors, shownDeathsMajors) = getLabeledShown(deathsDailyData)
  for major in shownDeathsMajors:
    smoothPlot(axs[1], range(max_length-len(deathsDailyData[major]), max_length), deathsDailyData[major], major, major in labeledDeathsMajors, False, False)
  axs[1].set_title("Deaths")
  axs[1].legend(loc='best')

  fig.tight_layout(pad=1.0)
  plt.subplots_adjust(top=0.85)
  plt.suptitle(CSC+" COVID-19 stats, Date:"+data_date)
  plt.savefig("/var/www/html/"+CSC+"_"+data_secs+".png")
  plt.close()
  print("Image saved.")


# 错误处理  如果发生了错误，可以事先约定返回一个错误代码，这样就可以知道出错原因和出错位置

try:
    print('try...')
    r = 10 / 0
    print('result: ',r)
#可以用不同的except来获取不同类型的错误
except ZeroDivisionError as e:
    print('except:',e)
except ValueError as e:
    print('ValueError:',e)
finally:
    print('finally...')
print('end')

# try except 捕获异常时，会遵循继承关系，如果错误类型是子类的类型，也可以被捕获
# 还可以跨越多层调用

# 记录错误
import logging
def foo(s):
    return 10/int(s)

def bar(s):
    return foo(s) * 2

#多层调用
def main():
    try:
        bar('0')
    except Exception as e:
        print("except:",e)
        logging.exception(e)#打印错误信息后退出
    finally:
        print('finally...')

main()
print('END')

# 抛出错误 raise
# 定义一个错误类型
class FooError(ValueError):
    pass

def foo(s):
    n =int(s)
    if n == 0:
        raise FooError('invalid value: ', s)
    return 10 / n

#foo('0')

# 练习
#  运行下面的代码，根据异常信息，定位出错误源头，并修复
from functools import reduce

def str2num(s):
#    return int(s)
    try:
      return int(s)
    except ValueError as e:
        logging.exception(e)

def calc(exp):
    ss = exp.split('+')
    ns = map(str2num,ss)
    try:
        return reduce(lambda acc,x:acc + x , ns)
    except TypeError as e:
        print('TypeError',e)
def main2():
    r = calc('100 + 200 + 345')
    print('100 + 200 + 345 = ',r)
    # 7.6 出错
    r = calc('99 + 88 + 7.6')
    print('99 + 88 + 7.6 = ',r)

main2()
print('over')


# -*- coding: utf-8 -*-
"""
Created on Wed Apr  6 00:54:55 2022

@author: Dave
"""

'''MEDIA & SOCIETY SCRIPT PART2

Focusing on the effect of recreational drug advertisements over an average age interval of 17-30
Will use pandas for easier analysis and visualization; matplotlib's pyplot for direct visuals; and
potentially numpy.

Use of R & ggplot2 could be useful in visualization and certain statistical methods, however the data
in this instance is not directly numerical & quantitative but more qualitative and is a total measure,
not a regression technique capable with strictly numerical data

Nevertheless, a few inferences will be made as a result of data analysis; the plan is for this list
to be expanded and more infeneces to be created, however given limited data & more qualitative data,
machine learning or forms of NLP might be needed in order to expand research.

- Average age
- Male to Female Ratio, the amount of Yes (Y) & No (N) responses per gender #Pandas .corr could come in handy
- If under 21 what is the ratio of Y or N to q1
- Ratio on q2, check its effect with optional q4
- Average % of Y & Y, N & N, Y & N, Y & Y & Y. Divide the amounts of these values by 3+, 5 'Response'
Intervals. This is very similar to large datasets where the total % is within the much higher 'Response'
counts
- Based on the data is it true that people under 21 are more likely to go out and purchase/consume
recreational drugs?
'''

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import csv

def piePlot(names,vals):
    names = np.array(names)
    lowest = vals.index(min(vals))
    explode = [0,0,0,0]
    explode[lowest] += 0.1
    explode = tuple(explode)

    fig, axis = plt.subplots()
    axis.pie(vals, explode=explode, labels=names, autopct="%1.1f%%",
             shadow=True, startangle=90)
    axis.axis('equal')

    plt.show()

def labels(x,y, avg):
    for i in range(len(x)):
        plt.text(i,y[i],avg[i], ha="center")

def plot(uni):
    #Plot a histogram measuring the total amount of q5's responses with is respective key
    #on top of each bar will be the the average age of that response

    x = list(uni.keys())
    y = [len(items) for items in uni.values()]
    avg = [round(sum(items) / len(items), 3) if len(items) > 0 else 0 for items in uni.values()]

    plt.figure(figsize = (10,5))
    plt.bar(x,y)

    labels(x,y,avg)

    plt.xlabel("Type of Question Responses")
    plt.ylabel("Amount")

    plt.title("Average age of Responses")

    plt.show()

def genderPlot(freq):
    keys = list(freq.keys())
    vals = list(freq.values())

    plt.pie(vals, labels = keys, explode=[0,0.2,0], autopct="%1.1f%%")
    plt.title("Gender Frequency")
    plt.legend()
    plt.show()

def VisualEase(data,idx):
    return data.loc[idx]

if __name__ == "__main__":
    data = pd.read_csv("ProjectData.csv")

    #1
    for headers in data.columns:
        data.rename(columns = {"age ": "age"}, inplace=True)
        if ( headers.startswith("q") ):
            data.pop(headers)

    averageAge = data["age"].mean().round(2)
    medianAge = data["age"].median()
    modeAge = data["age"].mode()

    #2
    M = 0
    F = 0
    nullAmount = 0
    genderFreq = {"M":M, "F":F, "N/A":nullAmount}

    for items in data.columns:
        if items == "gender":
            for values in data[items]:
                if values == "M":
                    genderFreq["M"] += 1
                elif values == "F":
                    genderFreq["F"] += 1
                else:
                    genderFreq["N/A"] += 1

    #genderPlot(genderFreq)

    #3
    '''
    Divide the dictionary into 4 sections:
    (1) 21+ and Yes
    (2) <21 and Yes
    (3) 21+ and No
    (4) <21 and No
    '''
    ageToQ1 = {"1":0, "2":0, "3":0, "4":0}
    ageRows = data["age"]
    a1 = data["a1"]
    a2 = data["a2"]
    a3 = data["a3"]
    a4 = data["a4"]

    ageL = np.sort(ageRows, order=None)

    for i in range(len(ageRows)):
        if ageRows[i] >= 21:
            if a1[i] == "Y":
                ageToQ1["1"] += 1
            elif a1[i] == "N":
                ageToQ1["3"] += 1
        else:
            if a1[i] == "Y":
                ageToQ1["2"] += 1
            elif a1[i] == "N":
                ageToQ1["4"] += 1

    q3Names = ["21+ & Y", "<21 & Y", "21+ & N", "<21 & N"]
    q3Vals = list(ageToQ1.values())
    #piePlot(q3Names, q3Vals)

    #4
    totalIncomeClass = len(data)
    checkZero = 0
    total = a4.sum()

    for i in range(len(a4)):
        if a4[i] == 0:
            checkZero += 1

    #this is seperate from the main theme of research as we are looking to assess the
    #age interval specified and whether or not the questions show a pattern of commonality,
    #instead of by income class (also ask yourself whether the ages in comparison to their income class
    #show a pattern)

    #income & yes or no response (idx 0 is YES, while idx 1 is NO)
    upperVals = [0,0]  #upper middle and wealthy (3 & 4)
    middleVals = [0,0] #strictly middle (2)
    lowerVals = [0,0] #lower (1)

    for i in range(len(a2)):
        if a4[i] >= 3:  #upper middle class and wealthy
            if a2[i] == "Y":
                upperVals[0] += 1
            elif a2[i] == "N":
                upperVals[1] += 1
        elif a4[i] == 2: #middle class
            if a2[i] == "Y":
                middleVals[0] += 1
            elif a2[i] == "N":
                middleVals[1] += 1
        elif a4[i] == 1:
            if a2[i] == "Y":
                lowerVals[0] += 1
            elif a2[i] == "N":
                lowerVals[0] == 1

    #5
    length = len(data)
    '''#uncomment for visual ease of dataframe
    for i in range(length):
        visualDF = VisualEase(data, i)
        print(visualDF)
    '''
    universal = { "YY":[], "YN":[], "NN":[], "NY":[], "YYY":[], "NNN":[], "YNY":[], "NYN":[] }

    for i in range(length):
        if a1[i] == "Y":
            if a2[i] == "Y":
                universal["YY"].append(ageRows[i])
                if a3[i] == "Y":
                    universal["YYY"].append(ageRows[i])

            elif a2[i] == "N":
                universal["YN"].append(ageRows[i])
                if a3[i] == "Y":
                    universal["YNY"].append(ageRows[i])
        elif a1[i] == "N":
            if a2[i] == "N":
                universal["NN"].append(ageRows[i])
                if a3[i] == "N":
                    universal["NNN"].append(ageRows[i])

            elif a2[i] == "Y":
                universal["NY"].append(ageRows[i])
                if a3[i] == "N":
                    universal["NYN"].append(ageRows[i])

    #plot(universal)


#!/usr/bin/env python3

import connexion

from swagger_server import encoder
from swagger_server.controllers import resource_controller

def main():
    app = connexion.App(__name__, specification_dir='./swagger/')
    app.app.json_encoder = encoder.JSONEncoder
    app.add_api('swagger.yaml', arguments={'title': 'Data Lake Catalog Service API'})
    resource_controller.init_catalog_access()
    app.run(port=8086)

if __name__ == '__main__':
    main()


def soleil_leve (heure_lever, heure_coucher, heure_actuelle):
    """ vérifie si 2 nombres sont égaux
    """

    if heure_lever < heure_coucher:
        resultat = (heure_lever <= heure_actuelle and heure_actuelle < heure_coucher)
    elif heure_coucher < heure_lever:
        resultat = (heure_actuelle < heure_coucher or heure_actuelle >= heure_lever)
    else:
        if heure_lever == 12:
            resultat = (heure_actuelle > 23)
        elif heure_lever == 0:
            resultat = (heure_actuelle < 24)

    return resultat

n1 = int(input())
n2 = int(input())
n3 = int(input())
n4 = int(input())

for h in range (0, 24):
    print(h, end="")
    if soleil_leve(n1, n2, h) or soleil_leve(n3, n4, h):
        print(end="\n")
    else:
        print(" *", end="\n")


from pygame import *
from cactus import *
from cloud import *
from config import *
from dino import *
from floor import *
from mensages import *
from dino_fly import *

class Game:
    def __init__(self):
        pass
    pygame.init()
    screen = pygame.display.set_mode((width, height))
    pygame.display.set_caption("Dino run")

    Dino = Dino(sprite_dino)
    Messages = Messages()

    game_over = Messages.show_text('GAME OVER', 35, black)
    close = Messages.show_text('Press "x" to close the Game', 20, black)

    for ct in range(2):
        cactus = Cactus()
        all_sprites.add(cactus)
        obstacles_group.add(cactus)

    for c in range(4):
        cloud = Cloud(sprite_cloud)
        all_sprites.add(cloud)

    for f in range(640 * 2 // 64):
        floor = Floor(f, sprite_floor)
        all_sprites.add(floor)

    dino_fly = Ptera(sprite_dino_fly)
    all_sprites.add(dino_fly)
    obstacles_group.add(dino_fly)

    collision = False
    while True:
        clock.tick(30)
        screen.fill(white)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
            if event.type == KEYDOWN:
                if event.key == K_SPACE:
                    if dino.rect.y == 508 and not collision:
                        Sounds.jump_sound.play()
                        dino.leap()
                if event.key == pygame.K_x and collision:
                    exit()

        if key.get_pressed()[K_DOWN]:
            dino.duck()
        else:
            if dino.down:
                dino.undunking()

        collisions = pygame.sprite.spritecollide(dino, obstacles_group, False, pygame.sprite.collide_mask)
        all_sprites.draw(screen)
        if collisions and not collision:
            Sounds.death_sound.play()
            collision = True

        if collision:
            dino.dead()
            screen.blit(game_over, (width // 2 - 150, height // 2 - 150))
            screen.blit(close, (width // 2 - 260, height // 2 - 90))
            score_dino2 = Messages.show_text(score, 35, black)
            screen.blit(score_dino2, (520, 30))
        else:
            score += 1
            score_dino = Messages.show_text(score, 35, black)
            screen.blit(score_dino, (520, 30))
            all_sprites.update()
        if score % 100 == 0:
            Sounds.score_sound.play()
        pygame.display.flip()


import os
import azure.cognitiveservices.speech as speechsdk

class Tts:

    def __init__(self, voice_name, text):
        # This example requires environment variables named "SPEECH_KEY" and "SPEECH_REGION"
        speech_config = speechsdk.SpeechConfig(subscription=os.getenv('AZURE_SPEECH_KEY'), region=os.getenv('AZURE_REGION_KEY'))
        audio_config = speechsdk.audio.AudioOutputConfig(use_default_speaker=True)

        # The language of the voice that speaks.
        speech_config.speech_synthesis_voice_name=voice_name

        self.speech_synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config)
        self.text = text

    def speak_text(self):
        speech_synthesis_result = self.speech_synthesizer.speak_text_async(self.text).get()
        if speech_synthesis_result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
            print("Speech synthesized for text [{}]".format(self.text))
        elif speech_synthesis_result.reason == speechsdk.ResultReason.Canceled:
            cancellation_details = speech_synthesis_result.cancellation_details
            print("Speech synthesis canceled: {}".format(cancellation_details.reason))
            if cancellation_details.reason == speechsdk.CancellationReason.Error:
                if cancellation_details.error_details:
                    print("Error details: {}".format(cancellation_details.error_details))
                    print("Did you set the speech resource key and region values?")
        return speech_synthesis_result


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import tempfile

from scilpy.io.fetcher import fetch_data, get_home, get_testing_files_dict

# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['processing.zip'])
tmp_dir = tempfile.TemporaryDirectory()

def test_help_option(script_runner):
    ret = script_runner.run('scil_convert_tensors.py', '--help')
    assert ret.success

def test_execution_processing(script_runner):
    os.chdir(os.path.expanduser(tmp_dir.name))

    # No tensor in the current test data! I'm running the compute_dti_metrics
    # to create one.
    in_dwi = os.path.join(get_home(), 'processing',
                          'dwi_crop_1000.nii.gz')
    in_bval = os.path.join(get_home(), 'processing',
                           '1000.bval')
    in_bvec = os.path.join(get_home(), 'processing',
                           '1000.bvec')
    script_runner.run('scil_compute_dti_metrics.py', in_dwi,
                      in_bval, in_bvec, '--not_all',
                      '--tensor', 'tensors.nii.gz', '--tensor_format', 'fsl')

    ret = script_runner.run('scil_convert_tensors.py', 'tensors.nii.gz',
                            'converted_tensors.nii.gz', 'fsl', 'mrtrix')

    assert ret.success


from django.conf.urls import url
from django.conf import settings
from django.views.static import serve
from . import views

urlpatterns = [

    url(r'^$', views.index, name = 'index'),
    url(r'^user/(\w+)/$', views.profile, name='profile'),
    url(r'post_url/', views.post_treasure, name='post_treasure'),
    url(r'^([0-9]+)/$', views.detail, name = 'detail'),
    url(r'^login/$', views.login_view, name='Login'),
    url(r'^logout/$', views.logout_view, name='Logout'),
    url(r'^like_treasure/$', views.like_treasure, name='like_treasure' ),
]

# add to the bottom of your file
if settings.DEBUG:
    urlpatterns += [
        url(r'^media/(?P<path>.*)$', serve, {
            'document_root': settings.MEDIA_ROOT,
        }),
    ]


import imageio

def create_gif(image_list, gif_name, duration=1):
    """
    :param image_list: 原始图片，png
    :param gif_name: gif的文件名
    :param duration: 间隔时间
    path：路径
    :return:
    """

    frames = []
    for image_name in image_list:
        frames.append(imageio.imread(image_name))
    # 保存为GIF
    imageio.mimsave(gif_name, frames, 'GIF', duration=duration)

    return

def main():
    image_list = ['1.png', '2.png', '3.png', '4.png']
    gif_name = 'first.gif'
    duration = 1.5
    create_gif(image_list, gif_name)

# 当前程序被当作主程序运行时， __ name__被自动赋值为固定的字符串__main__;当它被当作模块被其他文件调用时，自动被赋值为模块所在的文件名
if __name__ == '__main__':
    main()


import enum
import typing
import numpy as np
from typing import Any, TYPE_CHECKING, Union, Optional

from powerowl.exceptions.graph_encoding_error import GraphEncodingError

if TYPE_CHECKING:
    from powerowl.graph import MultiLayerGraph

class GraphEncoder:
    """
    This class allows to derive a JSON-serializable dict-representation of the given MultiLayerGraph
    Default data types are preserved, while other objects are transformed via their "to_dict" method.
    To preserve pointers and handle circular references, complex objects are stored in a reference
    table and then referenced in the actual graph structure.

    Supported data types:
    None, bool, int, float, ModelNode, ModelEdge, GridElement
    and any object that provides the to_dict and from_dict methods.
    """
    def __init__(self, mlg: 'MultiLayerGraph'):
        self.mlg = mlg
        self._references = {}

    def encode(self, include_layer_objects: bool = False) -> dict:
        self._references = {}
        encoded_nodes = self._iterencode(self.mlg.get_nodes())
        encoded_edges = self._iterencode(self.mlg.get_edges())
        encoded_layers = self._iterencode(self.mlg.get_layers(True))
        encoded_graph = {
            "$references": self._references,
            "nodes": encoded_nodes,
            "edges": encoded_edges,
            "layers": encoded_layers
        }
        if include_layer_objects:
            encoded_graph["layer_objects"] = {
                layer.name: self._iterencode(self.mlg.get_layer_object(layer=layer.name))
                for layer in self.mlg.get_layers(True)
            }
        return encoded_graph

    def _iterencode(self, o: Any, context: Optional[str] = None):
        if context is None:
            context = ""
        if o is None:
            return None
        elif isinstance(o, enum.Enum):
            # Required for enums that also inherit str or int
            return self._iterencode_object(o, context)
        elif isinstance(o, (str, float, int, bool)):
            return o
        elif isinstance(o, np.integer):
            return int(o)
        elif isinstance(o, np.floating):
            return float(o)
        elif isinstance(o, np.ndarray):
            return self._iterencode_list_alike(o.tolist(), context)
        elif isinstance(o, dict):
            return self._iterencode_dict(o, context)
        elif isinstance(o, (list, tuple, set)):
            return self._iterencode_list_alike(o, context)
        else:
            return self._iterencode_object(o, context)

    def _iterencode_list_alike(self, collection: Union[list, tuple, set], context: str):
        """
        Recursively encodes a list-alike object (lists, tuples, sets)
        """
        cls = self._fqcn(collection)
        elements = [self._iterencode(e, f"{context}.{str(i)}") for i, e in enumerate(collection)]
        return {
            "$class": cls,
            "$elements": elements
        }

    def _iterencode_dict(self, d: dict, context: str):
        """
        Recursively encodes a dictionary
        """
        return {k: self._iterencode(v, f"{context}.{k}") for k, v in d.items()}

    def _iterencode_object(self, o: Any, context: str):
        """
        Encodes objects as references.
        If a reference does not yet exist, it is created.
        """
        identifier = str(id(o))
        if identifier not in self._references:
            # Create placeholder reference
            self._references[identifier] = None
            cls = self._fqcn(o)
            dict_representation = None
            if isinstance(o, type):
                dict_representation = {
                    "$class": cls
                }
            elif o.__class__.__module__ == "typing":
                dict_representation = {
                    "$class": repr(o).split("[")[0],
                    "$sub_types": [
                        self._iterencode(sub_type, context) for sub_type in typing.get_args(o)
                    ]
                }
            elif isinstance(o, enum.Enum):
                dict_representation = {
                    "$class": cls,
                    "$name": o.name
                }
            else:
                if callable(getattr(o, "to_dict", None)) and callable(getattr(o, "from_dict", None)):
                    dict_representation = {
                        "$class": cls,
                        "$restore_method": "from_dict",
                        "$restore_args": self._iterencode_dict(o.to_dict(), f"{context}.{o.__class__.__name__}")
                    }
            if dict_representation is None:
                raise GraphEncodingError(f"{context}\nCannot encode object of type {cls}.")
            self._references[identifier] = dict_representation
        return self._build_reference(identifier)

    @staticmethod
    def _build_reference(identifier) -> dict:
        return {"$ref": str(identifier)}

    @staticmethod
    def _fqcn(instance_or_class) -> str:
        """
        Returns the fully-qualified class name of a given object.
        """
        if isinstance(instance_or_class, type):
            cls = instance_or_class
        else:
            cls = instance_or_class.__class__
        # cls = instance_or_class.__class__
        module = cls.__module__
        if module == "builtins":
            return cls.__qualname__
        return f"{module}.{cls.__qualname__}"


import copy

def findWord(board, word, i, j):
    if word == "":
        return True

    for k in [0, 1, -1]:
        for t in [0, 1, -1]:
            if not (k == 0 and t == 0):
                if 0 <= i+k < len(board) and 0 <= j+t < len(board[0]) and board[i+k][j+t] == word[0:1]:
                    temp = copy.deepcopy(board)
                    temp[i+k][j+t] = "_"
                    if findWord(temp, word[1:], i+k, j+t):
                        return True

    return False

def wordBoggle(board, words):
    if not words:
        return words

    re = set()
    for word in words:
        for i in range(len(board)):
            for j in range(len(board[0])):
                if board[i][j] == word[0:1]:
                    temp = copy.deepcopy(board)
                    temp[i][j] = "_"
                    if findWord(temp, word[1:], i, j):
                        re.add(word)

    return sorted(re)


import queue

class Node:
    def __init__(self, key, left=None, right=None):
        self.key = key
        self.left = left
        self.right = right

    def __repr__(self):
        return "(" + str(self.key) + " " + str(self.left) + " " + str(self.right) + ")"

def printLevelByLevel(root):
    delimeter = Node('')

    q = queue.Queue(maxsize=10)
    q.put(root)
    q.put(delimeter)

    while True:
        root = q.get()
        if (root == delimeter and q.empty()):
            return
        if root == delimeter:
            print(" ")
            q.put(root)
        else:
            print(root.key, end=" ")
            if root.left:
                q.put(root.left)
            if root.right:
                q.put(root.right)

# root = Node(1)
# root.left = Node(2)
# root.right = Node(3)
# root.left.left = Node(4)
# root.left.right = Node(5)
# root.right.left = Node(6)
# root.right.right = Node(7)

n15 = Node(15)
n19 = Node(19, None, n15)

n18 = Node(18)
n25 = Node(25)
n20 = Node(20, n18, n25)

n18_ = Node(18, n19, n20)

n25 = Node(25)
n20_ = Node(20, None, n25)
n40 = Node(40)
n35 = Node(35, n20_, n40)

n55 = Node(55)
n70 = Node(70)
n60 = Node(60, n55, n70)

n50 = Node(50, n35, n60)

n25_ = Node(25, n18_, n50)
root = n25_

# 25
# 18 50
# 19 20 35 60
# 15 18 25 20 40 55 70
# 25

printLevelByLevel(root)


import matplotlib.pyplot as plt
import scipy.stats
import pandas as pd
import statsmodels.api as sm
from statsmodels.distributions.empirical_distribution import ECDF
import math

sumStatsTraitA = pd.read_table('sumstats_trait_A.txt')
sumStatsTraitB = pd.read_table('sumstats_trait_B.txt')

# Turn the files into a pandas data frame, so we have useable columns
dfA = pd.DataFrame(sumStatsTraitA, columns = ['SNP', 'CHR','BPOS', 'A1','A2','MAF','N', 'beta_hat', 'z', 'NCHROBS', 'info'])
dfB = pd.DataFrame(sumStatsTraitB, columns = ['SNP', 'CHR','BPOS', 'A1','A2','MAF','N', 'beta_hat', 'z', 'NCHROBS', 'info'])

#Calculating and printing p-values for sumstats_A and sumstats_B

p_value_dfa = scipy.stats.norm.sf(abs(dfA["z"]))*2

# scaling down pvalues to -log10 (- log base 10 (x) = log base 10 (1/x))
log_x_scale_dfa = [math.log(1/x_i) for x_i in p_value_dfa]

# get empirical data via library function
empirical_CDF_dfa = ECDF(log_x_scale_dfa)

# plot empirical CDF data x and y in a scatter
plt.scatter(empirical_CDF_dfa.x, empirical_CDF_dfa.y)
plt.legend(["sumStatsTraitA"])

# repeat for study 2 (dfB)
p_value_dfb = scipy.stats.norm.sf(abs(dfB["z"]))*2
log_x_scale_dfb = [ math.log(1/x_i) for x_i in p_value_dfb]
empirical_CDF_dfb = ECDF(log_x_scale_dfb)

# plot again, tried to put a legend for dfB but ran out of time
plt.scatter(empirical_CDF_dfb.x, empirical_CDF_dfb.y)
plt.legend(["sumStatsTraitB"])

# scale down the graph view
plt.xscale('log')
plt.yscale('log')

# rename labels
plt.xlabel('p-values under the null hypothesis')
plt.ylabel('empirical CDF of the p-values from the GWAS summary statistics')

# build 45 degree solid line
xpoints = ypoints = plt.xlim()
plt.plot(xpoints, ypoints, linestyle='-', color='k', lw=1)

# show graph
plt.show()


from enum import Enum
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import time

app = FastAPI()

class DogType(str, Enum):
    terrier = "terrier"
    bulldog = "bulldog"
    dalmatian = "dalmatian"

class Dog(BaseModel):
    name: str
    pk: int
    kind: DogType

class Timestamp(BaseModel):
    id: int
    timestamp: int

dogs_db = {
    0: Dog(name='Bob', pk=0, kind='terrier'),
    1: Dog(name='Marli', pk=1, kind="bulldog"),
    2: Dog(name='Snoopy', pk=2, kind='dalmatian'),
    3: Dog(name='Rex', pk=3, kind='dalmatian'),
    4: Dog(name='Pongo', pk=4, kind='dalmatian'),
    5: Dog(name='Tillman', pk=5, kind='bulldog'),
    6: Dog(name='Uga', pk=6, kind='bulldog')
}

post_db = [
    Timestamp(id=0, timestamp=12),
    Timestamp(id=1, timestamp=10)
]

kind_types = {'terrier', 'bulldog', 'dalmatian'}

@app.get('/')
def root():
    return "UwU"

@app.post('/post')
def post():
    post_db.append(Timestamp(id=post_db[-1].id + 1, timestamp=int(time.time())))
    return post_db[-1]

@app.get('/dog')
def get_dogs(kind=None):
    if kind in kind_types:
        return [v for k, v in dogs_db.items() if v.kind==kind]
    elif kind is None:
        return [v for k, v in dogs_db.items()]
    raise HTTPException(status_code=422, detail='Ошибка в данных')

@app.post('/dog')
def post_dog(name, pk, kind):
    if int(pk) not in dogs_db.keys() and kind in kind_types and name:
        dogs_db[int(pk)] =  Dog(name=name, pk=pk, kind=DogType(kind))
        return dogs_db[ int(pk)]
    raise HTTPException(status_code=422, detail='Ошибка в данных')

@app.get('/dog/{pk}')
def get_dog_pk(pk):
    if int(pk) in dogs_db.keys():
        return dogs_db[int(pk)]
    raise HTTPException(status_code=422, detail='Ошибка в данных')

@app.patch('/dog/{pk}')
def upd_dog(name, pk, kind):
    if int(pk) in dogs_db.keys() and kind in kind_types and name:
        dogs_db[int(pk)] = Dog(name=name, pk=int(pk), kind=DogType(kind))
        return dogs_db[int(pk)]
    raise HTTPException(status_code=422, detail='Ошибка в данных')


#'a aa abC aa ac abc bcd a AA'

wordsList = input().lower().split()
resDict = {}

for w in wordsList:
    if w in resDict:
        resDict[w] += 1
    else:
        resDict[w] = 1

for key in resDict:
    print(key, resDict[key])

count_words('a aa abC aa ac abc bcd a')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script to compute fODF lobe-specific metrics derived from a Bingham
distribution fitting, as described in [1]. Resulting metrics are fiber density
(FD), fiber spread (FS) and fiber fraction (FF) [2].

The Bingham coefficients volume comes from scil_fit_bingham_to_fodf.py.

A lobe's FD is the integral of the Bingham function on the sphere. It
represents the density of fibers going through a given voxel for a given
fODF lobe (fixel). A lobe's FS is the ratio of its FD on its maximum AFD. It
is at its minimum for a sharp lobe and at its maximum for a wide lobe. A lobe's
FF is the ratio of its FD on the total FD in the voxel.

Using 12 threads, the execution takes 10 minutes for FD estimation for a brain
with 1mm isotropic resolution. Other metrics take less than a second.
"""

import nibabel as nib
import time
import argparse
import logging
from scilpy.io.image import get_data_as_mask

from scilpy.io.utils import (add_overwrite_arg,
                             add_processes_arg,
                             add_verbose_arg,
                             assert_inputs_exist,
                             assert_outputs_exist, validate_nbr_processes)
from scilpy.reconst.bingham import (compute_fiber_density,
                                    compute_fiber_spread,
                                    compute_fiber_fraction)

EPILOG = """
[1] T. W. Riffert, J. Schreiber, A. Anwander, and T. R. Knösche, “Beyond
    fractional anisotropy: Extraction of bundle-specific structural metrics
    from crossing fiber models,” NeuroImage, vol. 100, pp. 176-191, Oct. 2014,
    doi: 10.1016/j.neuroimage.2014.06.015.

[2] J. Schreiber, T. Riffert, A. Anwander, and T. R. Knösche, “Plausibility
    Tracking: A method to evaluate anatomical connectivity and microstructural
    properties along fiber pathways,” NeuroImage, vol. 90, pp. 163-178, Apr.
    2014, doi: 10.1016/j.neuroimage.2014.01.002.
"""

def _build_arg_parser():
    p = argparse.ArgumentParser(description=__doc__,
                                formatter_class=argparse.RawTextHelpFormatter,
                                epilog=EPILOG)
    p.add_argument('in_bingham', help='Input Bingham image.')

    p.add_argument('--out_fd', default='',
                   help='Path to output fiber density. [fd.nii.gz]')
    p.add_argument('--out_fs', default='',
                   help='Path to output fiber spread. [fs.nii.gz]')
    p.add_argument('--out_ff', default='',
                   help='Path to fiber fraction file. [ff.nii.gz]')
    p.add_argument('--not_all', action='store_true',
                   help='Do not compute all metrics.')
    p.add_argument('--mask',
                   help='Optional mask image. Only voxels inside '
                        'the mask are computed.')

    p.add_argument('--nbr_integration_steps', type=int, default=50,
                   help='Number of integration steps along the theta axis for'
                        ' fiber density estimation. [%(default)s]')

    add_overwrite_arg(p)
    add_verbose_arg(p)
    add_processes_arg(p)
    return p

def main():
    parser = _build_arg_parser()
    args = parser.parse_args()
    if args.verbose:
        logging.getLogger().setLevel(logging.INFO)

    if not args.not_all:
        args.out_fd = args.out_fd or 'fd.nii.gz'
        args.out_fs = args.out_fs or 'fs.nii.gz'
        args.out_ff = args.out_ff or 'ff.nii.gz'

    arglist = [args.out_fd, args.out_fs, args.out_ff]
    if args.not_all and not any(arglist):
        parser.error('At least one output file must be specified.')

    outputs = [args.out_fd, args.out_fs, args.out_ff]
    assert_inputs_exist(parser, args.in_bingham, args.mask)
    assert_outputs_exist(parser, args, outputs)

    bingham_im = nib.load(args.in_bingham)
    bingham = bingham_im.get_fdata()
    mask = get_data_as_mask(nib.load(args.mask), dtype=bool)\
        if args.mask else None

    nbr_processes = validate_nbr_processes(parser, args)

    t0 = time.perf_counter()
    logging.info('Computing fiber density.')
    fd = compute_fiber_density(bingham, m=args.nbr_integration_steps,
                               mask=mask, nbr_processes=nbr_processes)
    t1 = time.perf_counter()
    logging.info('FD computed in (s): {0}'.format(t1 - t0))
    if args.out_fd:
        nib.save(nib.Nifti1Image(fd, bingham_im.affine), args.out_fd)

    if args.out_fs:
        t0 = time.perf_counter()
        logging.info('Computing fiber spread.')
        fs = compute_fiber_spread(bingham, fd)
        t1 = time.perf_counter()
        logging.info('FS computed in (s): {0}'.format(t1 - t0))
        nib.save(nib.Nifti1Image(fs, bingham_im.affine), args.out_fs)

    if args.out_ff:
        t0 = time.perf_counter()
        logging.info('Computing fiber fraction.')
        ff = compute_fiber_fraction(fd)
        t1 = time.perf_counter()
        logging.info('FS computed in (s): {0}'.format(t1 - t0))
        nib.save(nib.Nifti1Image(ff, bingham_im.affine), args.out_ff)

if __name__ == '__main__':
    main()


# import JSON
import json
# import Regular Expression
import re
# import Time (for sleep)
import time
# import Operator (for sorted)
import operator

# use official coinbase api
### https://pypi.org/project/coinbase/
### https://github.com/coinbase/coinbase-python/
from coinbase.wallet.client import Client

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#~~~~~~~~~~~~~~~~~ FUNCTIONS ~~~~~~~~~~~~~~~~~#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#

########################################################
# Init coinbase connection
def get_client(json_config:json):
    print("get_client")
    coinbase_api_key = ""
    coinbase_api_secret = ""
    if "coinbase_api_key" in json_config:
        coinbase_api_key = json_config['coinbase_api_key'];
    if "coinbase_api_secret" in json_config:
        coinbase_api_secret = json_config['coinbase_api_secret'];
    if (coinbase_api_key != "" and coinbase_api_secret != "") :
        return Client(coinbase_api_key, coinbase_api_secret)

########################################################
# Append all pagined accounts to only one array
g_all_accounts = {}
def get_all_accounts(client: object):
    print("get_all_accounts")

    # read from globals if exist
    global g_all_accounts
    if len(g_all_accounts) > 0:
        return g_all_accounts

    # do it if nothing else exist
    all_accounts = {}
    starting_after = None
    # infinite loop
    while True:
        accounts = client.get_accounts(limit=25, starting_after=starting_after)
        # if pagination exist then push all account in array and loop again
        if accounts.pagination.next_starting_after is not None:
            starting_after = accounts.pagination.next_starting_after
            for account in accounts.data:
                all_accounts[account.currency] = account
            time.sleep(1)
        # if pagination don't exist then push all account in array and exit loop
        else:
            for account in accounts.data:
                all_accounts[account.currency] = account
            break

    # init globals before return
    g_all_accounts = all_accounts
    return g_all_accounts

########################################################
# sort transaction by transaction created date reversed
def sort_owned_currencies_by_value(owned_currencies: object):
    return dict(sorted(owned_currencies.items(), key=operator.itemgetter(1), reverse=True))

########################################################
# get own currencies
g_owned_currencies = {}
def get_owned_currencies(accounts: json):
    print("get_owned_currencies")
    global g_owned_currencies

    # read from globals if exist
    if len(g_owned_currencies) > 0:
        return g_owned_currencies

    # do it if nothing else exist
    owned_currencies = {}
    for currency in accounts:
        balance = float(accounts[currency].native_balance.amount)
        if (balance > 0):
            owned_currencies[currency] = float(accounts[currency].native_balance.amount)

    # init globals before return
    g_owned_currencies = sort_owned_currencies_by_value(owned_currencies);
    return g_owned_currencies

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#~~~~~~~~~~~~~~~~ MAIN SCRIPT ~~~~~~~~~~~~~~~~#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#

# Loading configuration
with open('config.json') as datas_config:
   json_config = json.load(datas_config)

g_client = get_client(json_config)
g_all_accounts = get_all_accounts(g_client)
g_owned_currencies = get_owned_currencies(g_all_accounts)
print(g_owned_currencies)


n = input()
num = list(map(int, n))

if len(n) == 1:
    print(n)

else:
    #본인
    sum = len(n) + 9
    for i in range (len(n)):
        sum += (num[i]) * len(n) * 10

print(sum)


"""Normalized Artist table

Revision ID: 2f5f7e9a6647
Revises: 7be7e06ac500
Create Date: 2020-04-24 15:38:27.264110

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '2f5f7e9a6647'
down_revision = '7be7e06ac500'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('Artist', sa.Column('seeking_description', sa.String(length=500), nullable=True))
    op.add_column('Artist', sa.Column('seeking_venue', sa.Boolean(), server_default='f', nullable=False))
    op.add_column('Artist', sa.Column('website', sa.String(length=120), nullable=True))
    op.alter_column('Artist', 'genres',
               existing_type=sa.VARCHAR(length=120),
               type_=sa.String())
    op.alter_column('Artist', 'image_link',
               existing_type=sa.VARCHAR(length=500),
               nullable=False)
    op.alter_column('Artist', 'name',
               existing_type=sa.VARCHAR(length=120),
               type_=sa.String(120),
               nullable=False)
    op.create_unique_constraint(None, 'Artist', ['name'])
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint('Artist_name_key', 'Artist', type_='unique')
    op.alter_column('Artist', 'name',
               existing_type=sa.VARCHAR(length=120),
               nullable=True)
    op.alter_column('Artist', 'image_link',
               existing_type=sa.VARCHAR(length=500),
               nullable=True)
    op.drop_column('Artist', 'website')
    op.drop_column('Artist', 'seeking_venue')
    op.drop_column('Artist', 'seeking_description')
    # ### end Alembic commands ###


#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import String
from geometry_msgs.msg import Twist
from numpy import interp

left = 0.0
right = 0.0
w = 0.32  # distance between wheels in meters

def callback(msg):
    global vx, vy, vr, pub
    ############### to find the speed value ############################
    # vx = msg.linear.x * 100
    # vz = msg.angular.z * 100
    #
    # if(vx != 0):
    #     if(vx > 0):
    #         pub.publish("w,"+str(vx))
    #     elif(vx < 0):
    #         vx = abs(vx)
    #         pub.publish("s,"+str(vx))
    #
    # elif(vz != 0):
    #     if(vz > 0):
    #         pub.publish("a,"+str(vz))
    #     elif(vx < 0):
    #         vz = abs(vz)
    #         pub.publish("d,"+str(vz))
    #
    # else:
    #     pub.publish("c,0")

    ###################   values found ##########################
        # max pwm = 40   min pwm = 30
        # max linear vel = 0.26 min linear vel = 0.17

        # max pwm = 43   min pwm = 37
        # max angular vel = 0.92  min angular vel = 0.55

    ################   to run navigation ########################
    if vz > 0.92 and vz < 5 :
        vz = 0.92

    if vz < 0.55 and vz > 0.4 :
        vz = 0.55

    if vz < -0.4 and vz > -0.55:
        vz = -0.55
        print("wrapped")

    if vz < -0.92 and vz > -2:
        vz = -0.92

    if((vx != 0) or (vz != 0)):
        if(vx != 0):
            if (vx >= 0.17 and vx <= 0.26):
                vx = int(interp(vx,[0.17,0.26],[26,56]))
                pub.publish("w,"+str(vx))
            elif(vx <= -0.17 and vx >= -0.26):
                vx = int(interp(vx,[-0.26,-0.17],[56,26]))
                pub.publish("s,"+str(vx))

        if(vz != 0):
            if(vz >= 0.55 and vz <= 0.92):
                vz = int(interp(vz,[0.55,0.92],[25,30]))
                pub.publish("a,"+str(vz))
            elif(vz <= -0.55 and vz >= -0.92):
                vz = int(interp(vz,[-0.92,-0.55],[30,25]))
                pub.publish("d,"+str(vz))

    else:
        pub.publish("c,0")

    print(vz)
    ##################################################################33

if __name__ == '__main__':
    rospy.init_node('twist_motors', anonymous=True)
    pub = rospy.Publisher('base_cmd', String, queue_size=10)
    rospy.Subscriber("cmd_vel", Twist, callback)

    rate = rospy.Rate(10)
    while not rospy.is_shutdown():

        rate.sleep()


import pygame, sys
from pygame.locals import *
from playsound import playsound
from pathlib import Path
import math
import keyboard
import random
import controller
from pygame.math import Vector2

SCRIPT_DIR = Path(__file__).parent
GEAR = SCRIPT_DIR / 'running-gear-6403.mp3'

pygame.init()

FPS = 60
FramePerSec = pygame.time.Clock()

RED = (255, 0, 0)
WHITE = (255, 255, 255)

# Screen information
SCREEN_WIDTH = 1500
SCREEN_HEIGHT = 1000

DISPLAY = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
DISPLAY.fill(WHITE)
pygame.display.set_caption("Graffiti Gamebot")

Score = 0

def rotate(image, rect, angle, offset):
    """Rotate the image while keeping its center."""
    # Rotate the original image without modifying it.
    new_image = pygame.transform.rotate(image, angle)
    offset_rotated = offset.rotate(-angle)
    # Get a new rect with the center of the old rect.
    rect = new_image.get_rect(center=rect.center+offset_rotated)
    return new_image, rect

class Arm1(pygame.sprite.Sprite):
    def __init__(self, id):
        super().__init__()

        self.moving = False

        self.joy = pygame.joystick.Joystick(id)
        self.name = self.joy.get_name()
        self.joy.init()
        self.numaxes = self.joy.get_numaxes()
        self.numballs = self.joy.get_numballs()
        self.numbuttons = self.joy.get_numbuttons()
        self.numhats = self.joy.get_numhats()

        self.axis = []
        for i in range(self.numaxes):
            self.axis.append(self.joy.get_axis(i))

        self.ball = []
        for i in range(self.numballs):
            self.ball.append(self.joy.get_ball(i))

        self.button = []
        for i in range(self.numbuttons):
            self.button.append(self.joy.get_button(i))

        self.hat = []
        for i in range(self.numhats):
            self.hat.append(self.joy.get_hat(i))

        self.image = pygame.image.load("arm1.png")
        self.rotation = 0
        self.image = pygame.transform.rotate(self.image, self.rotation)
        self.rect = self.image.get_rect()
        self.rect.center = (240, 350)

    def update(self):
        pressed_keys = pygame.key.get_pressed()

        hat = self.joy.get_hat(0)
        rightbutton = self.joy.get_button(5)
        leftbutton = self.joy.get_button(4)

        self.rect.move_ip(0,5 * self.joy.get_axis(1))

        self.rotation += -self.joy.get_axis(3)

        if self.rotation > 75:
            self.rotation = 75

        if self.rotation < -75:
            self.rotation = -75

        if self.rect.centery > 650:
            self.rect.centery = 650

        if self.rect.centery < 60:
            self.rect.centery = 60

        Mouse_x, Mouse_y = pygame.mouse.get_pos()
        global Score
        Score = (Mouse_x, Mouse_y)
        # if pressed_keys[K_UP]:
        # playsound(r"C:\Users\night\PythonProjects\GEAR.mp3")
        # self.rect = self.image.get_rect()

    def draw(self, surface):
        image, rect = rotate(self.image, self.rect, self.rotation, Vector2(210, 0))
        surface.blit(image, rect)

R1 = Arm1(0)

class Pole(pygame.sprite.Sprite):
    def __init__(self, id):
        super().__init__()
        self.image = pygame.image.load("Pole.png")
        self.image = pygame.transform.scale(self.image, (700, 700))
        self.rotation = 0
        #self.image = pygame.transform.rotate(self.image, self.rotation)
        self.rect = self.image.get_rect()
        self.rect.center = (250, 350)

    def draw(self, surface):
        image, rect = rotate(self.image, self.rect, self.rotation, Vector2(0,0))
        surface.blit(image, rect)

P1 = Pole(1)

class arm2(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.joy = pygame.joystick.Joystick(0)
        # self.name = self.joy.get_name()
        self.joy.init()
        self.image = pygame.image.load("arm1.png")
        self.rect = self.image.get_rect()
        self.rect.center = (R1.rect.center)
        self.offset = Vector2(0, 0)
        self.direction = 0
        self.toggled = False

    def update(self):
        pressed_keys = pygame.key.get_pressed()
        hat = self.joy.get_hat(0)
        self.rect.center = (R1.rect.center)

        if (pressed_keys[K_z] or self.joy.get_button(2)) and not self.toggled:
            if self.offset.x == 0:
                self.offset.x = 400
            elif self.offset.x == 400:
                self.offset.x = 0

        self.toggled = (pressed_keys[K_z] or self.joy.get_button(2))
        if self.offset.x > 400:
            self.offset.x = 400

        if self.offset.x < 0:
            self.offset.x = 0

    def draw(self, surface):
        image, rect = rotate(self.image, self.rect, R1.rotation, Vector2(210,0))
        rotatedoffset = self.offset.rotate(-R1.rotation)
        rect = image.get_rect(center=rect.center+rotatedoffset)
        surface.blit(image, rect)

R2 = arm2()

class fingers(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.joy = pygame.joystick.Joystick(0)
        # self.name = self.joy.get_name()
        self.joy.init()
        self.image = pygame.image.load("fingers.png")
        self.image = pygame.transform.scale(self.image, (200, 200))
        self.rect = self.image.get_rect()
        self.rect.center = (R1.rect.center)
        self.offset = Vector2(0, 0)
        self.direction = 0
        self.toggled = False
        self.closed = False

    def update(self):
        actualcenter = Vector2 (self.rect.centerx, self.rect.centery)
        actualcenter += Vector2 (535 + R2.offset.x,0).rotate (-R1.rotation)
        if self.joy.get_button(3) and not self.toggled and not self.closed:
            self.image = pygame.image.load("closedfingers.png")
            self.image = pygame.transform.scale(self.image, (200, 200))
            if C1.rect.centerx > actualcenter.x - 100 and C1.rect.centerx < actualcenter.x + 100 and C1.rect.centery > actualcenter.y - 100 and C1.rect.centery < actualcenter.y + 100:
                C1.grabbed = True
            self.closed = True
        elif self.joy.get_button(3) and not self.toggled and self.closed:
            self.image = pygame.image.load("fingers.png")
            self.image = pygame.transform.scale(self.image, (200, 200))
            if C1.grabbed:
                C1.rect.center = (actualcenter.x, actualcenter.y)
            C1.grabbed = False
            self.closed = False

        self.toggled = self.joy.get_button(3)

    def draw(self, surface):
        self.rect.center = (R1.rect.center)
        image, rect = rotate(self.image, self.rect, R1.rotation, Vector2(210,0))
        rotatedoffset = (R2.offset + Vector2(325,0)).rotate(-R1.rotation)
        rect = image.get_rect(center=rect.center+rotatedoffset)
        surface.blit(image, rect)

F1 = fingers()

class cube(pygame.sprite.Sprite):
    def __init__(self, id):
        super().__init__()
        self.image = pygame.image.load("cubefrc.png")
        self.image = pygame.transform.scale(self.image, (200, 200))
        self.rotation = 0
        #self.image = pygame.transform.rotate(self.image, self.rotation)
        self.rect = self.image.get_rect()
        self.rect.center = (1200, 650)
        self.grabbed = False
        self.velocity  = 0
        self.prevy = 650

    def update(self):
        self.prevy = self.rect.centery
        if self.grabbed == True:
            self.rect.center = F1.rect.center
        if not self.grabbed:
            self.velocity += 0.1
            self.rect.centery += self.velocity
        if self.rect.centery > 650:
            self.rect.centery = 650
            self.velocity = 0
        if self.prevy <= 110 and self.rect.centery > 110 and self.rect.centerx > 910 and self.rect.centerx < 1490:
            self.rect.centery = 110
            self.velocity = 0

    def draw(self, surface):
        if self.grabbed == True:
            self.rect.center = (R1.rect.center)
            image, rect = rotate(self.image, self.rect, R1.rotation, Vector2(210,0))
            rotatedoffset = (R2.offset + Vector2(325,0)).rotate(-R1.rotation)
            rect = image.get_rect(center=rect.center+rotatedoffset)
            surface.blit(image, rect)
        else:
            surface.blit(self.image, self.rect)

C1 = cube(3)

class Shelf(pygame.sprite.Sprite):
    def __init__(self, id):
        super().__init__()
        self.image = pygame.image.load("shelf.png")
        self.image = pygame.transform.scale(self.image, (700, 700))
        self.rotation = 0
        #self.image = pygame.transform.rotate(self.image, self.rotation)
        self.rect = self.image.get_rect()
        self.rect.center = (1200, 300)

    def draw(self, surface):
        image, rect = rotate(self.image, self.rect, self.rotation, Vector2(0,0))
        surface.blit(image, rect)

S1 = Shelf(4)

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    R1.update()
    R2.update()
    F1.update()
    C1.update()
    DISPLAY.fill(WHITE)
    S1.draw(DISPLAY)
    R1.draw(DISPLAY)
    P1.draw(DISPLAY)
    R2.draw(DISPLAY)
    F1.draw(DISPLAY)
    C1.draw(DISPLAY)

    font = pygame.font.SysFont(None, 24)
    img = font.render(str(Score), True, RED)
    DISPLAY.blit(img, (20, 20))
    pygame.display.update()
    FramePerSec.tick(FPS)


# -*- coding: utf-8 -*-
"""
HALOS
flux_model module
Framework for building out models for flux modeling and outputting images
to either a data file or an optimization model.
"""
import csv

import matplotlib.pyplot as plt
import numpy

import sol_pos
import sp_module

def ReadWeatherFile(weather_file, get_angles=False):
    """
    Reads in a Typical Meteroological Year (TMY) weather file compatible
    with SolarPILOT and records time-series DNI, plus lat/lon coordinates.
    This is stored as a dictionary under the member name 'weather_data'.

    arguments:
        weather_file -- path to TMY weather file

    returns:
        weather_data, a dictionary with categorical and time-series data
    """
    weather_data = {"dni": numpy.zeros(8760, dtype=float),
                    "year": numpy.zeros(8760, dtype=int),
                    "month": numpy.zeros(8760, dtype=int),
                    "day": numpy.zeros(8760, dtype=int),
                    "hour": numpy.zeros(8760, dtype=int),
                    "solar_zenith": numpy.zeros(8760, dtype=float),
                    "solar_azimuth": numpy.zeros(8760, dtype=float)}
    reader = csv.reader(open(weather_file, 'r'))
    # First line is column headers for categorical data
    header_keys = next(reader)
    # Second line is data for first line of headers; record lat and lon
    fline = next(reader)
    d = {}
    for i in range(len(fline)):
        d[header_keys[i]] = fline[i]
    weather_data["lat"] = float(d["Latitude"])
    weather_data["lon"] = float(d["Longitude"])
    weather_data["time_zone"] = float(d["Time Zone"])
    # Third line is column headers for time-series data, just track dni
    keys = next(reader)
    year_idx = keys.index("Year")
    month_idx = keys.index("Month")
    day_idx = keys.index("Day")
    hour_idx = keys.index("Hour")
    if d["Source"] == "IWEC" or d["Source"]=="INTL":
        dni_idx = keys.index("Beam")
    else:
        dni_idx = keys.index("DNI")
    #Record time-series data
    t = 0
    for line in reader:
        weather_data["dni"][t] = float(line[dni_idx])
        weather_data["year"][t] = int(line[year_idx])
        weather_data["month"][t] = int(line[month_idx])
        weather_data["day"][t] = int(line[day_idx])
        weather_data["hour"][t] = int(line[hour_idx])
        t += 1
        if t == 8760:
            break
    if get_angles:
        import sol_pos
        zenith, azimuth = sol_pos.solar_position(weather_data)
        weather_data["solar_zenith"] = numpy.array(zenith)
        weather_data["solar_azimuth"] = numpy.array(azimuth)
    return weather_data

class FluxModel(object):
    def __init__(self,sun_shape, mirror_shape, receiver, flux_method,
                 weather_file, field, filenames = None, hour_id = None,
                 use_sp_flux = False, dni = None, read_flux_from_file = False):
        self.sun_shape = sun_shape
        self.mirror_shape = mirror_shape
        self.receiver = receiver
        self.flux_method = flux_method
        self.weather_data = ReadWeatherFile(weather_file)
        self.field = field
        self.filenames = filenames
        self.hour_id = hour_id
        self.use_sp_flux = use_sp_flux
        self.read_flux_from_file = read_flux_from_file
        if self.receiver.dni != None:
            self.dni = self.receiver.dni
        elif self.hour_id != None:
            self.dni = self.weather_data['dni'][hour_id]
        elif dni != None:
            self.dni = dni
        else:
            msg = "No inputs given for DNI."
            raise Exception(msg)
        if use_sp_flux:
            self.get_sp_flux_parallel()
        elif self.read_flux_from_file:
            self.get_flux_maps_from_files()
        else:
            self.get_halos_native_flux()
        if self.receiver.params["receiver_type"] == "External cylindrical":
            print("Generating Fraction Maps")
            self.getFractionMap()
        else:
            print("No fraction maps generation - Flat Plate")
            pass

    def addSettings(self,settings):
        self.settings = settings

    def HermiteConvolution(self, aim_loc, measure_loc):
        pass  # do the hermite evaluation

    def getSolarVector(self,azimuth, zenith):
        """
        returns normalized 3-d vector when given azimuth and zenith as input.
        """
        x = numpy.sin(azimuth)*numpy.cos(zenith)
        y = numpy.sin(zenith)
        z = numpy.cos(azimuth)*numpy.cos(zenith)
        return numpy.array([x,y,z])

    def GenerateSingleFluxMap(self,helio_idx,aimpoint_idx,solar_vector,approx=True):
        """
        for a single heliostat and aimpoint pairing, generates a flux image on
        the receiver.
                                     "or"
        Given use_sp_flux true and filenames to class FLuxModel generates a flux image on
        the receiver for a single Heliostat using SolarPilot API
        """

        if self.use_sp_flux:
            import sp_flux
            flux_map = sp_flux.single_helio_flux(self.filenames,self.field, helio_idx,self.weather_data,self.hour_id)
            flux_map = numpy.array(flux_map)
            return flux_map
        else:
            flux_map = numpy.zeros_like(self.receiver.x)
            helio = self.field.coords[helio_idx]
            aim = self.receiver.aimpoints[aimpoint_idx]
            center_aim = self.receiver.aimpoints[len(self.receiver.aimpoints) // 2]
            for mrow in range(len(self.receiver.x)):
                for mcol in range(len(self.receiver.x[mrow])):
                    norm_idx = mrow*len(self.receiver.x[mrow]) + mcol
                    measurement = numpy.array([self.receiver.x[mrow,mcol],self.receiver.y[mrow,mcol],self.receiver.z[mrow,mcol]])
                    flux_map[mrow,mcol] += self.flux_method.GetFlux(helio,aim,measurement,self.receiver.normals[norm_idx],solar_vector,self.dni,approx,center_aim)
            return flux_map

    def GenerateFullFieldFluxMap(self,solar_vector,aimpoints,approx = True):
        """
        given a solar vector and aimpoint indices, generates a flux map of the
        receiver.
                                     "or"
        Given use_sp_flux true and filenames to class FLuxModel generates a flux image on
        the receiver using SolarPilot API
        """
        if self.use_sp_flux:
            import sp_flux
            full_map = sp_flux.full_field_flux(self.filenames)
            full_map = numpy.array(full_map)

        else:
            full_map = numpy.zeros_like(self.receiver.x)
            for i in range(self.field.num_heliostats):
                full_map += self.GenerateSingleFluxMap(i,aimpoints[i],solar_vector,approx)
        return full_map

    def GetNormalizationFactor(self,mirror_power,flux_map):
        return mirror_power / sum(flux_map*self.receiver.surface_area.flatten())

    def flux_by_section(self, section_id):
        """
        Given section ID returns dict of helios-flux_map pairing

        Parameters
        ----------
        section_id :
            index of section

        Returns
        -------
        flux : dict
            key: Helio_index, Value: Flux_map

        """
        flux = {}
        if self.use_sp_flux:
            for h in self.field.helios_by_section[section_id]:
                flux_map = self.sp_flux.get_single_helio_flux(h,self.weather_data,self.hour_id,self.dni)
                flux[h] = numpy.array(flux_map)
        elif self.read_flux_from_file:
            import inputs
            num_cols = self.receiver.params["pts_per_len_dim"]
            num_rows = self.receiver.params["pts_per_ht_dim"]
            for h in self.field.helios_by_section[section_id]:
                fname = self.filenames["heliostat_file_dir"]+"heliostat"+str(h+1)+".csv"
                flux[h] = inputs.readFluxMapFromCSV(fname, num_rows, num_cols)
        else:
            for h in self.field.helios_by_section[section_id]:
                if self.receiver.params["receiver_type"] == "Flat plate":
                    center_idx = len(self.receiver.aimpoints) // 2
                else:
                    center_idx = len(self.receiver.aimpoints[h]) // 2
                solar_vector = self.getSolarVector(self.weather_data["solar_azimuth"][self.hour_id], self.weather_data["solar_zenith"][self.hour_id])
                flux_map = self.GenerateSingleFluxMap(h, center_idx, solar_vector, True)
                flux[h] = numpy.array(flux_map)
        return flux

    def get_halos_native_flux(self):
        """
        Get flux map per heliostat in parallel Using HALOS

        Returns
        -------
        None. Populates self.parallel_flux_maps

        """
        self.sp_flux = sp_module.SP_Flux(self.filenames, self.field)
        print(len(self.field.x))
        section_id = []
        for s in range(self.field.num_sections):
            section_id.append(s)
        self.parallel_flux_maps = {}
        for s in section_id:
            sect = self.flux_by_section(s)
            self.parallel_flux_maps.update(sect)
        for h in self.parallel_flux_maps.keys():
            self.parallel_flux_maps[h] = numpy.matrix(self.parallel_flux_maps[h]).round(3)  # round to nearest Watt
        print("HALOS Native Flux Calculation - Done!")

    def get_flux_maps_from_files(self):
        """
        Get flux maps by reading CSV files directly.

        Returns
        -------
        None. Populates self.parallel_flux_maps
        """
        section_id = []
        for s in range(self.field.num_sections):
            section_id.append(s)
        import multiprocessing
        p = multiprocessing.Pool(multiprocessing.cpu_count())
        results = p.map(self.flux_by_section, section_id)
        self.parallel_flux_maps = {}
        for sect in results:
            self.parallel_flux_maps.update(sect)
        for h in self.parallel_flux_maps.keys():
            self.parallel_flux_maps[h] = numpy.matrix(self.parallel_flux_maps[h]).round(3)  # round to nearest Watt
        print("Parallel Flux Calculation - Done!")
        del (p)

    def get_sp_flux_parallel(self):
        """
        Get flux map per heliostat in parallel Using Solarpilot

        Returns
        -------
        None. Populates self.parallel_flux_maps

        """
        self.sp_flux = sp_module.SP_Flux(self.filenames, self.field)
        section_id = []
        for s in range(self.field.num_sections):
            section_id.append(s)
        import multiprocessing
        p = multiprocessing.Pool(multiprocessing.cpu_count())
        results = p.map(self.flux_by_section, section_id)
        self.parallel_flux_maps = {}
        for sect in results:
            self.parallel_flux_maps.update(sect)
        for h in self.parallel_flux_maps.keys():
            self.parallel_flux_maps[h] = numpy.matrix(self.parallel_flux_maps[h]).round(3)  #round to nearest Watt
        print("Parallel Flux Calculation - Done!")
        del(p)

    def ShiftImage_GenerateSingleHeliostatFluxMaps(self,helio_idx,solar_vector,approx=True):
        """
        Given the heliostat, a solar vector, dni, and an efficiency map,
        generates a flux map of the receiver for each aimpoint-measurement
        point pair.
        FLux map at center aimpoint is shifted on other aimpoints as well.
        Here, the flux maps are flatteend into 1-dimensional
        arrays for the optimization model.

        Returns
        -------
        maps:  Dictionary
            Key is the index of the aimpoint whereas value has the repected
            flux map generated through shifting center aim map.

        """
        def shift_2d_array(data, dx, dy, constant=False):
            """
            Shifts the array in two dimensions while setting rolled values to constant

            Parameters
            ----------
            data : 2D Array
                The 2d numpy array to be shifted
            dx : int
                The shift in x
            dy : int
                The shift in y
            constant :  optional
                The constant to replace rolled values with

            Returns
            -------
            shifted_array : 2D Array
                The shifted array with "constant" where roll occurs

            """

            shifted_data = numpy.roll(data, dx, axis=1)
            if dx < 0:
                shifted_data[:, dx:] = constant
            elif dx > 0:
                shifted_data[:, 0:dx] = constant

            shifted_data = numpy.roll(shifted_data, dy, axis=0)
            if dy < 0:
                shifted_data[dy:, :] = constant
            elif dy > 0:
                shifted_data[0:dy, :] = constant
            return shifted_data
        #Getting center map using same code of previous function
        maps = {}
        aim_rows = int(self.receiver.params["aim_rows"])
        #sp_flux_dict = self.flux_dict_SP()
        #map_center = numpy.array(self.sp_flux_dict[helio_idx + 1])
        if self.receiver.params["receiver_type"] == "External cylindrical":
            center_idx = len(self.receiver.aimpoints[helio_idx]) // 2
            aim_cols = 1
            #PARALLEL FLUX
            map_center = self.parallel_flux_maps[helio_idx]
            x_shift_size = 0
            y_shift_size = round(len(map_center)/aim_rows)

        elif self.receiver.params["receiver_type"] == "Flat plate":
            center_idx = len(self.receiver.aimpoints) // 2
            map_center = self.parallel_flux_maps[helio_idx]
            aim_cols = int(self.receiver.params["aim_cols"])
            x_shift_size = round(len(map_center)/aim_cols)
            y_shift_size = round(len(map_center)/aim_rows)
        map_center = numpy.array(map_center)
        center_map = map_center.flatten()
        if not (self.use_sp_flux or self.read_flux_from_file):
            mirror_power = self.dni * self.field.mirror_area
            factor = self.GetNormalizationFactor(mirror_power,center_map)
        else:
            factor = 1.0
        maps[center_idx] = factor * center_map # Center map stored in dict after flatting
        # Image Shifting uses Center MAP before flatting
        for y_shift in range(0,(aim_rows//2)+1): #Aimpoint are 5 by 5 so we have to 2 steps up and 2 steps down. y_shift zero is center row
            #y_shift +ive goes downwards
            for x_shift in range(0,(aim_cols//2)+1): #Similarly x_shift 0 is center column where as +2 is ahead and -2 is behind
                ## Center Line
                ## Positive in x moves ahead - Positive in y here moves down
                x_frwd = shift_2d_array(map_center, x_shift*x_shift_size, y_shift*y_shift_size, constant=0)
                ##TO PLOT
                # im = plt.imshow(x_frwd)
                # plt.colorbar(im)
                # plt.tight_layout()
                # plt.show()
                maps[center_idx + (aim_cols * y_shift) + x_shift] = factor * x_frwd.flatten()
                x_bcwd = shift_2d_array(map_center, - x_shift*x_shift_size, y_shift*y_shift_size, constant=0)
                ##TO PLOT
                # im = plt.imshow(x_bcwd)
                # plt.colorbar(im)
                # plt.tight_layout()
                # plt.show()
                maps[center_idx + (aim_cols * y_shift) - x_shift] = factor * x_bcwd.flatten()
                ## Negative in x moves behind - Negative in y here moves up from center
                x_frwd = shift_2d_array(map_center, x_shift*x_shift_size, - y_shift*y_shift_size, constant=0)
                maps[center_idx - (aim_cols * y_shift) + x_shift] = factor * x_frwd.flatten()
                x_bcwd = shift_2d_array(map_center, - x_shift*x_shift_size, - y_shift*y_shift_size, constant=0)
                maps[center_idx - (aim_cols * y_shift) - x_shift] = factor * x_bcwd.flatten()
        #print(maps.keys())   ##Indexes Tested - Image shift tested using plotting
        return maps

    def SectionFluxMap(self):
        """
        Calculates section wise column sum of heliostat wise flux_maps

        Returns
        -------
        Dictionary with column sum of flux for each section

        """
        self.flux_sum_cols = {}
        for s in range(self.field.num_sections):
            flux = numpy.matrix(numpy.zeros_like(self.receiver.x))
            for h in self.field.helios_by_section[s]:
                map_center = numpy.matrix(self.parallel_flux_maps[h])
                flux = flux + map_center
            print("Section Number: ", s)
            sum_col = numpy.sum(numpy.array(flux), axis = 0)
            self.flux_sum_cols[s] = sum_col
        return self.flux_sum_cols

    def getFractionMap(self):
        """
        Using Section Column flux sum calculates the fraction for each column.
        The fraction is used to divide flux limits on the receiver in cylindrical
        case.

        Returns
        -------
        None, Populates self.fraction_maps

        """
        import pandas
        col_sum_each_map = self.SectionFluxMap()
        col_sums = []  # Stores sum as: 1st list is sum of 1st column of each section

        for ncol in range(self.receiver.params["pts_per_len_dim"]):
            col_sum_each_column = []   #Stores sum of one specific column from each section
            for s in range(self.field.num_sections):
                col_sum_each_column.append((col_sum_each_map[s])[ncol])
            col_sums.append(col_sum_each_column)

        self.fraction_maps = []
        for s in range(self.field.num_sections):
            fraction_map = pandas.DataFrame(numpy.zeros_like(self.receiver.x))
            for ncol in range(self.receiver.params["pts_per_len_dim"]):
                fraction_map[ncol] = fraction_map[ncol] + (col_sums[ncol])[s]/sum(col_sums[ncol])
            self.fraction_maps.append(numpy.array(fraction_map))

    def GenerateSingleHeliostatFluxMaps(self,helio_idx,solar_vector,dni,approx=True):
        """
        given the heliostat, a solar vector, dni, and an efficiency map,
        generates a flux map of the receiver for each aimpoint-measurement
        point pair.  Here, the flux maps are flatteend into 1-dimensional
        arrays for the optimization model.
        """
        center_idx = len(self.receiver.aimpoints) // 2
        maps = {}
        center_map = self.GenerateSingleFluxMap(helio_idx,center_idx,solar_vector,approx).flatten()
        mirror_power = dni * self.field.mirror_area
        factor = self.GetNormalizationFactor(mirror_power,center_map)
        maps[center_idx] = factor * center_map
        for aimpoint_idx in range(len(self.receiver.aimpoints)):
            if aimpoint_idx != center_idx:
                maps[aimpoint_idx] = factor * self.GenerateSingleFluxMap(helio_idx,aimpoint_idx,solar_vector,approx).flatten()
        return maps

    def GenerateFullFluxProblem(self,solar_vector,dni,outfile=None,approx=True):
        all_maps = {}
        for helio_idx in range(self.field.num_heliostats):
            all_maps[helio_idx] = self.GenerateSingleHeliostatFluxMaps(helio_idx,solar_vector,dni,approx)
        return all_maps

if __name__ == "__main__":
    import sun_shape
    import geometry
    import mirror_model
    import field

    sun = sun_shape.SinglePointSun(0)
#    params = {"length": 21, "height": 17, "pts_per_dim": 51}
    params = {"length": 21, "height": 17, "pts_per_dim": 10, "zenith_deg": 0, "azimuth_deg": 0,
              "rec_cent_offset": [-10, 5, 0]}
    h = 150
    receiver = geometry.FlatPlateReceiver(h, params)
    receiver.generateAimpointsGrid(5,5)
    mirror = mirror_model.SinglePointGaussianMirror(numpy.array([300, 300, 0]), 5.0)
    weather_file = "./../weather_files/USA NV Tonopah Airport (TMY3).csv"
    f = field.Field()
    f.GenerateCoords(numpy.array([-200,-100,0,100,200]),numpy.array([-300,-300,-300,-300,-300]),numpy.array([0,0,0,0,0]))
    fm = FluxModel(sun, mirror, receiver, None, weather_file, f)


"""Added shop_item to artwork model

Revision ID: 9fca9afda70e
Revises: 0d14636ce3dd
Create Date: 2023-08-03 13:08:27.236487

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '9fca9afda70e'
down_revision = '0d14636ce3dd'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('artworks', sa.Column('shop_item', sa.Boolean(), nullable=True))
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('artworks', 'shop_item')
    # ### end Alembic commands ###