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

#

# In[8]:

"""

    Helper functions for the pretrained model to be used within our API.

    Author: Explore Data Science Academy.

    Note:
    ---------------------------------------------------------------------
    Plase follow the instructions provided within the README.md file
    located within this directory for guidance on how to use this script
    correctly.

    Importantly, you will need to modify this file by adding
    your own data preprocessing steps within the `_preprocess_data()`
    function.
    ----------------------------------------------------------------------

    Description: This file contains several functions used to abstract aspects
    of model interaction within the API. This includes loading a model from
    file, data preprocessing, and model prediction.

"""

# In[9]:

# Helper Dependencies
import numpy as np
import pandas as pd
import pickle
import json
import geopy

# In[10]:

test = pd.read_csv('utils/data/test_data.csv')
riders = pd.read_csv('utils/data/riders.csv')
test = test.merge(riders, how='left', on='Rider Id')

data = test.iloc[1].to_json()

# In[11]:

# Convert the json string to a python dictionary object
feature_vector_dict = json.loads(data)
# Load the dictionary as a Pandas DataFrame.
feature_vector_df = pd.DataFrame.from_dict([feature_vector_dict])

# In[12]:

feature_vector_df.iloc[0]['Order No']
query_num = test[test['Order No'] == feature_vector_df.iloc[0]['Order No']].index
test.iloc[query_num]

# In[50]:

riders = pd.read_csv('utils/data/riders.csv')

def _preprocess_data(data):
    """Private helper function to preprocess data for model prediction.

    NB: If you have utilised feature engineering/selection in order to create
    your final model you will need to define the code here.

    Parameters
    ----------
    data : str
        The data payload received within POST requests sent to our API.

    Returns
    -------
    Pandas DataFrame : <class 'pandas.core.frame.DataFrame'>
        The preprocessed data, ready to be used our model for prediction.

    """
    # Convert the json string to a python dictionary object
    feature_vector_dict = json.loads(data)
    # Load the dictionary as a Pandas DataFrame.
    feature_vector_df = pd.DataFrame.from_dict([feature_vector_dict])

    # ---------------------------------------------------------------
    # NOTE: You will need to swap the lines below for your own data
    # preprocessing methods.
    #
    # The code below is for demonstration purposes only. You will not
    # receive marks for submitting this code in an unchanged state.
    # ---------------------------------------------------------------
    # Obtain query number
    test_df = test.copy()
    query_num = test_df[test_df['Order No'] == feature_vector_df.iloc[0]['Order No']].index
    # ---------------------------------------------------------------
    # Rename Columns of test df
    test_df.iloc[query_num]

    def col_rename(df):
        """Function that renames columns and drops columns that
        were not used in the test set
        Parameters
        ----------
        df: DataFrame
              input df to rename columns for
        Returns
        -------
        new_df: DataFrame
              output df with renamed and dropped columns
              as well as a printout of dropped columns
        """
        static_dict = {"Order No":"Order No","User Id":"User Id","Vehicle Type":"Vehicle Type","Platform Type":"Platform",
            "Personal or Business":"Pers Business","Placement - Day of Month":"Place DoM",
            "Placement - Weekday (Mo = 1)":"Place Weekday","Placement - Time":"Place Time",
            "Confirmation - Day of Month":"Confirm DoM","Confirmation - Weekday (Mo = 1)":"Confirm Weekday",
            "Confirmation - Time":"Confirm Time","Arrival at Pickup - Day of Month":"Arr Pickup DoM",
            "Arrival at Pickup - Weekday (Mo = 1)":"Arr Pickup Weekday","Arrival at Pickup - Time":"Arr Pickup Time",
            "Pickup - Day of Month":"Pickup DoM","Pickup - Weekday (Mo = 1)":"Pickup Weekday","Pickup - Time":"Pickup Time",
            "Distance (KM)":"Distance KM","Temperature":"Temperature","Precipitation in millimeters":"Precipitation mm",
            "Pickup Lat":"Pickup Lat","Pickup Long":"Pickup Long","Destination Lat":"Destination Lat","Time from Pickup to Arrival":"Time from Pickup to Arrival",
            "Destination Long":"Destination Long","Rider Id":"Rider Id"}
        new_df = df.copy()
        new_cols = {}
        droplist = []
        for col in new_df.columns:
            if col in static_dict.keys():
                new_cols[col] = static_dict[col].replace(" ","_")
        else:
            droplist.append(col)
        new_df.rename(columns = new_cols, inplace=True)
        for col in droplist:
            if col in new_df.index:
                return new_df.drop(columns=droplist, inplace=True)
            return new_df

    test_df = col_rename(test_df)

    def data_preprocessing(df):
        """Function that preprocesses data used for predictions and testing
        Parameters
        ----------
        df: DataFrame
              DataFrame to preprocess.
        Returns
        -------
        df: DataFrame
              Preprocessed DataFrame

        """
        cdf = df.copy()
        old = cdf.memory_usage().sum()

        # Convert time columns to hour
        time_cols = [col for col in cdf.columns if col.endswith("Time")]
        for col in time_cols:
            cdf[col] = pd.to_datetime(cdf[col])
            cdf[col] = [time.time() for time in cdf[col]]
            cdf[col] = cdf[col].apply(lambda x: x.hour)

        # Create lists of columns to change
        integers = [col for col in cdf.columns if cdf[col].dtypes == 'int64']
        floats = [col for col in cdf.columns if cdf[col].dtypes == 'float64']

        # Reduce size of data storage types
        cdf[integers] = cdf[integers].astype('int16')
        cdf[floats] = cdf[floats].astype('float16')
        # Correcting specific columns
        if 'Distance (KM)' in cdf.columns:
            cdf['Distance (KM)'] = cdf['Distance (KM)'].astype('float16')

        new = cdf.memory_usage().sum()

        return cdf

    test_df = data_preprocessing(test_df)

    def collinear(df):
        """Function that drops chosen columns
        Parameters
        ----------
        df: DataFrame
              DataFrame to drop columns from
        cols: list-like
              Names of columns to be dropped from
        Returns
        -------
        col_df: DataFrame
              Modified DataFrame
        """
        col_df = df.copy()
        droplist = ['Place_DoM', 'Place_Weekday',
                  'Place_Time', 'Confirm_DoM',
                  'Confirm_Weekday', 'Confirm_Time',
                  'Arr_Pickup_DoM', 'Arr_Pickup_Weekday',
                  'Arr_Pickup_Time']
        if droplist[0] in col_df.columns:
            col_df = col_df.drop(columns=droplist)

        return col_df

    test_df = collinear(test_df)

#     def null(df, na_thresh = 1.0 , strategy = "median"):
#         """Function that drops columns with more than na_thresh null from

#         """
#         no_null=df.copy()
#         # Dropping NaN's
#         for col in no_null.columns:
#             missing = no_null[col].isnull().sum()/len(no_null)
#         if missing > na_thresh:
#             no_null.drop(columns=col, inplace=True)

#         # Filling NaN's
#         for col in no_null.columns:
#             if no_null[col].isnull().sum() > 0:
#                 if no_null[col].dtypes == 'object':
#                     no_null[col].fillna(no_null[col].mode(), inplace=True)
#                 elif strategy == 'mean':
#                     no_null[col].fillna(round(no_null[col].mean()), inplace=True)
#                 elif strategy == 'median':
#                     no_null[col].fillna(round(no_null[col].median()), inplace=True)
#                 elif strategy == 'rolling':
#                     no_null[col].fillna(no_null[col].rolling(7).mean(), inplace=True)
#                 else:
#                     raise ValueError
#         return no_null

    def variable_transformer(df):
        """Function to apply variable ALL transformations to dataset
        Parameters
        ----------
        df: DataFrame
              Input df to be transformed
        Returns
        -------
        trans_df: DataFrame
              Output df
        """
        index = df.index
        trans_df = df.copy()

        # # Time to number
        # for time in time_cols:
        #   if time in trans_df.columns:
        #     trans_df[time] = pd.to_datetime(trans_df[time])

        # # Feature scaling
        # predictor_cols = ['Distance_KM'	,'Temperature	','Precipitation_mm', 'No_Of_Orders', 'Age', 'Average_Rating',	'No_of_Ratings']
        # sc = StandardScaler()
        # sc.fit_transform(trans_df[predictor_cols])

        # Drop unnecessary features
        droplist = ['User_Id', 'Vehicle_Type', 'Rider_Id', 'Temperature', 'Precipitation_mm'] #, 'Pickup_Lat',	'Pickup_Long',	'Destination_Lat',	'Destination_Long', 'Temperature','Precipitation_mm', 'Pay_Day', 'Pickup_DoM']
        for col in droplist:
            if col in trans_df.columns:
                trans_df.drop(columns=col, inplace=True)

        # Reorder columns
        reindex_cols = [col for col in trans_df.columns if col != 'Time_from_Pickup_to_Arrival']
        trans_df = trans_df.reindex(columns = reindex_cols)
        trans_df.index = (index)
        original_features = [col for col in trans_df.columns if col != 'Time_from_Pickup_to_Arrival']
        return trans_df, original_features

    test_df, ori_feats = variable_transformer(test_df)

    def variable_creator(df):
        """Doctstring here
        """
        create_df = df.copy()

        # covert GPS corrdinates to distance
#         def dist(df,lat1,long1,lat2,long2):
#             list1=[]
#             geo_df = df.copy()
#             for i in range (0,len(geo_df)):
#                 coords_1 = (geo_df[lat1][i], geo_df[long1][i])
#                 coords_2 = (geo_df[lat2][i], geo_df[long2][i])

#                 distance = geopy.distance.geodesic.vincenty(coords_1, coords_2).m

#                 list1.append(distance)
#             geo_df['Geo_Distance'] = list1
#             return geo_df
#         create_df = dist(create_df,'Pickup_Lat', 'Pickup_Long', 'Destination_Lat',
#             'Destination_Long')

        # Extract hours from columns
#         create_df['Pickup_Hour'] = pd.to_datetime(create_df['Pickup_Time'].astype(str)).dt.hour

        # Determine which platform is busiest
        def is_busy(platform):
            if platform == 3:
                return True
            else:
                return False
        create_df['Platform_load'] = create_df['Platform'].apply(is_busy)

        # Which drivers are the most experienced
        def experience(age):
            if age < 1000:
                return 1
            elif age < 2000:
                return 2
            elif age < 3000:
                return 3
            return 4
        create_df['Driver_exp'] = create_df['Age'].apply(experience)

        # Business day
        def weekday(day):
            if day in [1,2,3,4,5]:
                return 1
            return 0
        create_df['Business_day'] = create_df['Pickup_Weekday'].apply(weekday)

        # Is it hot?
#         def comfort(temp):

#             if temp < 18:
#                 return 0
#             elif temp < 28.75:
#                 return 1
#             return 2
#         create_df['Comfort'] = create_df['Temperature'].apply(comfort)

        # Is pay day?
        def pay_day(DoM):
            if DoM in [30,31]:
                return True
            return False

        create_df['Pay_Day'] = create_df['Pickup_DoM'].apply(pay_day)

        # Reorder columns
        reindex_cols = [col for col in create_df.columns if col != 'Time_from_Pickup_to_Arrival'] + ['Time_from_Pickup_to_Arrival']
        create_df = create_df.reindex(columns = reindex_cols)

        create_features = [col for col in create_df.columns if col not in df.columns]

        return create_df, create_features
    test_df, new_feats = variable_creator(test_df)

    def get_dum(df):
        # Get dummies
        dummy_df = df.copy()
        dummy_cols = ['Pers_Business','Pickup_Weekday','Pickup_DoM','Platform','Pickup_Time']
        dummy_df = pd.get_dummies(dummy_df,columns=dummy_cols,drop_first=True)
        return dummy_df

    test_df = get_dum(test_df)

    test_df = test_df.iloc[query_num]

    predictor_feats = [# 'Feature',  # Individual P-Score
                  # 'Platform',
                  # 'Pers_Business',
                  # 'Pickup_DoM',
                  # 'Pickup_Weekday',
                  # 'Pickup_Time',
                  'Distance_KM', # P - 0.00
                  # 'Temperature', # P - 0.305
                  # 'Precipitation_mm', # P - 0.216
                  # 'Pickup_Lat', # location does not consider obstacles
                  # 'Pickup_Long',  # location does not consider obstacles
                  # 'Destination_Lat',  # location does not consider obstacles
                  # 'Destination_Long', # location does not consider obstacles
                  # 'No_Of_Orders', # condition number is large, 5.09e+03.
                  # 'Age', # condition number is large, 2.88e+03.
                  'Average_Rating', # P - 0.000
                  # 'No_of_Ratings', # condition number is large, 1.11e+03.
                  # 'Geo_Distance',  # condition number is large, 1.6e+04.
                  # 'Platform_load', # P - 0.229
                  'Driver_exp', # P - 0.000
                  # 'Business_day', # P - 0.000 # multicollinearity
                  # 'Comfort', # P - 0.104
                  # 'Pay_Day', # P - 0.306
                  'Pers_Business_Personal', # P - 0.002
                  'Pickup_Weekday_2', # P - 0.000
                  # 'Pickup_Weekday_3', # P - 0.369
                  # 'Pickup_Weekday_4', # P - 0.123
                  'Pickup_Weekday_5', # P - 0.000
                  'Pickup_Weekday_6', # P - 0.000
                  # 'Pickup_Weekday_7', # P - 0.292
                  # 'Pickup_DoM_2', # P - 0.939
                  # 'Pickup_DoM_3', # P - 0.947
                  # 'Pickup_DoM_4', # P - 0.355
                  # 'Pickup_DoM_5', # P - 0.577
                  # 'Pickup_DoM_6', # P - 0.737
                  # 'Pickup_DoM_7', # P - 0.304
                  'Pickup_DoM_8', # P - 0.023
                  'Pickup_DoM_9', # P - 0.021
                  # 'Pickup_DoM_10', # P - 0.725
                  'Pickup_DoM_11', # P - 0.140
                  # 'Pickup_DoM_12', # P - 0.332
                  # 'Pickup_DoM_13', # P - 0.550
                  # 'Pickup_DoM_14', # P - 0.288
                  # 'Pickup_DoM_15', # P - 0.735
                  # 'Pickup_DoM_16', # P - 0.195
                  'Pickup_DoM_17', # P - 0.098
                  # 'Pickup_DoM_18', # P - 0.229
                  # 'Pickup_DoM_19', # P - 0.425
                  # 'Pickup_DoM_20', # P - 0.845
                  # 'Pickup_DoM_21', # P - 0.553
                  'Pickup_DoM_22', # P - 0.098
                  # 'Pickup_DoM_23', # P - 0.500
                  # 'Pickup_DoM_24', # P - 0.627
                  # 'Pickup_DoM_25', # P - 0.352
                  # 'Pickup_DoM_26', # P - 0.245
                  'Pickup_DoM_27', # P - 0.001
                  # 'Pickup_DoM_28', # P - 0.746
                  'Pickup_DoM_29', # P - 0.096
                  'Pickup_DoM_30', # P - 0.079
                  # 'Pickup_DoM_31', # P - 0.565
                  # 'Platform_2', # P - 0.342
                  # 'Platform_3', # P - 0.229
                  # 'Platform_4', # P - 0.155
                  # 'Pickup_Time_7',  # P - 0.947
                  'Pickup_Time_8',  # P - 0.043
                  'Pickup_Time_9',  # P - 0.000
                  'Pickup_Time_10', # P - 0.000
                  # 'Pickup_Time_11', # P - 0.380
                  'Pickup_Time_12', # P - 0.086
                  # 'Pickup_Time_13', # P - 0.879
                  # 'Pickup_Time_14', # P - 0.625
                  'Pickup_Time_15', # P - 0.000
                  'Pickup_Time_16', # P - 0.086
                  # 'Pickup_Time_17', # P -0.325
                  # 'Pickup_Time_18', # P - 0.585
                  # 'Pickup_Time_19', # P - 0.741
                  # 'Pickup_Time_20', # P - 0.461
                  # 'Pickup_Time_21', # P - 0.300
                  # 'Pickup_Time_22', # P - 0.158
                  # 'Pickup_Time_23' # P - 0.514
    ]
    # ----------- Replace this code with your own preprocessing steps --------

    predict_vector = test_df[predictor_feats]
    # ------------------------------------------------------------------------

    return predict_vector

# In[51]:

predict_vector = _preprocess_data(data)

# In[52]:

predict_vector.head()

# In[57]:

def load_model(path_to_model:str):
    """Adapter function to load our pretrained model into memory.

    Parameters
    ----------
    path_to_model : str
        The relative path to the model weights/schema to load.
        Note that unless another file format is used, this needs to be a
        .pkl file.

    Returns
    -------
    <class: sklearn.estimator>
        The pretrained model loaded into memory.

    """
    return pickle.load(open(path_to_model, 'rb'))

# In[58]:

def make_prediction(data, model):
    """Prepare request data for model prediciton.

    Parameters
    ----------
    data : str
        The data payload received within POST requests sent to our API.
    model : <class: sklearn.estimator>
        An sklearn model object.

    Returns
    -------
    list
        A 1-D python list containing the model prediction.

    """
    # Data preprocessing.
    prep_data = _preprocess_data(data)
    # Perform prediction with model and preprocessed data.
    prediction = model.predict(prep_data)
    # Format as list for output standerdisation.
    return prediction[0].tolist()


from scrapy.crawler import CrawlerProcess
from anjuke.spiders.AnjukeCitySaleSpider import AnjukehebListSaleSpider, \
    AnjukeWuHanListSaleSpider, AnjukeJingMenListSaleSpider
from scrapy.utils.project import get_project_settings

if __name__ == '__main__':
    # 创建一个CrawlerProcess对象
    process = CrawlerProcess(settings=get_project_settings())  # 括号中可以添加参数

    process.crawl(AnjukeJingMenListSaleSpider)
    process.crawl(AnjukehebListSaleSpider)
    process.crawl(AnjukeWuHanListSaleSpider)
    process.start()


# template for "Stopwatch: The Game"
import simplegui
# define global variables
t = 0
a = 0
b = 0
bc = 0
c = 0
d = 0
running = False
x = 0
y = 0

# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
    global a, b, c, bc, d
    a = t/600
    bc = (t - a * 600)/10
    b = bc/10
    c = bc - b * 10
    d = t - a * 600 - bc * 10
    return str(a) + ":" + str(b) + str(c) + "." + str(d)

# define event handlers for buttons; "Start", "Stop", "Reset"
def start():
    global running
    timer.start()
    running = True

def stop():
    global running, d, x, y
    if running:
        timer.stop()
        y += 1
        if d == 0:
            x +=1
        running = False

def reset():
    global running, t, x, y
    if running:
        timer.stop()
        running = False
    t = 0; x = 0; y = 0

# define event handler for timer with 0.1 sec interval
def tick():
    global t
    t += 1

# define draw handler
def draw(canvas):
    global t
    canvas.draw_text(format(t), [100, 150], 36, "White")
    canvas.draw_text(str(x) + "/" + str(y),
                     [250, 50], 20, "Green")

# create frame
frame = simplegui.create_frame("Stopwatch", 300, 300)

# register event handlers
start_button = frame.add_button("Start", start, 100)
stop_button = frame.add_button("Stop", stop, 100)
reset_button = frame.add_button("Reset", reset, 100)
timer = simplegui.create_timer(100, tick)
frame.set_draw_handler(draw)

# start frame
frame.start()

# Please remember to review the grading rubric


# -*- coding: utf-'8' "-*-"
__author__ = 'mkarrer'

from openerp import SUPERUSER_ID
from openerp import tools
from openerp.osv import osv, orm, fields
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
from openerp.addons.base_tools.image import resize_to_thumbnail

# mandatory fields setting for checkout form
# HINT: used in website_sale_donate main.py -> _get_mandatory_*_fields
# ATTENTION: You must use *_mandatory_bill and *_mandatory_ship after the field name! (to later identify the fields)
class website_sale_donate_settings(osv.Model):
    _inherit = 'website'
    _columns = {
        # Billing
        'name_mandatory_bill': fields.boolean(string='name'),
        'phone_mandatory_bill': fields.boolean(string='phone'),
        'email_mandatory_bill': fields.boolean(string='email'),
        'street2_mandatory_bill': fields.boolean(string='street2'),
        'city_mandatory_bill': fields.boolean(string='city'),
        'country_id_mandatory_bill': fields.boolean(string='country_id'),
        'street_mandatory_bill': fields.boolean(string='street'),
        'state_id_mandatory_bill': fields.boolean(string='state_id'),
        'vat_mandatory_bill': fields.boolean(string='state_id'),
        'vat_subjected_mandatory_bill': fields.boolean(string='state_id'),
        'zip_mandatory_bill': fields.boolean(string='state_id'),
        # Shipping
        'name_mandatory_ship': fields.boolean(string='name'),
        'phone_mandatory_ship': fields.boolean(string='phone'),
        'street_mandatory_ship': fields.boolean(string='street'),
        'city_mandatory_ship': fields.boolean(string='city'),
        'country_id_mandatory_ship': fields.boolean(string='country_id'),
        'state_id_mandatory_ship': fields.boolean(string='state_id'),
        'zip_mandatory_ship': fields.boolean(string='street2'),
        # Country
        'country_default_value': fields.many2one('res.country', string='Default country for checkout page'),
        # Behaviour
        'add_to_cart_stay_on_page': fields.boolean(string='Add to Cart and stay on Page'),
    }
    _defaults = {
        # Mandatory for billing
        'name_mandatory_bill': 1,
        'email_mandatory_bill': 1,
        'country_id_mandatory_bill': 1,
        # Mandatory for shipping
        'name_mandatory_ship': 1,
        'phone_mandatory_ship': 1,
        'street_mandatory_ship': 1,
        'city_mandatory_ship': 1,
        'country_id_mandatory_ship': 1,
    }

class payment_interval(osv.Model):
    _name = 'product.payment_interval'
    _columns = {
        'name': fields.text('Payment Interval', required=True, translate=True),
        'product_template_ids': fields.many2many('product.template', string='Products'),
    }

payment_interval()

# HINT: Since we set this fields on product.template it is not possible to have different values for variants
#       of this product template (= product.product) - which is the intended use-case and ok ;)
class product_template(osv.Model):
    _inherit = "product.template"

    def _get_parallax_image(self, cr, uid, ids, name, args, context=None):
        result = dict.fromkeys(ids, False)
        for obj in self.browse(cr, uid, ids, context=context):
            result[obj.id] = tools.image_get_resized_images(obj.parallax_image,
                                                            big_name='parallax_image',
                                                            medium_name='parallax_image_medium',
                                                            small_name='parallax_image_small',
                                                            avoid_resize_medium=True)
        return result

    def _set_parallax_image(self, cr, uid, id, name, value, args, context=None):
        return self.write(cr, uid, [id], {'parallax_image': value}, context=context)

    def _get_square_image(self, cr, uid, ids, name, args, context=None):
        result = dict.fromkeys(ids, False)
        for obj in self.browse(cr, uid, ids, context=context):
            # need to return also an dict for the image like result[1] = {'image_square': base_64_data}
            result[obj.id] = {'image_square': False}
            if obj.image:
                result[obj.id] = {'image_square': resize_to_thumbnail(img=obj.image, box=(440, 440),)}
        return result

    def _set_square_image(self, cr, uid, id, name, value, args, context=None):
        return self.write(cr, uid, [id], {'image': value}, context=context)

    # OVERRIDE orignal image functional fields to store full size images
    def _set_image(self, cr, uid, id, name, value, args, context=None):
        return self.write(cr, uid, [id], {'image': value}, context=context)

    def _get_image(self, cr, uid, ids, name, args, context=None):
        result = dict.fromkeys(ids, False)
        for obj in self.browse(cr, uid, ids, context=context):
            result[obj.id] = tools.image_get_resized_images(obj.image, avoid_resize_medium=True)
        return result

    _columns = {
        'hide_payment': fields.boolean('Hide complete Checkout Panel'),
        'hide_price': fields.boolean('Hide Price in Shop overview Pages'),
        'hide_quantity': fields.boolean('Hide Product-Quantity-Selector in CP'),
        'simple_checkout': fields.boolean('Simple Checkout'),
        'price_donate': fields.boolean('Arbitrary Price'),
        'price_donate_min': fields.integer(string='Minimum Arbitrary Price'),
        'payment_interval_ids': fields.many2many('product.payment_interval', string='Payment Intervals'),

        'hide_search': fields.boolean('Hide Search Field'),
        'hide_categories': fields.boolean('Hide Categories Navigation'),
        'hide_image': fields.boolean('Hide Image in Checkout Panel'),
        'hide_salesdesc': fields.boolean('Hide Text in Checkout Panel'),
        'hide_panelfooter': fields.boolean('Hide Checkout Panel Footer'),

        'show_desctop': fields.boolean('Show additional Description above Checkout Panel'),
        'show_descbottom': fields.boolean('Show additional Description below Checkout Panel'),

        'desc_short_top': fields.html(string='Banner Product Description - Top'),
        'desc_short': fields.html(string='Banner Product Description - Center'),
        'desc_short_bottom': fields.html(string='Banner Product Description - Bottom'),
        'image_square': fields.function(_get_square_image, fnct_inv=_set_square_image,
            string="Square Image (Auto crop and zoom)", type="binary", multi="_get_square_image",
            store={'product.template': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10)}),
        'parallax_image': fields.binary(string='Background Parallax Image'),
        'parallax_image_medium': fields.function(_get_parallax_image, fnct_inv=_set_parallax_image,
            string="Background Parallax Image", type="binary", multi="_get_parallax_image",
            store={
                'product.template': (lambda self, cr, uid, ids, c={}: ids, ['parallax_image'], 10),
            },
            help="Medium-sized image of the background. It is automatically "\
                 "resized as a 128x128px image, with aspect ratio preserved, "\
                 "only when the image exceeds one of those sizes. Use this field in form views or some kanban views."),
        'parallax_speed': fields.selection([('static', 'Static'), ('slow', 'Slow')], string='Parallax Speed'),
        # OVERRIDE orignal image functional fields to store full size images
        'image_medium': fields.function(_get_image, fnct_inv=_set_image,
            string="Medium-sized image", type="binary", multi="_get_image",
            store={
                'product.template': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
            },
            help="Medium-sized image of the product. It is automatically "\
                 "resized as a 128x128px image, with aspect ratio preserved, "\
                 "only when the image exceeds one of those sizes. Use this field in form views or some kanban views."),
        'image_small': fields.function(_get_image, fnct_inv=_set_image,
            string="Small-sized image", type="binary", multi="_get_image",
            store={
                'product.template': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
            },
            help="Small-sized image of the product. It is automatically "\
                 "resized as a 64x64px image, with aspect ratio preserved. "\
                 "Use this field anywhere a small image is required."),
    }
    _defaults = {
        'price_donate_min': 0,
        'parallax_speed': 'slow',
        'hide_quantity': True,
    }

# Extend sale.order.line to be able to store price_donate and payment interval information
class sale_order_line(osv.Model):
    _inherit = "sale.order.line"
    _columns = {
        'price_donate': fields.float('Donate Price', digits_compute=dp.get_precision('Product Price'), ),
        'payment_interval_id': fields.many2one('product.payment_interval', string='Payment Interval ID'),
        'payment_interval_name': fields.text('Payment Interval Name'),
        'payment_interval_xmlid': fields.text('Payment Interval Name'),
    }

class sale_order(osv.Model):
    _inherit = "sale.order"

    def _website_product_id_change(self, cr, uid, ids, order_id, product_id, qty=0, line_id=None, context=None):
        context = context or {}
        res = super(sale_order, self)._website_product_id_change(cr, uid, ids, order_id, product_id, qty=qty,
                                                                 line_id=line_id, context=context)
        if context.get('price_donate'):
            res.update({'price_unit': context.get('price_donate')})
        return res

    # extend _cart_update to write price_donate and payment_interval to the sale.order.line if existing in kwargs
    def _cart_update(self, cr, uid, ids, product_id=None, line_id=None, add_qty=0, set_qty=0, context=None, **kwargs):

        # Try to recalculate all functional fields on write
        context = context or {}
        context = dict(context, recompute=True)
        context = dict(context, no_store_function=True)

        # Helper: Check if Argument is a Number and greater than zero
        def is_float_gtz(number=''):
            try:
                # if float conversion fails = except: return False
                # or if number is smaller than zero also return False
                if float(number) <= 0:
                    return False
                return True
            except:
                return False

        # Set the Quantity always to 1 or 0 if hide_quantity is set
        # HINT: We have to use product.product NOT product.temaplate beacuse it could be a product variant
        #       _cart_update always gets the product.product id !!! from the template!
        if self.pool.get('product.product').browse(cr, SUPERUSER_ID, product_id, context=context).hide_quantity:
            if add_qty >= 0:
                set_qty = 1
            else:
                set_qty = 0

        # Update context with price_donate and call super
        price_donate = kwargs.get('price_donate')
        if price_donate:
            context.update({'price_donate': price_donate})
        cu = super(sale_order, self)._cart_update(cr, uid, ids,
                                                  product_id, line_id, add_qty, set_qty, context=context, **kwargs)
        if context.get('price_donate'):
            context.pop('price_donate', None)

        payment_interval_id = kwargs.get('payment_interval_id')
        line_id = cu.get('line_id')
        quantity = cu.get('quantity')
        sol_obj = self.pool.get('sale.order.line')
        sol = sol_obj.browse(cr, SUPERUSER_ID, line_id, context=context)

        # sol.exists() is checked in case that so line was unlinked in inherited _cart_update
        if quantity > 0 and sol.exists():

            # If we come from a product page price_donate may be in the kwargs and if so we write it to so line
            # SECURITY: Make sure price_donate is some sort of float (real float conversion will be done by orm)
            # SECURITY: make sure price_donate checkbox is set in related product
            # VALIDATION: Make Sure price_donate is not lower than price_donate_min set in the product
            #             if it is lower then do not set price_donate = do not alter price_unit
            if price_donate \
                    and is_float_gtz(price_donate) \
                    and sol.product_id.price_donate \
                    and price_donate >= sol.product_id.price_donate_min:
                sol.price_donate = price_donate
                # sol_obj.write(cr, SUPERUSER_ID, [line_id], {'price_donate': price_donate, }, context=context)

            # no matter where we come from if so line already exists and has filled price_donate field we have to
            # update the price_unit again to not loose our custom price price_donate
            if sol.price_donate:
                sol.price_unit = sol.price_donate
                # sol_obj.write(cr, SUPERUSER_ID, [line_id], {'price_unit': sol.price_donate, }, context=context)

            # TODO: Hack: for no obvious reason functional fields do net get updated on sale.order.line writes ?!? so we do it manually!
            # Sadly not working
            # sol_obj.write(cr, SUPERUSER_ID, [line_id], {'price_subtotal': sol_obj._amount_line(cr, SUPERUSER_ID, [line_id], None, None, context=context), 'price_reduce': sol_obj._get_price_reduce(cr, SUPERUSER_ID, [line_id], None, None, context=context), }, context=context)

            # If Payment Interval is found in kwargs write it to the so line
            # Todo: SECURITY Check if payment_intervall_id: is an int and if it is available in product.payment_interval
            if payment_interval_id:
                # Todo: CATCH if int conversion fails (like float above)
                sol.payment_interval_id = int(payment_interval_id)
                if sol.payment_interval_id.exists():
                    sol.payment_interval_name = sol.payment_interval_id.name
                    sol.payment_interval_xmlid = sol.payment_interval_id.get_metadata()[0]['xmlid']

                    # ToDo: Try to browse and write to the sales order to update relevant fields
                    # so_obj = self.pool.get('sale.order')
                    # so = so_obj.browse(cr, SUPERUSER_ID, sol.order_id.id, context=context)
                    # so.write(cr, SUPERUSER_ID, {}, context=context)

        return cu

    # Check if there are any recurring transaction products in the sale order
    def _has_recurring(self, cr, uid, ids, field_name, arg, context=None):
        # HINT: functional Fields have to return an dict!
        #       https://doc.odoo.com/6.0/developer/2_5_Objects_Fields_Methods/field_type/
        res = {}

        # Get th ID of payment interval with xml_id once_only to use it in the search domain
        # HINT: get_object takes the module name where the record was created and NOT the model name as expected!
        model_data_obj = self.pool.get('ir.model.data')
        pi_once_only_id = model_data_obj.get_object(cr, uid, 'website_sale_donate', 'once_only').id

        # check if we can find a related SO line with an payment interval other than None or once_only
        for order in self.browse(cr, uid, ids, context=context):
            domain = [('order_id', '=', order.id), ('payment_interval_id', '!=', pi_once_only_id)]
            if self.pool.get('sale.order.line').search(cr, SUPERUSER_ID, domain, context=context):
                res[order.id] = True
            else:
                res[order.id] = False

        return res

    _columns = {
        'has_recurring': fields.function(_has_recurring,
                                         type='boolean',
                                         string='Has order lines with recurring transactions'),
    }

# Add the field - recurring_transactions to all payment providers and an image field for icons too
# ToDo If this field is not enabled for a PP it will be hidden if there is any so line with
#      a payment_interval_id in the current shopping cart. Seems that i have to do this by java script and not by
#      the controller that renders the PP?!?
# HINT: We also add a functional field to sale_order "has_recurring_transactions" type bool - This field is true
#       if there are any recurring transaction products other than  "einmailig" which has an xml_id of
#       "once_only" in this sale.order
class PaymentAcquirer(osv.Model):
    _inherit = 'payment.acquirer'
    _columns = {
        'recurring_transactions': fields.boolean('Recurring Transactions'),
        'acquirer_icon': fields.binary("Acquirer Icon", help="Acquirer Icon 120x90 PNG 32Bit"),
    }

    _defaults = {
        'recurring_transactions': False,
    }

# CROWD FUNDING EXTENSIONS
# ========================
class product_product(osv.Model):
    _inherit = 'product.product'

    def _sold_total(self, cr, uid, ids, field_name, arg, context=None):
        r = dict.fromkeys(ids, 0)
        domain = [
            ('state', 'in', ['waiting_date', 'progress', 'manual', 'shipping_except', 'invoice_except', 'done']),
            ('product_id', 'in', ids),
        ]
        for group in self.pool['sale.report'].read_group(cr, SUPERUSER_ID, domain, ['product_id', 'price_total'],
                                                         ['product_id'], context=context):
            r[group['product_id'][0]] = group['price_total']

        # HINT: functional fields functions have to return a dict in form of {id: value}
        return r

    def action_view_sales_sold_total(self, cr, uid, ids, context=None):
        result = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'sale.action_order_line_product_tree',
                                                            raise_if_not_found=True)
        result = self.pool['ir.actions.act_window'].read(cr, uid, [result], context=context)[0]
        domain = [
            ('state', 'in', ["confirmed", "done"]),
            ('product_id', 'in', ids),
        ]
        result['domain'] = str(domain)
        return result

    _columns = {
        'sold_total': fields.function(_sold_total, string='# Sold Total', type='float'),
    }

class product_template(osv.Model):
    _inherit = 'product.template'

    def _sold_total(self, cr, uid, ids, field_name, arg, context=None):
        res = dict.fromkeys(ids, 0)
        for template in self.browse(cr, SUPERUSER_ID, ids, context=context):
            res[template.id] = sum([p.sold_total for p in template.product_variant_ids])
        return res

    def _funding_reached(self, cr, uid, ids, field_name, arg, context=None):
        res = dict.fromkeys(ids, 0)
        for ptemplate in self.browse(cr, SUPERUSER_ID, ids, context=context):
            try:
                res[ptemplate.id] = int(round(ptemplate.sold_total / (ptemplate.funding_goal / 100)))
            except:
                res[ptemplate.id] = int(0)
        return res

    def action_view_sales_sold_total(self, cr, uid, ids, context=None):
        act_obj = self.pool.get('ir.actions.act_window')
        mod_obj = self.pool.get('ir.model.data')
        # find the related product.product ids
        product_ids = []
        for template in self.browse(cr, uid, ids, context=context):
            product_ids += [x.id for x in template.product_variant_ids]
        domain = [
            ('state', 'in', ["confirmed", "done"]),
            ('product_id', 'in', product_ids),
        ]
        # get the tree view
        result = mod_obj.xmlid_to_res_id(cr, uid, 'sale.action_order_line_product_tree', raise_if_not_found=True)
        result = act_obj.read(cr, uid, [result], context=context)[0]
        # add the search domain
        result['domain'] = str(domain)
        return result

    # Hack because i could not find a way to browse res.partner.name in qweb template - always error 403 access rights
    # The positive side effect is better security since no one can browse res.partner fully!
    def _get_name(self, cr, uid, ids, flds, args, context=None):
        res = dict.fromkeys(ids, 0)
        for ptemplate in self.browse(cr, SUPERUSER_ID, ids, context=context):
            if ptemplate.funding_user:
                res[ptemplate.id] = ptemplate.funding_user.name
            else:
                res[ptemplate.id] = False
        return res

    _columns = {
        'sold_total': fields.function(_sold_total, string='# Sold Total', type='float'),
        'funding_goal': fields.float(string='Funding Goal'),
        'funding_desc': fields.html(string='Funding Description (HTML Field below Bar)'),
        'funding_reached': fields.function(_funding_reached, string='Funding reached in %', type='integer'),
        'funding_user': fields.many2one('res.partner', string='Funding-Campaign User'),
        'funding_user_name': fields.function(_get_name, string="Funding-Campaign User Name", type='char'),

        'hide_fundingtextinlist': fields.boolean('Hide Funding-Text in Overview-Pages'),
        'hide_fundingbarinlist': fields.boolean('Hide Funding-Bar in Overview-Pages'),
        'hide_fundingtextincp': fields.boolean('Hide Funding-Text in Checkout-Panel'),
        'hide_fundingbarincp': fields.boolean('Hide Funding-Bar in Checkout-Panel'),
        'hide_fundingtext': fields.boolean('Hide Funding-Text in Page'),
        'hide_fundingbar': fields.boolean('Hide Funding-Bar in Page'),
        'hide_fundingdesc': fields.boolean('Hide Funding-Description in Page'),
    }


import pygame
import sys
from pygame.locals import *
from random import randint

class Player(pygame.sprite.Sprite):
    '''The class that holds the main player, and controls how they jump. nb. The player doens't move left or right, the world moves around them'''
    def __init__(self, start_x, start_y, width, height):

        pygame.sprite.Sprite.__init__(self)

        # Define list of images
        self.images = []
        self.images.append(pygame.transform.scale(
            pygame.image.load(player_image), (width, height)))
        self.images.append(pygame.transform.scale(
            pygame.image.load(player_image2), (width, height)))
        # Create an index for the images
        self.index = 0
        # Initialize to first image
        self.image = self.images[self.index]

        self.rect = self.image.get_rect()
        self.rect.x = start_x
        self.rect.y = start_y
        self.speed_y = 0
        self.base = pygame.Rect(start_x, start_y + height, width, 2)

        self.sound = pygame.mixer.Sound(jump_sound)
        self.sound.set_volume(0.2)

        self.dogsound = pygame.mixer.Sound(dog_sound)
        self.dogsound.set_volume(1.0)

    def move_y(self):
        '''this calculates the y-axis movement for the player in the
        current speed'''
        collided_y = world.collided_get_y(self.base)
        # If upward velocity or not colliding, treat as free
        if self.speed_y <= 0 or collided_y < 0:
            # Move according to speed
            self.rect.y = self.rect.y + self.speed_y
            # Accelerate speed downward
            self.speed_y = self.speed_y + gravity
        # If colliding and not moving upward
        if collided_y >0 and self.speed_y > 0:
            # y position is at the top of the block
            self.rect.bottom = collided_y

        self.base.y = self.rect.y+self.rect.height

    def jump(self, speed):
        '''This sets the player to jump, but it only can if its feet are on the floor'''
        if world.collided_get_y(self.base)>0:
            self.speed_y = speed
            self.index = 1
            self.image = self.images[self.index]
            self.sound.play()

    def update(self):
        ''' This changes the image back to standard if touching ground '''
        if world.collided_get_y(self.base)>0 and self.index >0 :
            self.index = 0
            self.image = self.images[self.index]

    def animate(self, ind):
        self.image = self.images[ind]

class World():
    '''This will hold the platforms and the goal.
    nb. In this game, the world moves left and right rather than the player'''
    def __init__(self, level, block_size, color_platform, color_goals):
        self.platforms = []
        self.goals = []
        self.posn_y = 0
        self.color = color_platform
        self.color_goals = color_goals
        self.block_size = block_size
        self.sound = pygame.mixer.Sound(level_sound)
        self.sound.play()

        for line in level:
            self.posn_x = 0
            for block in line:
                if block == '-':
                    self.platforms.append(pygame.Rect(
                        self.posn_x, self.posn_y,
                        block_size, block_size))
                if block == 'G':
                    self.goals.append(Goals(self.posn_x, self.posn_y))

                self.posn_x = self.posn_x + block_size
            self.posn_y = self.posn_y + block_size

    def move(self, dist):
        '''move the world dist pixels right (a negative dist means left)'''
        for block in self.platforms:
            block.move_ip(dist, 0)

        for block in self.goals:
            block.move_x(dist)

    def collided_get_y(self, player_rect):
        '''get the y value of the platform the player is currently on'''
        return_y = -1
        for block in self.platforms:
            if block.colliderect(player_rect):
                return_y = block.y + 1
        return return_y

    def at_goal(self, player_rect):
        '''return True if the player is currently in contact with the goal. False otherwise'''
        for block in self.goals:
            if block.rect.colliderect(player_rect):
                return True
        return False

    def update(self, screen):
        '''draw all the rectangles onto the screen'''
        for block in self.platforms:
            pygame.draw.rect(screen, self.color, block, 0)
        for block in self.goals:
            self.ball_plain = pygame.sprite.RenderPlain(self.goals)
            self.ball_plain.draw(screen)
            #pygame.draw.rect(screen, self.color_goals, block, 0)

class Doom():
    '''this class holds all the things that can kill the player'''
    def __init__(self, fireball_num, pit_depth, color):
        self.base = pygame.Rect(0, screen_y - pit_depth,
                    screen_x, pit_depth)
        self.color = color
        self.fireballs = []
        for i in range(0, fireball_num):
            self.fireballs.append(Fireball())
        self.fireball_plain = pygame.sprite.RenderPlain(self.fireballs)

        self.sound = pygame.mixer.Sound(explo_sound)
        self.sound.set_volume(0.5)

    def move(self, dist):
        '''move everything right dist pixels (negative dist means left)'''
        for fireball in self.fireballs:
            fireball.move_x(dist)

    def update(self, screen):
        '''move fireballs down, and draw everything on the screen'''
        for fireball in self.fireballs:
            fireball.move_y()
        self.fireball_plain.draw(screen)
        pygame.draw.rect(screen, self.color, self.base, 0)

    def collided(self, player_rect):
        '''check if the player is currently in contact with any of the doom.
        nb. shrink the rectangle for the fireballs to make it fairer'''
        for fireball in self.fireballs:
            if fireball.rect.colliderect(player_rect):
                hit_box = fireball.rect.inflate(
                    -int(fireball_size/2),
                    -int(fireball_size/2))
                if hit_box.colliderect(player_rect):
                    return True
        return self.base.colliderect(player_rect)

class Fireball(pygame.sprite.Sprite):
    '''this class holds the fireballs that fall from the sky'''
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.transform.scale(
            pygame.image.load(fireball_image),
            (fireball_size, fireball_size))
        self.rect = self.image.get_rect()
        self.reset()

    def reset(self):
        '''re-generate the fireball a random distance along the screen and give them a random speed'''
        self.y = 0
        self.speed_y = randint(fireball_low_speed, fireball_high_speed)
        self.x = randint(0, screen_x)
        self.rect.topleft = self.x, self.y

    def move_x(self, dist):
        '''move the fireballs dist pixels to the right
        (negative dist means left)'''
        self.rect.move_ip(dist, 0)
        if self.rect.x < -50 or self.rect.x > screen_x:
            self.reset()

    def move_y(self):
        '''move the fireball the appropriate distance down the screen
        nb. fireballs don't accellerate with gravity, but have a random speed. if the fireball has reached the bottom of the screen,
        regenerate it'''
        self.rect.move_ip(0, self.speed_y)
        if self.rect.y > screen_y:
            self.reset()

    def update(self, screen, colour):
        '''draw the fireball onto the screen'''
        pass

class Goals(pygame.sprite.Sprite):
    '''this class holds the fireballs that fall from the sky'''
    def __init__(self, xpos, ypos):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.transform.scale(
            pygame.image.load(ball_image),
            (ball_size, ball_size))
        self.rect = self.image.get_rect()
        self.rect.topleft = xpos, ypos

    def move_x(self, dist):
        '''move the fireballs dist pixels to the right
        (negative dist means left)'''
        self.rect.move_ip(dist, 0)

    def update(self, screen, colour):
        '''draw the fireball onto the screen'''
        pass

# options
mult = 2
screen_x = 600*mult
screen_y = 400*mult
game_name = "Awesome Raspberrylock size 30, posn_x 7050 posn_y 0"
player_spawn_x = 50
player_spawn_y = 200
player_image = "bruceside.png"
player_image2 = "bruce_turn_small.png"

player_width, player_height = int(30*mult), int(28*mult)
#player_width, player_height = 30*2, 28*2

ball_size = 15*mult
ball_image = "dryer_ball.png"

gravity = 0.8*mult
jump_speed = -10*mult

level=[
    "                    ",
    "                    ",
    "                    ",
    "                    ",
    "                    ",
    "                    ",
    "                    ",
    "                    ",
    "                    ",
    "          -       G ",
    "     - --   ---  -  ",
    " -- -          --   "]
   #"--------------------"

platform_color = (100, 100, 100)
block_size = int(30*mult)
goal_color = (0, 0, 255)
doom_color = (255, 0, 0)
fireball_size = int(20*mult)
fireball_number = 10
fireball_low_speed = 3
fireball_high_speed = 7
fireball_image = "flame.png"

# Sounds
jump_sound = "qubodup-cfork-ccby3-jump.ogg"
level_sound = "ambientmain_0_0.ogg"
explo_sound = "explosion1.ogg"
dog_sound = "dog_sound_1.ogg"

# initialise pygame.mixer
pygame.mixer.pre_init(44100, -16, 8, 2048)
pygame.mixer.init()

# initialise pygame
pygame.init()
window = pygame.display.set_mode((screen_x, screen_y))
pygame.display.set_caption(game_name)
screen = pygame.display.get_surface()

# load level
if len(sys.argv) > 1:
    with open(sys.argv[1]) as f:
        level = f.readlines()

# initialise variables
clock = pygame.time.Clock()
finished = False
player = Player(player_spawn_x, player_spawn_y, player_width, player_height)
player_plain = pygame.sprite.RenderPlain(player)
world = World(level, block_size, platform_color, goal_color)
doom = Doom(fireball_number, 10, doom_color)

# setup the background
background_image = "Catacomb_Entrance_Hall_by_KingCloud_crop.png"
#background_image = "Catacomb_Entrance_Hall_by_KingCloud.jpg"
#background_image = "ex_background.png"
background = pygame.transform.scale(pygame.image.load(background_image),
                                    (screen_x, screen_y)).convert()

bg_1_x = 0
bg_2_x = screen_x

while not finished:
    # blank screen
    screen.fill((0,0,0))
    # check events
    for event in pygame.event.get():
        if event.type == QUIT:
            finished = True

    # check which keys are held
    key_state = pygame.key.get_pressed()
    if key_state[K_LEFT]:
        world.move(2*mult)
        doom.move(2*mult)
        # move background at slower pace
        bg_1_x = bg_1_x + 1
        bg_2_x = bg_2_x + 1
        # if going into negative space, bring screen 2 to -screen_x + amount negative
        if bg_1_x > 0:
            bg_2_x = -screen_x+bg_1_x

    elif key_state[K_RIGHT]:
        world.move(-2*mult)
        doom.move(-2*mult)
        # move background at slower pace
        bg_1_x = bg_1_x - 1
        bg_2_x = bg_2_x - 1

        # if have moved to edge, put screen 1 in front
        if bg_2_x < 0:
            bg_1_x = screen_x+bg_2_x
        # if going from negative to positive space, bring screen 2 back in front minus movement amount
        if bg_1_x < 0:
            bg_2_x = screen_x+bg_1_x

    if key_state[K_SPACE]:
        player.jump(jump_speed)

    # move the player with gravity
    player.move_y()
    # Update the image based on whether jumping or not
    player.update()
    # render the frame
    screen.blit(background, (bg_1_x,0))
    screen.blit(background, (bg_2_x,0))
    player_plain.draw(screen)
    world.update(screen)
    doom.update(screen)

    # update the display
    pygame.display.update()
    # check if the player is dead
    if doom.collided(player.rect):
        doom.sound.play()
        pygame.time.wait(1500)
        print("You Lose!")
        finished = True
    # check if the player has completed the level
    if world.at_goal(player.rect):
        player.animate(1)
        player_plain.draw(screen)
        pygame.display.update()
        player.dogsound.play()
        pygame.time.wait(1000)
        print("Winner!")
        finished = True
    # set the speed in fps
    clock.tick(20)

pygame.quit()


import os

# Send a command to the linux terminal
def terminal(cmd):
	#print(cmd)
	return os.popen(cmd).read()

def getServerProcessID():
	output = terminal('ps -A | grep bssl')
	output = output.strip().split(' ')
	if len(output) == 0 or output[0] == '': return None
	pid = int(output[0])
	return pid

def stopServer():
	pid = getServerProcessID()
	if pid != None:
		print('Stopping server...')
		terminal(f'kill {pid}')

stopServer()


import requests
from bs4 import BeautifulSoup
import pandas as pd
import time

url = 'https://en.wikipedia.org/wiki/2018%E2%80%9319_UEFA_Champions_League'
page = requests.get(url)

columns = ['Team']
data_teams = pd.DataFrame(columns = columns)

soup = BeautifulSoup(page.text, 'html.parser')
tables = soup.find_all(class_='wikitable')

for index in range(21,29):
    rows = tables[index].find_all('tr')
    for row in range(1,len(rows)):
      td = rows[row].find_all('td')
      a = td[0].find_all('a')
      team = a[1].text
      team_data = pd.DataFrame([[team]])
      team_data.columns = columns
      data_teams = data_teams.append(team_data,ignore_index=True)


# -*- coding: utf-8 -*-
"""
Created on Sun Mar 11 23:01:13 2018

@author: narendra
"""

class Triangle(object):
  number_of_sides=3
  def __init__(self,angle1,angle2,angle3):
    self.angle1=angle1
    self.angle2=angle2
    self.angle3=angle3

  def check_angles(self):
    if (self.angle1+self.angle2+self.angle3) == 180:
      return True
    else:
      return False

class Equilateral(Triangle):
  angle=60
  def __init__(self):
    self.angle1=self.angle
    self.angle2=self.angle
    self.angle3=self.angle
my_triangle=Triangle(90,30,60)
print(my_triangle.number_of_sides)
print(my_triangle.check_angles())


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

from paasta_tools.cli.cmds import docker_exec

@patch('paasta_tools.cli.cmds.docker_exec.get_subparser', autospec=True)
def test_add_subparser(mock_get_subparser):
    mock_subparsers = mock.Mock()
    docker_exec.add_subparser(mock_subparsers)
    assert mock_get_subparser.called
    mock_get_subparser.return_value.add_argument.assert_called_with('exec_command',
                                                                    help='Command to append to docker docker_exec',
                                                                    nargs='?',
                                                                    default='/bin/bash')

@patch('paasta_tools.cli.cmds.docker_exec.subprocess', autospec=True)
@patch('paasta_tools.cli.cmds.docker_exec.get_container_name', autospec=True)
@patch('paasta_tools.cli.cmds.docker_exec.pick_slave_from_status', autospec=True)
@patch('paasta_tools.cli.cmds.docker_exec.get_status_for_instance', autospec=True)
def test_paasta_docker_exec(mock_get_status_for_instance, mock_pick_slave_from_status, mock_get_container_name,
                            mock_subprocess):
    mock_status = mock.Mock(marathon=mock.Mock(app_id='appID1'))
    mock_get_status_for_instance.return_value = mock_status
    mock_args = mock.Mock(cluster='cluster1',
                          service='mock_service',
                          instance='mock_instance',
                          host='host1',
                          mesos_id=None,
                          exec_command='/bin/bash')
    mock_pick_slave_from_status.return_value = 'host1'

    docker_exec.paasta_docker_exec(mock_args)
    mock_get_status_for_instance.assert_called_with(cluster='cluster1',
                                                    service='mock_service',
                                                    instance='mock_instance')
    mock_pick_slave_from_status.assert_called_with(status=mock_status,
                                                   host='host1')

    mock_get_container_name.assert_called_with('appID1', slave_hostname='host1', task_id=None)
    expected = ["ssh", "-o", "LogLevel=QUIET", "-tA", mock_pick_slave_from_status.return_value,
                "sudo docker exec -ti {0} ''/bin/bash''".format(mock_get_container_name.return_value)]
    mock_subprocess.call.assert_called_with(expected)


n, y = map(int, input().split())
ans = [-1, -1, -1]
for i in range(n+1):
  for j in range(n+1-i):
    k = n-i-j
    if i*10000+j*5000+k*1000 == y and k>=0:
      ans[0] = i
      ans[1] = j
      ans[2] = k
      break
print(ans[0], ans[1], ans[2])


import sys
import numpy as np
import tensorflow as tf
import cv2

import tensorflow.contrib.slim as slim
import tensorflow.contrib.layers as layers
import os
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from PIL import Image

from primesense import openni2
from primesense import _openni2 as c_api

from django_project.Hand_pose_estimation_part.data.importers import DepthImporter
from django_project.Hand_pose_estimation_part.netlib.basemodel import basenet2
from django_project.Hand_pose_estimation_part.util.realtimehandposepipeline import RealtimeHandposePipeline
from django_project.Object_detectin_part.hand_detection_RGBD import detection_results

##===================================Overview======================================================

# The system is composed from 2 main steps  :
#  1-  Hand Detection : to crop the area of interest containing the hand
#  2-  Hand Pose Estimation : to get the (X,Y) in pixels and (Z) in mm coordinates for each hand joint
# 	   using the cropped image, the final output is the araay J_Pixels

# PS : -the function model.run_sess is responsible for all the process
#
# 	   -we can add more functions to the system to exploit J_Pixels' information like getting the lowest
# 	   joint in term of depth and store it in a JSON file to controle the mose by finger mouvment
#
#      - Object detection can be done by training an SSD mobilenet detector and using the same approach
#	   of the RGB-D Hand Detector so that the 3 models can run simultaneously

#=========================Depth parameters========================================================
EXACT_TABLE_CAMERA_DISTANCE = 2000	  # in mm, greater depth values will be replaced by this one
DEPTH_THRESHOLD = 200 # in mm     ,  smaller depth values will be replaced by this one

## depth correction Coefs in case there are some problems

CORRECTION_COEF_1_AFTER_LOADING = 1
DEPTH_CORRECTION = 1
ADD_RANGE_CORRECTION = 0

## A function to rescale depth values from maximum-minimum to 0-255
## RGB-D Hand detector uses RGB(0-255) encoded format instead of 1 depth channel with mm values
min_depth_for_scaling = 0   # changes for each image
max_depth_for_scaling = 1500
def Depth_to_255_scale(entry):
    if entry>max_depth_for_scaling or entry<50:
        return 0
    else :
        return 255-((entry-min_depth_for_scaling)/(max_depth_for_scaling-min_depth_for_scaling)*255)

Depth_to_255_scale = np.vectorize(Depth_to_255_scale)

## A function to remove depth noise (noisy values are zeros)
def remove_noise(entry):
	global m
	mapper_dict = {0:m}   ## noise replaced by maximum depth in every frame

	return mapper_dict[entry] if entry in mapper_dict else entry

remove_noise = np.vectorize(remove_noise)
m = 0

def DepthMapCorrection(depth):
		"""
		Correcting the depth map
		:return: image data of depth image
		"""
		global m,MAXIMUM_DEPTH_RANGE,CORRECTION_COEF_1_AFTER_LOADING,DEPTH_CORRECTION, min_depth_for_scaling

		## Storing maximum depth
		m = np.max(depth)
		## removing noise
		depth = remove_noise(depth)
		##storing minimum depth
		min_depth_for_scaling = np.min(depth)
		## Converting to a numpy array
		imgdata = np.asarray(depth, np.float32)/CORRECTION_COEF_1_AFTER_LOADING*DEPTH_CORRECTION + ADD_RANGE_CORRECTION

		return imgdata

## The hand Pose estimation Model :
class model_setup():
	def __init__(self,dataset,model_path):
		self._dataset=dataset
		self.model_path=model_path
		self.inputs = tf.placeholder(dtype=tf.float32, shape=(None, 96, 96, 1))  ## Image size is fixed
		self.hand_tensor=None
		self.model()
		self.saver = tf.train.Saver(max_to_keep=15)

### the model's configurations
	def __self_dict(self):
		return (14,9,5)

	def __config(self):
		flag=-1
		di = DepthImporter(fx=535.4, fy=flag*539.2, ux=320.1, uy=247.6)
		config = {'fx': di.fx, 'fy': abs(di.fy), 'cube': (250,250, 250), 'im_size': (96, 96)}
		return di, config

	def __crop_cube(self):
		return self.__config()[1]['cube'][0]
	def __joint_num(self):
		return self.__self_dict()[0]

## the model's initialization
	def model(self):
		outdims=self.__self_dict()
		fn = layers.l2_regularizer(1e-5)
		fn0 = tf.no_regularizer
		with slim.arg_scope([slim.conv2d, slim.fully_connected],
							weights_regularizer=fn,
							biases_regularizer=fn0, normalizer_fn=slim.batch_norm):
			with slim.arg_scope([slim.batch_norm],
								is_training=False,
								updates_collections=None,
								decay=0.9,
								center=True,
								scale=True,
								epsilon=1e-5):
				pred_comb_ht, pred_comb_hand, pred_hand, pred_ht = basenet2(self.inputs, kp=1, is_training=False,
																			outdims=outdims)

		self.hand_tensor=pred_hand

### the entire process :

	def sess_run(self,detection_graph=0,detection_sess=0):

		## rtp library, containing some useful functions
		_di,_config=self.__config()

		rtp = RealtimeHandposePipeline(1, config=_config, di=_di, verbose=False, comrefNet=None,maxDepth=EXACT_TABLE_CAMERA_DISTANCE,minDepth=DEPTH_THRESHOLD)
		joint_num=self.__joint_num()  ## 14 joints
		cube_size=self.__crop_cube()  ##  to rescale the cropped hand image

		with tf.Session() as sess:
			init = tf.global_variables_initializer()
			sess.run(init)
			self.saver.restore(sess, self.model_path)

			### Initialize OpenNI with its libraries

			frameRate = 30
			width = 640 		# Width of image
			height = 480		# height of image
			openni2.initialize("django_project\\orbbec-astra\\Redist") #The OpenNI2 Redist folder
			# Open a device
			dev = openni2.Device.open_any()
			# Open two streams: one for color and one for depth
			depth_stream = dev.create_depth_stream()
			depth_stream.start()
			depth_stream.set_video_mode(c_api.OniVideoMode(pixelFormat = c_api.OniPixelFormat.ONI_PIXEL_FORMAT_DEPTH_1_MM, resolutionX = width, resolutionY = height, fps = frameRate))

			color_stream = dev.create_color_stream()
			color_stream.start()
			color_stream.set_video_mode(c_api.OniVideoMode(pixelFormat = c_api.OniPixelFormat.ONI_PIXEL_FORMAT_RGB888, resolutionX = width, resolutionY = height, fps = frameRate))

			# Register both streams so they're aligned
			dev.set_image_registration_mode(c_api.OniImageRegistrationMode.ONI_IMAGE_REGISTRATION_DEPTH_TO_COLOR)
			# Set exposure settings
			# Camera Exposure
			bAutoExposure = Fals
			exposure = 100
			if (color_stream.camera != None):
				color_stream.camera.set_auto_exposure(bAutoExposure)
				color_stream.camera.set_exposure(exposure)

			## ===================================main loop==============================================
			while True:

				## Loading and correcting depth frame
				frame = depth_stream.read_frame()
				frame_data = frame.get_buffer_as_uint16()
				depthPix = np.frombuffer(frame_data, dtype=np.uint16)
				depthPix.shape = (height, width)

				depthPix = DepthMapCorrection(depthPix)

				## ____________________RGB-D based hand detection :____________________________________
				# transform 1 channel depth image to RGB channels
				detection_frame = np.array(Image.fromarray(Depth_to_255_scale(depthPix)).convert('RGB'))

				##Detection :
				processed_image, cropped,[xmin,xmax,ymin,ymax] = detection_results( detection_graph,detection_frame ,detection_sess,score_threshold=0.2)
				cv2.imshow('detection_frame',processed_image)

				depthPix_original = depthPix.copy()
				depthPix = depthPix[xmin : xmax, ymin:ymax]
				cv2.imshow('cropped',cropped)
				## returning cropped depth image :depthPix  (original size 200x200 : change it in the hand detection folder )

				try:
					## loc is the center's coordinates of our bounding box in (pixels,pixels,mm), used to make the center of mass of the hand closer to it instead of the closest object to the camera
					loc_rgbd_detector = [depthPix.shape[0]//2,depthPix.shape[1]//2,depthPix[depthPix.shape[0]//2,depthPix.shape[1]//2]]

					## Countour based Hand detection + image preprocessing + the hand's center of mass com3D
					crop1, M, com3D,bounds = rtp.detect(depthPix,loc_rgbd_detector)
					if com3D[0]==0:
						continue # skipping errors during hand detection using COM and contours

					crop = crop1.reshape(1, crop1.shape[0], crop1.shape[1], 1).astype('float32')

					##____________________________Hand pose estimation______________________________________
					pred_ = sess.run(self.hand_tensor, feed_dict={self.inputs: crop})
					norm_hand = np.reshape(pred_, (joint_num, 3))

					## from normalized and relative to com3D to global coordinates
					pose = norm_hand * cube_size / 2. + com3D

					## Show results
					img,J_pixels = rtp.show3(depthPix_original, pose,self._dataset,(np.float32(xmin), np.float32(ymin)))
					cv2.imshow('frame', img)
					cv2.imshow('crop1', crop1)

					print('com3D :',com3D,' pose[0] :',pose[0],' pixels[0] ' ,J_pixels[0])
				except:
					print('error happened')
					continue
				if cv2.waitKey(1) >= 0:
					break
		openni2.unload()

		cv2.destroyAllWindows()


"""
Notes:

    1) This script will make csv files for each block.
    2) Orients from block_length (number of trials per category),
        and stim_dict.
    3) Assumes dimensional stimuli are called "foo_low" and "foo_high"
        for mapping assignment.
    4) Assumes stimuli are found in ../Stimuli/foo, will write to ../blocks/BlockX.csv

Updates:
    1) Dropped "Dim" from task
    2) randomized category assignment
        writes blocks for e/subj to ../blocks/sub-*/BlockX.csv
        receives single subj arg
        removed "dim" syntax (for syntax - v0.1)

TODO
    1) update to receive list of subj?

Usage: python job_taskSetup.py 1
"""
import os
import sys
import random
import pathlib
from random import randrange
import pandas as pd

def main(subj):
    """
    Set up

    Fix1/2 = fixed mapping
    Cond = conditional mapping

    stim_dict["Block1"]["Fix1"]: "School" = School
        stimuli will be used for fixed mapping in block1.
        Also, stimuli will be located in stim_dir/School
    """

    # set paths
    parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    stim_dir = os.path.join(parent_dir, "stimuli")
    stim_p = pathlib.Path(stim_dir)
    stim_rel = pathlib.Path(*stim_p.parts[5:])

    block_dir = os.path.join(parent_dir, "blocks")
    if not os.path.exists(block_dir):
        os.makedirs(block_dir)

    """
    Make stim lists per block, for psychopy.

    Will randomize L/R for fixed and dimension mappings (ref coin_toss).
    Conditional mapping is based off preceding trial.
    Dataframe will not start with conditional trial.
    """

    # set block length
    block_length = 60

    # dict of categories
    cat_list = [
        "Dangerous",
        "Healthy",
        "Old",
        "Sad",
        "School",
        "Small",
        "Smell",
        "Soft",
        "Wealth",
    ]

    # make random stim_dict
    cat_rand = random.sample(cat_list, len(cat_list))
    stim_dict = {
        "Block1": {"Fix1": cat_rand[0], "Fix2": cat_rand[1], "Cond": cat_rand[2]},
        "Block2": {"Fix1": cat_rand[3], "Fix2": cat_rand[4], "Cond": cat_rand[5]},
        "Block3": {"Fix1": cat_rand[6], "Fix2": cat_rand[7], "Cond": cat_rand[8]},
    }

    # make individual blocks
    for block in stim_dict:
        # block = "Block1"

        # randomly assign fixed mapping
        coin_toss = randrange(2)
        corr_A = "left" if coin_toss == 1 else "right"
        corr_B = "left" if corr_A == "right" else "right"

        # set up block dictionary
        #   pull random stim of length = block_length
        block_dict = {
            "Fix1": [
                [corr_A] * block_length,
                [
                    os.path.join(stim_rel, stim_dict[block]["Fix1"], x)
                    for x in random.sample(
                        os.listdir(os.path.join(stim_dir, stim_dict[block]["Fix1"])),
                        block_length,
                    )
                ],
            ],
            "Fix2": [
                [corr_B] * block_length,
                [
                    os.path.join(stim_rel, stim_dict[block]["Fix2"], x)
                    for x in random.sample(
                        os.listdir(os.path.join(stim_dir, stim_dict[block]["Fix2"])),
                        block_length,
                    )
                ],
            ],
            "Cond": [
                ["Cond"] * block_length,
                [
                    os.path.join(stim_rel, stim_dict[block]["Cond"], x)
                    for x in random.sample(
                        os.listdir(os.path.join(stim_dir, stim_dict[block]["Cond"])),
                        block_length,
                    )
                ],
            ],
        }

        # make master_dict for pandas df, randomize df,
        #   don't start with cond type
        master_dict = {f"{block}Type": [], f"{block}Stim": [], f"{block}Corr": []}
        for key in block_dict.keys():
            for ind in range(0, block_length):
                master_dict[f"{block}Type"].append(key)
                master_dict[f"{block}Stim"].append(block_dict[key][1][ind])
                master_dict[f"{block}Corr"].append(block_dict[key][0][ind])

        df = pd.DataFrame.from_dict(master_dict)
        df_rand = df.sample(frac=1).reset_index(drop=True)
        while df_rand.at[0, f"{block}Type"] == "Cond":
            df_rand = df.sample(frac=1).reset_index(drop=True)

        # Set conditional response (opposite from previous)
        for ind in range(0, df_rand.shape[0]):
            if df_rand.at[ind, f"{block}Corr"] == "Cond":
                old_val = df_rand.at[ind - 1, f"{block}Corr"]
                df_rand.at[ind, f"{block}Corr"] = (
                    "left" if old_val == "right" else "right"
                )

        # write df_rand to csv
        subj_dir = os.path.join(block_dir, f"sub-{subj}")
        if not os.path.exists(subj_dir):
            os.makedirs(subj_dir)
        df_rand.to_csv(os.path.join(subj_dir, f"{block}.csv"), index=False)

if __name__ == "__main__":
    h_subj = sys.argv[1]
    main(h_subj)


#!/usr/bin/env python
import common
import pulp

# NOTE(nox): Data
Proc = common.readMatrixFromFile('demand.dat')
Pv = common.readMatrixFromFile('selling_prices.dat')
Cf = common.readArrayFromFile('fixed_costs.dat')
Cv = common.readArrayFromFile('variable_costs.dat')
Cap = common.readArrayFromFile('capacity.dat')

# NOTE(nox): Indices
Mod = range(0, len(Pv))
Loj = range(0, len(Proc[0]))

# NOTE(nox): Decision variables
X = pulp.LpVariable.dicts('Number of watches', [(I,J) for I in Mod for J in Loj], cat=pulp.LpInteger, lowBound=0)
Y = pulp.LpVariable.dicts('Manufactured', Mod, cat=pulp.LpBinary)
Z = pulp.LpVariable.dicts('Sold in', [(I,J) for I in Mod for J in Loj], cat=pulp.LpBinary)

# NOTE(nox): Objective function
Model = pulp.LpProblem('Costs', pulp.LpMaximize)
Model += (sum(X[(I,J)]*(Pv[I][J] - Cv[I]) for I in Mod for J in Loj) -
          sum(Y[I]*Cf[I] for I in Mod))

# NOTE(nox): Subject to
for I in Mod:
    Model += Z[(I,0)] + Z[(I,1)] <= 1
    Model += Z[(I,2)] + Z[(I,3)] + Z[(I,4)] <= 1

    Model += sum(X[(I,J)] for J in Loj) <= Cap[I]*Y[I]
    Model += sum(X[(I,J)] for J in Loj) <= Cap[I]*Y[I]

    for J in Loj:
        Model += X[(I,J)] <= Proc[I][J]*Z[(I,J)]

Model += sum((sum(X[(I,J)] for J in Loj))/Cap[I] for I in Mod) <= 1

# NOTE(nox): Solve
Status = Model.solve()

if Status == pulp.LpStatusOptimal:
  print('Objective: {}'.format(Model.objective.value()))
  for I in Mod:
      print('Model {}'.format(I+1))
      for J in Loj:
          print('   Store {} -> {}'.format(J+1, X[(I,J)].value()))
  Model.writeLP('lp.out')


#!/usr/bin/python3

import sys

reverseMappings = {
'a': 'y',
'b': 'h',
'c': 'e',
'd': 's',
'e': 'o',
'f': 'c',
'g': 'v',
'h': 'x',
'i': 'd',
'j': 'u',
'k': 'i',
'l': 'g',
'm': 'l',
'n': 'b',
'o': 'k',
'p': 'r',
'q': 'z',
'r': 't',
's': 'n',
't': 'w',
'u': 'j',
'v': 'p',
'w': 'f',
'x': 'm',
'y': 'a',
'z': 'q',
' ': ' '
}

def reverse(string):
	return ''.join([reverseMappings[c] for c in string])

# Ignore number of tests
sys.stdin.readline()

casenum=0
for line in sys.stdin:
	casenum += 1
	reversed = reverse(line.strip())
	print("Case #%d: %s" % (casenum, reversed))


import os
import hashlib
import glob
from time import sleep
from threading import Thread
from datetime import datetime
from .client import StreamClient
from .batch import Batch
from .exceptions import DataException
from .operation import Operation, Update, Delete
from .models.definitions import from_json as model_from_json

ROOT_PATH = './.panamah'
ACCUMULATED_PATH = ROOT_PATH + '/accumulated'
SENT_PATH = ROOT_PATH + '/sent'
BATCH_MAX_LENGTH = 500
BATCH_MAX_SIZE = 5 * 1024
BATCH_MAX_AGE = 5 * 60

class BatchProcessor(Thread):
    def __init__(self, authorization_token, secret, assinante_id, batch_max_length=BATCH_MAX_LENGTH, batch_max_size=BATCH_MAX_SIZE, batch_max_age=BATCH_MAX_AGE):
        Thread.__init__(self, daemon=True)
        self.initialize_structure()
        self.assinante_id = assinante_id
        self.multitenancy = assinante_id == '*'
        self.client = StreamClient(authorization_token, secret, assinante_id)
        self.current_batch = Batch(
            filename='%s/%s' % (ROOT_PATH, 'current.pbt'), force_existence=True)
        self.last_batch_hash = None
        self.batch_max_length = batch_max_length
        self.batch_max_size = batch_max_size
        self.batch_max_age = batch_max_age

    def run(self):
        while True:
            self.initialize_structure()
            self.process()

    def initialize_structure(self):
        if not os.path.exists(ACCUMULATED_PATH):
            os.makedirs(ACCUMULATED_PATH)
        if not os.path.exists(SENT_PATH):
            os.makedirs(SENT_PATH)

    def process(self):
        if self.accumulated_batch_exists():
            self.send_accumulated_batches()
        self.watch_current_batch()
        self.delete_old_batches()

    def accumulated_batch_exists(self):
        return len([file for file in os.listdir(ACCUMULATED_PATH) if file.endswith('.pbt')]) > 0

    def send_accumulated_batches(self):
        batches = self.get_accumulated_batches()
        for batch in batches:
            response = self.client.post('/stream/data', batch.json(dumps=False))
            if response.status_code == 200:
                response_data = response.json()
                if hasattr(response_data, 'falhas'):
                    self.recover_from_failures(batch, response_data.falhas)
                    break
                else:
                    batch.move(source=ACCUMULATED_PATH, destiny=SENT_PATH)
            else:
                raise DataException()

    def watch_current_batch(self):
        if self.current_batch_expired():
            self.accumulate_current_batch()
        else:
            self.write_changes_to_current_batch()

    def delete_old_batches(self):
        sent_batches = [Batch(filename='%s/%s' % (SENT_PATH, file))
                        for file in os.listdir(SENT_PATH) if file.endswith('.pbt')]
        old_batches = [
            batch for batch in sent_batches if self.current_batch.age > 24 * 60 * 60]
        if len(old_batches) > 0:
            for batch in old_batches:
                batch.delete(SENT_PATH)

    def current_batch_expired(self):
        def expired_by_count():
            return self.current_batch.length >= self.batch_max_length

        def expired_by_size():
            return self.current_batch.size >= self.batch_max_size

        def expired_by_time():
            return self.current_batch.age >= self.batch_max_age

        return expired_by_count() or expired_by_size() or expired_by_time()

    def accumulate_current_batch(self):
        if self.current_batch.length > 0:
            self.current_batch.save(
                directory=ACCUMULATED_PATH, filename=self.current_batch.get_filename_by_created_date())
            self.current_batch.reset()

    def write_changes_to_current_batch(self):
        self.current_batch_hash = self.current_batch.hash()
        if self.current_batch_hash != self.last_batch_hash:
            self.current_batch.save(
                directory=ROOT_PATH,
                filename='current.pbt'
            )
            self.last_batch_hash = self.current_batch.hash()

    def get_accumulated_batches(self):
        return [Batch(filename='%s/%s' % (ACCUMULATED_PATH, file))
                for file in os.listdir(ACCUMULATED_PATH) if file.endswith('.pbt')]

    def recover_from_failures(self, batch, failures):
        if failures['falhas']['total'] > 0:
            failed_ids = [Operation.from_json(
                item).id for item in failures['falhas']['itens']]
            failed_operations = [Operation.from_json(operation) for operation in batch.operations
                                 if next((failed_id for failed_id in failed_ids
                                          if failed_id == Operation.from_json(operation).id
                                          ), False)]
            prioritized_batch = Batch(
                operations=failed_operations,
                high_priority=True
            )
            prioritized_batch.save(directory=ACCUMULATED_PATH)

    def save(self, model, assinante_id=None):
        if self.multitenancy and assinante_id is None:
            raise ValueError('assinante_id e requerido no modo multitenancy')
        model.validate()
        operation = Update.from_model(model, assinante_id if assinante_id else self.assinante_id)
        self.current_batch.remove(operation).append(operation)

    def delete(self, model, assinante_id=None):
        if self.multitenancy and assinante_id is None:
            raise ValueError('assinante_id e requerido no modo multitenancy')
        if hasattr(model, 'id'):
            self.current_batch.append(Delete.from_model(model, assinante_id if assinante_id else self.assinante_id))
        else:
            raise ValueError('id obrigatorio para exclusao')

    def request_pending_resources(self, start=0, count=100, concat=None):
        result = concat if concat is not None else {}
        response = self.client.get(
            '/stream/pending-resources?start=%d&count=%d' % (start, count))
        count = 0
        if response.status_code == 200:
            data = response.json()
            count = len(data)
            for assinante_id, value in data.items():
                for modelName, ids in value.items():
                    if assinante_id not in result:
                        result[assinante_id] = {}
                    if modelName not in result[assinante_id]:
                        result[assinante_id][modelName] = []
                    result[assinante_id][modelName] = result[assinante_id][modelName] + ids
        else:
            raise DataException('Erro ao buscar recursos pendentes.')
        return (result, count)

    def get_pending_resources(self):
        start = 0
        count = 100
        (pending_resources, count) = self.request_pending_resources()
        while count > 0:
            (pending_resources, count) = self.request_pending_resources(
                start + count,
                count,
                concat=pending_resources
            )
        result = {}
        for assinante_id, value in pending_resources.items():
            if assinante_id not in result:
                result[assinante_id] = []
            for modelName, ids in value.items():
                for id in ids:
                    result[assinante_id].append(model_from_json(modelName, {'id': id}))
        return result

    def flush(self):
        self.accumulate_current_batch()
        self.send_accumulated_batches()


import turtle
t = turtle.Turtle()
t.hideturtle()
t.speed(1)
t.color("blue")
t.penup()
t.goto(0,50)
t.showturtle()
t.pendown()
t.fillcolor("aquamarine")
t.begin_fill()

for i in range(36):
    t.fd(10)
    t.rt(10)
t.end_fill()
t.hideturtle()
turtle.done()

Python - Beginner/lesson 8 circle - youwen.py


import interpolation
from matplotlib import pyplot as plt
import numpy as np
from load_foil import *

x3_known = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
y3_knwon = [0, 0.001, 0.008, 0.027, 0.064, 0.125, 0.216, 0.343, 0.512, 0.729, 1]
spline_values = interpolation.spline(x3_known, y3_knwon, 11, 0, 3)

## Plot the interpolation of x^3
def x3_interpolation():
    x_abs = np.linspace(0, 1, 100)
    y_ord = []

    for i in range(len(x_abs)):
        y_ord.append(interpolation.splint(x3_known, y3_knwon, spline_values, 11, x_abs[i]))

    plt.plot(x_abs, y_ord)
    plt.show()

## Plot the error curve:
def x3_error():
    x_abs = np.linspace(0, 1, 1000)
    error = []

    for i in range(len(x_abs)):
        error.append(np.linalg.norm(interpolation.splint(x3_known, y3_knwon, spline_values, 11, x_abs[i])-pow(x_abs[i], 3))/np.linalg.norm(pow(x_abs[i], 3)))

    plt.plot(x_abs, error)
    plt.yscale('log')
    plt.grid(True,which="both")
    plt.xlabel(r"x")
    plt.ylabel(r"Error")

    plt.show()

## Plot the error in fuction of the number of known points:
def error_num_points():
    errors = []
    for i in range(5, 100):
        x_tested = np.linspace(0, 1, 10*i, endpoint=False)
        error = []
        x_known = np.linspace(0, 1, i, endpoint=False)
        y_known = [pow(x, 3) for x in x_known]
        spline_values3 = interpolation.spline(x_known, y_known, len(x_known), 0, 3)

        for j in range(len(x_tested)):
            error.append(abs(interpolation.splint(x_known, y_known, spline_values3, len(x_known), x_tested[j])-pow(x_tested[j], 3)))

        errors.append(max(error))

    plt.plot(range(5, 100), errors)
    plt.yscale('log')
    plt.grid(True,which="both")
    plt.xlabel(r"Point number")
    plt.ylabel(r"Error")

    plt.show()


import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings.production")

workers = 2
# umask = "0o111"
wsgi_app = "website.wsgi:application"
user = "myke"

LOG_DIR = os.environ["MF_LOG_DIR"]
accesslog = os.path.join(LOG_DIR, "gunicorn.log")
errorlog = os.path.join(LOG_DIR, "gunicorn.error.log")

socket_path = "/tmp/gunicorn-martinfarms.sock"
bind = f"unix:{socket_path}"

# capture console output
capture_output=True


#!/usr/bin/env python3
# encoding: utf-8
"""
pysdd-cli
~~~~~~~~~

PySDD command line interface.

:author: Wannes Meert, Arthur Choi
:copyright: Copyright 2019 KU Leuven and Regents of the University of California.
:license: Apache License, Version 2.0, see LICENSE for details.
"""
from pathlib import Path
import sys
import time
import argparse
import logging
from pysdd.sdd import SddManager, Vtree, Fnf, CompilerOptions

logger = logging.getLogger(__name__)

def main(argv=None):
    options, args = getopt(argv)

    if options.cnf_filename is not None:
        print("creating manager...")
        sdd, _ = SddManager.from_cnf_file(bytes(options.cnf_filename))

        root = sdd.root

        # Model Counting
        wmc = root.wmc(log_mode=False)
        wmc.propagate()

        weights = read_weights(bytes(options.cnf_filename))
        print("Weights size: " + str(len(weights)))

        literals = [sdd.literal(i) for i in range(1, sdd.var_count()+1)]

        print("Number of literals: " + str(len(literals)))

        # Set weights for all literals
        for i in range(1, len(literals)+1):
            wmc.set_literal_weight(i, weights[(i-1)*2])  # Positive literal weight
            wmc.set_literal_weight(-i, weights[(i-1)*2+1])  # Negative literal weight

        w = wmc.propagate()

        print("Weighted model count: " + str(w))
        #
        # for i in range(1, sdd.var_count()+1):
        #     print(str(i) + ": " + str(wmc.literal_weight(i)))
        #     print(str(-i) + ": " + str(wmc.literal_weight(-i)))

        # print("Model count: " + str(sdd.model_count(root)))

        # for i in range(1, sdd.var_count() + 1):
        #     print(str(i-1) + ": " + str(wmc.literal_pr(i)))

        # Weighted Model Counting

        wmc.set_literal_weight(literals[29], 0)  # Positive literal weight
        # wmc.set_literal_weight(-literals[29], 0)  # Negative literal weight

        # wmc.set_literal_weight(literals[32], 0)  # Positive literal weight
        wmc.set_literal_weight(-literals[32], 0)  # Negative literal weight
        #
        # wmc.set_literal_weight(literals[40], 0)  # Positive literal weight
        wmc.set_literal_weight(-literals[40], 0)  # Negative literal weight

        # for i in range(1, sdd.var_count()+1):
        #     print(str(i) + ": " + str(wmc.literal_weight(i)))
        #     print(str(-i) + ": " + str(wmc.literal_weight(-i)))

        w = wmc.propagate()

        for i in range(1, sdd.var_count() + 1):
            print(str(i) + ": " + str(wmc.literal_pr(i)))

        print("Weighted model count: " + str(w))

        print("8: " + str(wmc.literal_pr(8)))

def read_weights(nnf_path):
    """
    Format: c weights PW_1 NW_1 ... PW_n NW_n
    :param nnf_path: Path to NNF file
    :return: list of weights
    """
    weight_str = None
    with open(nnf_path, "r") as ifile:
        for line in ifile.readlines():
            if "c weights " in line:
                weight_str = line[10:].strip()
                break
    if weight_str is None:
        return None
    weight_strs = weight_str.split(" ")
    weights = [float(w) for w in weight_strs]
    return weights

def create_wmc(node, weights):
    if weights is None:
        return None
    wmc = node.wmc(False)
    for i in range(len(weights)):
        lit = (i // 2) + 1
        if (i % 2) == 1:
            lit = -lit
        w = weights[i]
        wmc.set_literal_weight(node.manager.literal(lit), w)
    return wmc

class CustomHelpFormatter(argparse.HelpFormatter):

    def _format_text(self, text):
        text = super()._format_text(text)
        if "Copyright" in text:
            a, b = text.split("Copyright")
            text = a + "\n\n" + super()._format_text("Copyright" + b)
        return text

def create_parser():
    def bytes_path(p):
        return bytes(Path(p))

    def bytes_str(s):
        return s.encode()

    epilog = ("Weighted Model Counting is performed if the NNF file containts a line formatted as follows: "
              "\"c weights PW_1 NW_1 ... PW_n NW_n\"."
              "Copyright 2017-2019, Regents of the University of California and KU Leuven")
    parser = argparse.ArgumentParser(description='Sentential Decision Diagram, Compiler',
                                     epilog=epilog,
                                     formatter_class=CustomHelpFormatter)
    input_group = parser.add_mutually_exclusive_group()
    input_group.add_argument('-c', metavar='FILE', type=bytes_path,
                             dest='cnf_filename', help='set input CNF file')
    input_group.add_argument('-d', metavar='FILE', type=bytes_path,
                             dest='dnf_filename', help='set input DNF file')
    input_group.add_argument('-s', metavar='FILE', type=bytes_path,
                             dest='sdd_filename', help='set input SDD file')
    parser.add_argument('-v', metavar='FILE', type=bytes_path,
                        dest='vtree_filename', help='set input VTREE file')

    parser.add_argument('-W', metavar='FILE', type=bytes_path,
                        dest='output_vtree_filename', help='set output VTREE file')
    parser.add_argument('-V', metavar='FILE', type=bytes_path,
                        dest='output_vtree_dot_filename', help='set output VTREE (dot) file')
    parser.add_argument('-R', metavar='FILE', type=bytes_path,
                        dest='output_sdd_filename', help='set output SDD file')
    parser.add_argument('-S', metavar='FILE', type=bytes_path,
                        dest='output_sdd_dot_filename', help='set output SDD (dot) file')

    parser.add_argument('-m', action='store_true',
                        dest='minimize_cardinality', help='minimize the cardinality of compiled sdd')

    parser.add_argument('-t', metavar='TYPE', type=bytes_str, default='balanced',
                        choices=[b'left', b'right', b'vertical', b'balanced', b'random'],
                        dest='initial_vtree_type',
                        help='set initial vtree type (left/right/vertical/balanced/random)')

    parser.add_argument('-r', metavar='K', type=int, default=-1,
                        dest='vtree_search_mode',
                        help='if K>0: invoke vtree search every K clauses. If K=0: disable vtree search. ' +
                             'By default (no -r option), dynamic vtree search is enabled')

    parser.add_argument('-q', action='store_true',
                        dest='post_search', help='perform post-compilation vtree search')

    parser.add_argument('-p', action='store_true',
                        dest='verbose', help='verbose output')

    parser.add_argument('--log_mode', action='store_true',
                        dest='log_mode', help='weights in log')

    return parser

def getopt(argv=None):
    parser = create_parser()
    args = parser.parse_args(argv)

    if args.verbose:
        logger.setLevel(logging.INFO)
    else:
        logger.setLevel(logging.WARNING)
    logger.addHandler(logging.StreamHandler(sys.stdout))

    options = CompilerOptions(cnf_filename=args.cnf_filename,
                              dnf_filename=args.dnf_filename,
                              vtree_filename=args.vtree_filename,
                              sdd_filename=args.sdd_filename,
                              output_vtree_filename=args.output_vtree_filename,
                              output_vtree_dot_filename=args.output_vtree_dot_filename,
                              output_sdd_filename=args.output_sdd_filename,
                              output_sdd_dot_filename=args.output_sdd_dot_filename,
                              initial_vtree_type=args.initial_vtree_type,
                              minimize_cardinality=args.minimize_cardinality,
                              vtree_search_mode=args.vtree_search_mode,
                              post_search=args.post_search,
                              verbose=args.verbose)
    # print(str(options))
    return options, args


#!/usr/bin/env python3
########################################################################
# Filename    : MPU6050RAW.py
# Description : Read the Raw data of MPU6050.
# Author      : www.quadstore.in
# modification: 2018/08/03
########################################################################
import MPU6050
import time

mpu = MPU6050.MPU6050()     #instantiate a MPU6050 class object
accel = [0]*3               #store accelerometer data
gyro = [0]*3                #store gyroscope data
def setup():
    mpu.dmp_initialize()    #initialize MPU6050

def loop():
    while(True):
        accel = mpu.get_acceleration()      #get accelerometer data
        gyro = mpu.get_rotation()           #get gyroscope data
        print("a/g:%d\t%d\t%d\t%d\t%d\t%d "%(accel[0],accel[1],accel[2],gyro[0],gyro[1],gyro[2]))
        print("a/g:%.2f g\t%.2f g\t%.2f g\t%.2f d/s\t%.2f d/s\t%.2f d/s"%(accel[0]/16384.0,accel[1]/16384.0,
            accel[2]/16384.0,gyro[0]/131.0,gyro[1]/131.0,gyro[2]/131.0))
        time.sleep(0.1)

if __name__ == '__main__':     # Program start from here
    print("Program is starting ... ")
    setup()
    try:
        loop()
    except KeyboardInterrupt:  # When 'Ctrl+C' is pressed,the program will exit.
        pass


import pygame
import random
from defs import *

class Bird():
    def __init__(self, gameDisplay): #initialize bird and its features
        self.gameDisplay = gameDisplay
        self.state = BIRD_ALIVE #Bird starts alive
        self.img = pygame.image.load(BIRD_FILENAME) #Load image of bird
        self.rect = self.img.get_rect() #Is used to find the position of bird
        self.speed = 0 #start with 0 speed
        self.time_lived = 0 #start with no time lived (This is for the AI to see if its doing well
        self.set_position(BIRD_START_X, BIRD_START_Y) #Startposition

    def set_position(self, x, y):
        self.rect.centerx = x
        self.rect.centery = y

    def move(self, dt): #When moving
        distance = 0 #empty distance
        new_speed = 0 #empty speed

        distance = (self.speed * dt) + (0.5 * GRAVITY * dt * dt) #s = ut + 0.5at^2
        new_speed = self.speed + (GRAVITY * dt) #v = u + at

        self.rect.centery += distance #Set the position of the bird on the y axis
        self.speed = new_speed #Set speed of the bird

        if self.rect.top < 0: #If the bird goes above the screen
            self.rect.top = 0 #stay in screen
            self.speed = 0 #set speed to 0

    def jump(self):
        self.speed = BIRD_START_SPEED #If jump is used, set speed again

    def draw(self):
        self.gameDisplay.blit(self.img, self.rect) #Draw every frame

    def check_status(self, pipes): #Check if the bird still lives
        if self.rect.bottom > DISPLAY_H: #If it is below the screen
            self.state = BIRD_DEAD
        else: #if not
            self.check_hits(pipes) #check if it hit with the pipes

    def check_hits(self, pipes):
        for p in pipes: #for every pipe in the list
            if p.rect.colliderect(self.rect): #When the bird collides with a pipe
                self.state = BIRD_DEAD
                break

    def update(self, dt, pipes):
        if self.state == BIRD_ALIVE: #if alive, call all the actions below
            self.time_lived += dt
            self.move(dt)
            self.draw()
            self.check_status(pipes)

class BirdCollection():
    def __init__(self, gameDisplay):
        self.gameDisplay = gameDisplay
        self.birds = []
        self.create_new_generation()

    def create_new_generation(self):
        self.birds = []
        for i in range(0, GENERATION_SIZE):
            self.birds.append(Bird(self.gameDisplay))

    def update(self, dt, pipes):
        num_alive = 0
        for b in self.birds:
            if random.randint(0,4) == 1:
                b.jump()
            b.update(dt,pipes)
            if b.state == BIRD_ALIVE:
                num_alive += 1

        return num_alive


# Constante variabelen (= worden niet gewijzigd als de code wordt uitgevoerd!)
PERC = 0.1
PERC_EX = 0.25
SINGLE_LIM = 32000.0
GEHUWD_LIM = 64000.0

# Vraagt de gebruiker naar inkomen en burgelijke staat:
bs = input("Vul 's' in voor single, 'g' voor gehuwd: ")
inkomen = int(input("Vul uw inkomen in: "))

#Bereken belastingen
belas = 0.0
belas_ex = 0.0

if bs == "s":
    if inkomen <= SINGLE_LIM:
        belas = inkomen * PERC
    else:
        belas = SINGLE_LIM * PERC
        belas_ex = (inkomen -SINGLE_LIM) * PERC_EX
else:
    if inkomen <= GEHUWD_LIM:
        belas = inkomen * PERC
    else:
        belas = GEHUWD_LIM * PERC
        belas_ex = (inkomen - GEHUWD_LIM) * PERC_EX

totaal_belas = belas + belas_ex
print("U moet", totaal_belas, "aan de staat.")


def solution(operations):
    answer = []
    operationslist=[] #숫자를 넣어주고 빼줄 리스트 하나 생성
    for i in range(len(operations)):
        operation=operations[i].split(' ')#operation을 그냥 operations[i][0]이런식으로 진행할려니 -가 붙을시 하나씩 늘어나는것이 힘들어서 split해주었다
        if operation[0] == 'I':
            operationslist.append(int(operation[1]))
        elif operationslist:
            if operations[i] == 'D -1':#전체를 보는것이 더 편한듯 해서 그냥 operations[i]로 해주었다
                operationslist.remove(min(operationslist))#-1이기 때문에 최소값제거
            else:
                operationslist.remove(max(operationslist))#아닌 경우는 D 1밖에 없기 때문에 최대값 제거
        else:
            continue
    if not operationslist: #위에 정돈된 리스트가 비었을시 0,0을 answer에 입력
        answer =[0,0]
    else:
        answer = [max(operationslist),min(operationslist)] #아닌경우 max와 min을 찾아서 정렬해준다
    return answer