"""Solar radiation and energy balance related functions"""
from geeet.common import is_img, is_eenum

def std_meridian(longitude=None):
    '''
    Get the closest 15-degree meridian for a given Longitude
    For a numpy array output, longitude is a required input.
    For an ee.Image output, longitude is an optional input.
    '''
    import numpy as np

    if longitude is None:
        from ee import Image
        lonlat_img = Image.pixelLonLat()
        longitude = lonlat_img.select('longitude')

    if is_img(longitude):
        stdMerid = longitude.add(187.5).divide(15).int().multiply(15).subtract(180)
    else:
        longitude = np.array(longitude)
        stdMerid = (((longitude + 187.5)/15).astype(int))*15-180

    return stdMerid

def eqn_time(doy):
    '''
    Function to calculate the equation of time, in hours
    Input: doy (np.array or ee.Number)
    Output: eot (np.array or ee.Number; matches the input type)
    '''
    import numpy as np
    DTOR = np.deg2rad(1) # constant to convert degrees to radians
    # Compute the value of the equation of time in hours eq
    if is_eenum(doy):
        f = doy.multiply(0.9856).add(279.575).multiply(DTOR)
        sinf = f.sin()
        sin2f = f.multiply(2).sin()
        sin3f = f.multiply(3).sin()
        sin4f = f.multiply(4).sin()
        cosf = f.cos()
        cos2f = f.multiply(2).cos()
        cos3f = f.multiply(3).cos()
        sin_term = sinf.multiply(-104.7).add(sin2f.multiply(596.2)).add(sin3f.multiply(4.3)).add(sin4f.multiply(-12.7))
        cos_term = cosf.multiply(-429.3).add(cos2f.multiply(-2.0)).add(cos3f.multiply(19.3))
        eot = sin_term.add(cos_term).divide(3600.0)
    else:
        f = (279.575 + 0.9856*doy)*DTOR
        eot = (-104.7*np.sin(f) + 596.2*np.sin(2*f) + 4.3*np.sin(3*f) - 12.7*np.sin(4*f) - 429.3*np.cos(f) - 2.0*np.cos(2*f) + 19.3*np.cos(3*f))/3600.0
    return eot

def compute_tnoon(doy, Lon = None, band_name = None):
    '''
    Function to compute the solar noon time in decimal hours.
    (Not accounting for daylight savings)
    Inputs:
        - doy (numpy array or ee.Number): the day of the year.
        - Lon* (numpy array or ee.Image): the pixel longitudes.

    *For a numpy array output, longitude is a required input;
     for an ee.Image output, longitude is an optional input.
    Outputs:
        - T_noon (numpy array or ee.Image): the solar noon.
    References
    ----------
    Campbell and Norman, 1998
    '''

    import numpy as np
    from geeet.common import is_img

    if Lon is None:
        from ee import Image
        lonlat_img = Image.pixelLonLat()
        Lon = lonlat_img.select('longitude')

    Std_meridian = std_meridian(Lon)

    equation_time = eqn_time(doy)

    if is_img(Lon):
        from ee import Image
        LC = (Lon.subtract(Std_meridian)).multiply(4).divide(60)
        T_noon = Image(12.0).subtract(LC).subtract(equation_time)
        if band_name:
            T_noon = T_noon.rename(band_name)
    else:
        # Compute the time of solar noon eq (11.3)
        LC = (4*(Lon - Std_meridian))/60.0 # correction in hours
        T_noon = 12.0 - LC - equation_time

    return T_noon

def compute_solar_declination(doy):
    """
    Function to compute the solar declination angle for a given day of year
    Input: doy (np.array or ee.Number)
    Output: solar_declination (np.array or ee.Number; matches the input type) in radians
    """
    import numpy as np
    DTOR = np.deg2rad(1) # constant to convert degrees to radians
    if is_eenum(doy):
        from ee import Number
        doy_scaled = doy.multiply(0.9856)
        sin1 = doy_scaled.add(356.6).multiply(DTOR).sin()
        sin2 = sin1.multiply(1.9165).add(doy_scaled).add(278.97).multiply(DTOR).sin()
        sin3 = Number(np.sin(23.45*DTOR))
        solar_declination = sin2.multiply(sin3).asin()
    else:
        solar_declination = np.arcsin(np.sin(23.45*DTOR)*np.sin(DTOR*(278.97 + 0.9856*doy + 1.9165*np.sin((356.6 + 0.9856*doy)*DTOR))))
    return solar_declination

def compute_solar_angles(doy = None, time = None, longitude = None, latitude = None):
    '''
    Function to compute the sun Zenith and Azimuth angles in degrees
    Inputs:
        - doy (ee.Number or numpy array): day of year
        - time (ee.Number or numpy array): time of measurement (decimal hours, local)
        - longitude (ee.Number or numpy array): only required if doy is numpy array.
        - latitude (ee.Number or numpy array): only required if doy is numpy array.
    Outputs:
        - solar_angles (tuple or ee.Image): tuple containing numpy arrays with the following
                components, or ee.Image containing the following bands:
            - zenith: (degrees)
            - azimuth: (degrees)
    '''
    import numpy as np
    from geeet.common import is_eenum

    DTOR = np.pi/180.0 # constant to convert degrees to radians
    RTOD = 180.0/np.pi # constant to convert radians to degrees

    if is_eenum(doy):
        from ee import Image, Algorithms
        t_noon = compute_tnoon(doy)
    else:
        t_noon = compute_tnoon(doy, longitude)

    # Estimate solar declination in radians
    solar_declination = compute_solar_declination(doy) # in radians; ee.Number or np.array
      # tnoon = Local time when Apparent solar time (AST) is noon
    # tnoon = 12 - EOT - LC  where LC is longitude correction = (4/60)*(Lon - Std meridian)
    # AST = Local time + EOT + LC
    # 12 = tnoon + EOT + LC
    # 12 - tnoon = EOT + LC
    # So we can get EOT + LC from tnoon
    # and then apply it to get AST
    # AST  = Local time + 12 - tnoon

    if is_eenum(doy):
        AST = Image(time.add(12)).subtract(t_noon)
        hour_angle = AST.subtract(12).multiply(15).multiply(DTOR)
        cos_hour_angle = hour_angle.cos()

        sin_solar = Image(solar_declination).sin()
        cos_solar = Image(solar_declination).cos()
        lonlat_img = Image.pixelLonLat()
        latitude = lonlat_img.select('latitude')

        lat_rad = latitude.multiply(DTOR)
        sin_lat = lat_rad.sin()
        cos_lat = lat_rad.cos()
        sin_term = sin_solar.multiply(sin_lat)

        cos_term = cos_hour_angle.multiply(cos_lat).multiply(cos_solar)
        cos_zenith = sin_term.add(cos_term)
        zenith = cos_zenith.acos().multiply(RTOD)

        sin_zenith = zenith.multiply(DTOR).sin()

        cos_azimuth = sin_lat.multiply(cos_zenith).subtract(sin_solar)
        cos_azimuth = cos_azimuth.divide(cos_lat.multiply(sin_zenith))
        azimuth = cos_azimuth.acos().multiply(RTOD)

        azimuth = Algorithms.If(hour_angle.lt(0), azimuth.add(180).mod(360),
        Image(540).subtract(azimuth).mod(360))

        solar_angles = zenith.addBands(azimuth).rename(['zenith', 'azimuth'])

    else:
        # Apparent solar time : AST
        AST = time + 12 - t_noon
        # Hour angle is (AST-12)*15  (if AST is 12 the hour angle is 0deg)
        hour_angle = (AST-12)*15
        # Solar zenith angle
        # cos(Zenith) = sin(Lat)sin(declination)  + cos(Lat)cos(declination)cos(hour angle)
        cos_zenith = np.sin(latitude*DTOR)*np.sin(solar_declination) + \
            np.cos(latitude*DTOR)*np.cos(solar_declination)*np.cos(hour_angle*DTOR)
        zenith = np.arccos(cos_zenith)*RTOD
        # Solar azimuth angle
        # cos(Azimuth) = sin(lat)*cos(zenith) - sin(declination) / (cos(lat)*sin(zenith))
        cos_azimuth = np.sin(latitude*DTOR)*cos_zenith - np.sin(solar_declination)
        cos_azimuth = cos_azimuth / (np.cos(latitude*DTOR)*np.sin(zenith*DTOR))
        azimuth = np.arccos(cos_azimuth)*RTOD
        if hour_angle>0:
            azimuth = (azimuth+180)%360
        else:
            azimuth = (540-azimuth)%360
        solar_angles = [zenith, azimuth]

    return solar_angles

def compute_sunset_sunrise(img = None, doy = None, longitude = None, latitude = None):
    '''
    Function to compute the sunset and sunrise times
    Inputs:
        - img (ee.Image) with the following bands or properties:
            - doy           (property) : day of year
            - longitude     (band)
            - latitude      (band)
        or the following numpy arrays as keywords:
            - doy: day of year
            - longitude
            - latitude

    Outputs:
        - solar_times (list or ee.Image): list containing numpy arrays with the following
                components, or ee.Image containing the following bands:
            - t_rise: time of sunrise (decimal time)
            - t_end:  time of sunset (decimal time)
    '''
    import numpy as np

    DTOR = np.deg2rad(1) # constant to convert degrees to radians
    RTOD = np.rad2deg(1) # constant to convert radians to degrees

    if is_img(img):
        from ee import Number, Image
        doy = Number(img.get('doy'))
        t_noon = compute_tnoon(doy)
        Lat = img.select('latitude')
        # Estimate solar declination in radians
        solar_declination = compute_solar_declination(doy)
        lat_rad = Lat.multiply(DTOR)
        sin_lat = lat_rad.sin()
        cos_lat = lat_rad.cos()

        sin_solar = Image(solar_declination).sin()
        cos_solar = Image(solar_declination).cos()

        sin_term = sin_solar.multiply(sin_lat)

        # Halfday length considering twilight
        # (using a zenitgh angle of the sun set to 96 degrees)
        cos_zs96 = Image(96*DTOR).cos()
        acos_zs96 = cos_zs96.subtract(sin_term).acos()
        halfday = acos_zs96.divide(cos_lat.multiply(cos_solar))
        halfday_h = halfday.multiply(RTOD).divide(15.0)  # in hours

        # Sunrise and sunset times
        t_rise = t_noon.subtract(halfday_h)
        t_end = t_noon.add(halfday_h)
        solar_times = t_rise.addBands(t_end)
        solar_times = solar_times.rename(['t_rise','t_end'])
    else:
        t_noon = compute_tnoon(doy, longitude)
        solar_declination = compute_solar_declination(doy)
        # Compute the halfday length considering twilight (set zs = 96 degrees) eq (11.6)
        halfday = np.arccos((np.cos(96*DTOR)-np.sin(latitude*DTOR)*np.sin(solar_declination))/(np.cos(latitude*DTOR)*np.cos(solar_declination)))
        halfday_h = halfday*RTOD/15.0 # converting to hours
        # Compute sunrise and sunset time eq (11.7)
        t_rise = t_noon - halfday_h
        t_end = t_noon + halfday_h
        solar_times = [t_rise, t_end]
    return solar_times

def rad_ratio(img=None, doy=None, time = None, longitude=None, latitude=None):
    '''
    Compute Jackson irradiance model (ratio of instantaneous radiation to daily radiation)
        Inputs:
        - img (ee.Image) with the following parameters:
            - doy (day of year)
            - time (time of observation)
        or
        the following numpy arrays as keyword arguments:
        doy (day of year)
        time (time of observation)
        longitude
        latitude

        *The ee.Image should contain the property "system:time_start"
        see https://developers.google.com/earth-engine/apidocs/ee-image-date
        and a time of observation property "time" in hours (local)
    Outputs:
       - Rs_ratio (numpy dstack or ee.Image): the computed ratio of instantaneous radiation to daily radiation
    '''
    import numpy as np

    if is_img(img):
        from ee import Image, Number
        doy = Number(img.get('doy'))
        lonlat_img = Image.pixelLonLat().set({'doy': doy})
        Time = Number(img.get('time'))  # time in hours (local time)
        solar_times = compute_sunset_sunrise(lonlat_img)
        sunrise_time = solar_times.select('t_rise').multiply(3600)
        sunset_time = solar_times.select('t_end').multiply(3600)
        sun_seconds = sunset_time.subtract(sunrise_time)
        sun_obs = Image(Time.multiply(3600)).subtract(sunrise_time)
        denom = (sun_obs.divide(sun_seconds).multiply(np.pi).sin()).multiply(np.pi*1E6)
        Rs_ratio = sun_seconds.multiply(2).divide(denom)
        Rs_ratio = Rs_ratio.divide(2.45)  # Convert from MJ/m2day to mm/day
    else:
        solar_times = compute_sunset_sunrise(doy=doy, longitude=longitude, latitude=latitude)
        sunrise_time = solar_times[0]*3600
        sunset_time = solar_times[1]*3600
        N = sunset_time - sunrise_time
        t = time*3600 - sunrise_time
        Rs_ratio = 2*N/((10 ** 6) * np.pi * np.sin(np.pi * t/N))
        Rs_ratio = Rs_ratio/2.45 # Convert to mm/day
    return Rs_ratio

def compute_g(doy, time, Rns, longitude = None, G_params = [0.31, 74000, 10800]):
    '''
    Function to compute the soil heat flux.
    Inputs:
        - doy (numpy array or ee.Number): the observation day (day of year)
        - time (numpy array or ee.Number): the observation local time in decimal hours.
        - Rns (numpy array or ee.Image): the net radiation to the soil.
    Optional_Inptus:
        - list or ee.List [float A, float B, float C] G_Params: the parameters for
          computing soil heat flux where A is the maximum ratio of G/Rns
          B reduces deviation of G/Rn to measured values, also thought of
          as the spread of the cosine wave and C is the phase shift between
          the peaks of Rns and G. B and C are in seconds.
        - longitude (numpy array): only required if Rns is a numpy array and not an ee.Image
    Outputs:
        - G (numpy array or ee.Image): the soil heat flux.
    References
    ----------
    Santanello and Friedl, 2003
    '''
    from geeet.common import is_img
    import numpy as np

    if is_img(Rns):
        from ee import Image, List, Number
        time = Number(time)
        doy = Number(doy)
        t_noon = compute_tnoon(doy)  # we ignore longitude,
        # and this way we make sure t_noon is cast as an ee.Image
        G_params = List(G_params)   # we make it a ee.List
        a = Number(G_params.get(0))
        b = Number(G_params.get(1))
        c = Number(G_params.get(2))
        t_g0 = Image(time).subtract(t_noon).multiply(3600.0)
        cos_term = t_g0.add(c).multiply(2.0*np.pi).divide(b)
        G = cos_term.cos().multiply(Rns).multiply(a).rename('soil_heat_flux')
    else:
        t_noon = compute_tnoon(doy, longitude) # longitude required for numpy array version.
        a = G_params[0]
        b = G_params[1]
        c = G_params[2]
        t_g0 = (time-t_noon)*3600.0
        cos_term = np.cos(2.0*np.pi*(t_g0+c)/b)
        G = a*cos_term*Rns
    return G

def compute_Rn(Sdn, Ldn, Albedo, Tr_K, fc, EmisVeg = 0.98, EmisGrd = 0.93):
    """
    Compute the net radiation using three components:
    (1) (1-albedo)*Sdn  where Sdn is the shortwave (solar) downwelling radiation
    (2) Ldn             where Ldn is the longwave (thermal) downwelling radiation
    (3) -eps*sigma*Tr^4 where eps is the emissivity of the surface,
                        sigma is the Steffan-Boltzman constant,
                        and Tr is the surface temperature.
    (1) and (3) as in Zhuang and Wu, 2015 (eqn 10), where
    the emissivity of the surface is calculated as:
    eps = fc Eveg + (1-fc)*Egrd  where Eveg and Egrd are the emissivity of vegetation
    and ground (default values as given above) and fc is the fractional vegetation cover.

    Inputs:
        - Sdn (numpy array or ee.Image): Shortwave (solar) downwelling radiation (W/m2)
        - Ldn (numpy array or ee.Image): Longwave (thermal) downwelling radiation (W/m2)
        - Albedo (numpy array or ee.Image): Albedo of the surface
        - Tr_K (numpy array or ee.Image): Surface temperature, in Kelvin
        - fc (numpy array or ee.Image): Fractional vegetation cover
    Outputs:
        - Rn (numpy array or ee.Image): Net radiation (W/m2).
    References
    ----------
    Zhuang, Q.; Wu, B. Estimating Evapotranspiration from an Improved Two-Source Energy
    Balance Model Using ASTER Satellite Imagery. Water 2015, 7, 6673-6688.
    https://doi.org/10.3390/w7126653
    """
    sb = 5.670373e-8 # Steffan-Boltzman constant, in W⋅m−2⋅K−4
    import numpy as np
    if is_img(Sdn):
        from ee import Image
        Rn_short = (Image(1).subtract(Albedo)).multiply(Sdn)
        EmisSurf = (fc.multiply(EmisVeg)).add((Image(1).subtract(fc)).multiply(EmisGrd))
        Rn_long = Ldn.subtract(EmisSurf.multiply(sb).multiply(Tr_K.pow(4)))
        Rn = Rn_short.add(Rn_long)
    else:
        EmisSurf = (fc*EmisVeg + (1-fc)*EmisGrd)
        Rn = (1 - Albedo)*Sdn + Ldn - EmisSurf* sb * Tr_K ** 4
        Rn = np.array(Rn)
    return Rn


# -*- coding: utf-8 -*-
import os
import time
import logging

from yobit_api import api

main_cfg = """currency1:
currency2:btc
api_key:
secret_key:
lt:1
"""
nonce_cfg = "0"
cfgs_lst = [main_cfg, nonce_cfg]

logging.basicConfig(filename='coin_sell.log', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

class CoinSell(object):
    def __init__(self):
        self.main_cfg = os.path.join(os.getcwd(), 'getme.cfg')
        self.nonce_cfg = os.path.join(os.getcwd(), 'nonce.cfg')
        self.public = api.PublicApi
        self.trade = api.TradeApi

    @staticmethod
    def files_exists(*args):
        """
        Method which check configs on current directory , if not exist - create them.
        :param args: configs
        :return:
        """
        for num, arg in enumerate(args):
            if os.path.isfile(arg) is False:
                with open(arg, 'w') as file:
                    file.write(cfgs_lst[num].format(1))

    def get_data_from_cfg(self):
        """
        Method which read main config by line and return data.
        :return:
        """
        with open(self.main_cfg, 'r') as file:
            data_lst = [line.split(':')[1].replace('\n', '') for line in file]

        return data_lst

    def get_balance(self, api_key, secret_key, main_currency):
        """
        Method which get account balance of main currency , which must be set in getme config file.
        :param api_key:
        :param secret_key:
        :param main_currency:
        :return:
        """
        info = self.trade(key=api_key, secret_key=secret_key).get_info()
        time.sleep(3)

        return float(info['return']['funds'][main_currency])

    def drain_balance(self, bal, main_currency, alt_currency, key, secret_key):
        """
        Method which sell all amount of main currency on pair main_currency/alt_currency.
        :param bal: current balance
        :param main_currency: pair1 in getme.cfg file.
        :param alt_currency: pair2 in getme.cfg file.
        :param key:
        :param secret_key:
        :return:
        """
        pair = f'{main_currency}_{alt_currency}'
        starting_balance = balance = bal
        trade = self.trade(key=key, secret_key=secret_key)

        while balance > 0:
            time.sleep(3)
            last_bid_order = self.public().get_pair_depth(pair, 1)['bids']
            subtrahend = balance if balance < last_bid_order[0][1] else last_bid_order[0][1]

            try:
                order_id = trade.sell(f'{main_currency}_{alt_currency}', last_bid_order[0][0],
                                      subtrahend)['return']['order_id']
            except KeyError:
                raise Exception('The total amount of the transaction is less than the minimum acceptable value.')

            # Check on worked order.
            time.sleep(20)
            active_order = trade.get_active_orders(pair)['success']

            if int(active_order) != 0:
                # Cancel opened order.
                trade.cancel_order(order_id)

            # Get new balance.
            balance = self.get_balance(key, secret_key, main_currency)

        logging.info(f'{starting_balance} {main_currency} was successfully sold.')

    def run(self):
        """
        Method which:
        1. Check configs on exist.
        2. Drain balance of main currency (pair1 in config file).
        :return:
        """
        self.files_exists(self.main_cfg, self.nonce_cfg)                                    # Check on configs exists
        main_currency, alt_currency, api_key, secret_key, lt = self.get_data_from_cfg()     # Get data from config.

        try:
            balance = self.get_balance(api_key, secret_key, main_currency)                  # Get balance.
        except KeyError:
            raise Exception('Non data in config.')

        if balance > float(lt):
            self.drain_balance(balance, main_currency, alt_currency, api_key, secret_key)   # Drain all balance.
        else:
            logging.info(f'Balance of {main_currency} is low than {lt}.')

if __name__ == '__main__':
    CoinSell().run()


#!/opt/storpool/python3/bin/python3

"""
Changes the default boot kernel for the system.
"""

from datetime import datetime
import os
import pathlib
import re
import shutil
import subprocess
import sys
import tempfile

SAFEENC = "Latin-1"

GRUB_DEFAULT_PATH = pathlib.Path("/etc/default/grub")
_BACKUP_TIMESTAMP = datetime.strftime(datetime.now(), "%Y-%m-%d_%H-%M-%S")
GRUB_DEFAULT_BACKUP = f"{GRUB_DEFAULT_PATH}.{_BACKUP_TIMESTAMP}"

GRUB_EFI_BASE = pathlib.Path("/boot/efi/EFI/")
GRUB_CFG_PATHS = [
    pathlib.Path("/boot/grub/grub.cfg"),
    pathlib.Path("/boot/grub2/grub.cfg"),
] + list(GRUB_EFI_BASE.glob("*/grub.cfg"))
BOOT_LOADER_ENTRIES = pathlib.Path("/boot/loader/entries")

GRUB_MKCONFIG_CMDS = ["grub-mkconfig", "grub2-mkconfig"]

GRUB_LINE_FILTER = re.compile(r"^submenu|^menuentry|^\s+menuentry")

def get_grub_menu_title(menu: str) -> str:
    """Get a (sub)menu title out of a grub.conf menu entry."""
    menu_split = menu.split("'")
    if len(menu_split) < 2:
        return ""
    return menu_split[1]

def get_grubcfg_title(cfg_path: pathlib.Path, kernel: str) -> str:
    """
    Parses a grub.cfg and returns the menu and submenu name
    of the desired kernel version in the GRUB menu.
    """
    menu = ""
    submenu = ""

    if not cfg_path.exists():
        return ""

    with open(cfg_path, "r", encoding=SAFEENC) as cfg_file:
        for line in cfg_file.readlines():
            if not GRUB_LINE_FILTER.match(line):
                continue
            line_lower = line.lower()
            if "(recovery mode)" in line_lower or "rescue" in line_lower:
                continue
            line = line.rstrip()

            if line.startswith("menuentry"):
                if kernel in line:
                    menu = get_grub_menu_title(line)
                    break
            elif line.startswith("submenu"):
                menu = get_grub_menu_title(line)
                submenu = ""
                continue
            else:
                if kernel in line:
                    submenu = get_grub_menu_title(line)
                    break

    if not menu:
        return ""
    if not submenu:
        return menu if kernel in menu else ""
    return menu + ">" + submenu

def get_boot_loader_title(kernel: str) -> str:
    """
    Parses /boot/loader/entries files to get the
    bootloader title for the desired kernel.
    """
    title = ""

    if not BOOT_LOADER_ENTRIES.exists():
        return title

    for entry in BOOT_LOADER_ENTRIES.glob(f"*{kernel}*.conf"):
        with open(entry, "r", encoding=SAFEENC) as entry_file:
            for line in entry_file.readlines():
                if not line.startswith("title "):
                    continue
                line = line.rstrip()
                title = line.lstrip("title ")
                break

    return title

def _copy_meta(src: pathlib.Path, dst: pathlib.Path):
    """
    Ensure the destination file has the same owner,
    group, and permissions as the source.
    """
    try:
        src_meta = os.stat(src)
    except OSError:
        return

    try:
        dst_meta = os.stat(dst)
    except OSError as err:
        sys.exit(f"Could not read metadata for {dst}: {err}")

    if dst_meta.st_mode != src_meta.st_mode:
        os.chmod(dst, src_meta.st_mode)

    new_gid, new_uid = -1, -1
    if dst_meta.st_gid != src_meta.st_gid:
        new_gid = src_meta.st_gid
    if dst_meta.st_uid != src_meta.st_uid:
        new_uid = src_meta.st_uid
    if new_gid > -1 or new_uid > -1:
        os.chown(dst, new_uid, new_gid)

def _safe_write(path: pathlib.Path, content: str):
    with tempfile.NamedTemporaryFile(
        mode="w",
        prefix=os.path.basename(path) + ".",
        dir=os.path.dirname(path),
        encoding=SAFEENC,
        delete=False,
    ) as tmpf:
        moved = False
        try:
            tmpf.write(content)
            _copy_meta(path, pathlib.Path(tmpf.name))
            os.rename(tmpf.name, path)
            moved = True
        finally:
            if not moved:
                os.unlink(tmpf.name)
        return moved

def replace_grub_default(title: str) -> bool:
    """
    Replace the GRUB default boot kernel in /etc/default/grub.
    """
    shutil.copy(GRUB_DEFAULT_PATH, GRUB_DEFAULT_BACKUP)
    grub_cfg = ""
    with open(GRUB_DEFAULT_PATH, "r", encoding=SAFEENC) as grub_file:
        for line in grub_file.readlines():
            if line.startswith("GRUB_DEFAULT="):
                line = f'GRUB_DEFAULT="{title}"\n'
            grub_cfg += line

    if not _safe_write(GRUB_DEFAULT_PATH, grub_cfg):
        return False

    grub_mkcfg = next(cmd for cmd in GRUB_MKCONFIG_CMDS if shutil.which(cmd))
    if not grub_mkcfg:
        print(f"Could not find any of the following GRUB tools: {GRUB_MKCONFIG_CMDS}")
        return False
    grub_cfg_path = next(path for path in GRUB_CFG_PATHS if path.exists())
    if not grub_cfg_path:
        print(f"Could not find any of the following GRUB config files: {GRUB_CFG_PATHS}")
        return False

    return subprocess.call([grub_mkcfg, "-o", grub_cfg_path], timeout=120) == 0

def get_kernel_title(kernel: str) -> str:
    """Look for the title of the desired kernel in various locations."""
    kernel_title = ""

    for cfg_path in GRUB_CFG_PATHS:
        kernel_title = get_grubcfg_title(cfg_path, kernel)
        if kernel_title:
            return kernel_title
    kernel_title = get_boot_loader_title(kernel)

    return kernel_title

def main() -> None:
    """
    Find the GRUB title for the desired kernel and
    replace it in the GRUB default configuration.
    """
    if len(sys.argv) != 2:
        sys.exit(
            f"Usage: {sys.argv[0]} <new_kernel_version>\n"
            "Sets the default kernel version to boot from"
        )
    new_kernel = sys.argv[1]
    print(new_kernel)

    kernel_title = get_kernel_title(new_kernel)
    if not kernel_title:
        sys.exit(f"Could not find GRUB kernel title for {new_kernel}, exiting")
    print(f"Found title '{kernel_title}' for kernel '{new_kernel}'")
    if os.getenv("SP_SET_KERNEL_DUMMY"):
        sys.exit(0)

    if not replace_grub_default(kernel_title):
        sys.exit(
            "Could not set new kernel as default, backup of "
            f"'{GRUB_DEFAULT_PATH}' is available at '{GRUB_DEFAULT_BACKUP}'"
        )
    print("GRUB default boot option replaced successfully")

if __name__ == "__main__":
    main()


  #%% 12 - Calculo folha de pagamento

"""
Faça um programa para o cálculo de uma folha de pagamento, sabendo que
os descontos são do Imposto de Renda, que depende do salário bruto
(conforme tabela abaixo) e 3% para o Sindicato e que o FGTS corresponde
a 11% do Salário Bruto, mas não é descontado (é a empresa que deposita).
O Salário Líquido corresponde ao Salário Bruto menos os descontos.
O programa deverá pedir ao usuário o valor da sua hora e a quantidade de
horas trabalhadas no mês.

Desconto do IR:
Salário Bruto até 900 (inclusive) - isento
Salário Bruto até 1500 (inclusive) - desconto de 5%
Salário Bruto até 2500 (inclusive) - desconto de 10%

Salário Bruto acima de 2500 - desconto de 20% Imprima na tela as
informações, dispostas conforme o exemplo abaixo. No exemplo o valor da
hora é 5 e a quantidade de hora é 220.

        Salário Bruto: (5 * 220)        : R$ 1100,00
        (-) IR (5%)                     : R$   55,00
        (-) INSS ( 10%)                 : R$  110,00
        FGTS (11%)                      : R$  121,00
        Total de descontos              : R$  165,00
        Salário Liquido                 : R$  935,00

"""

valor_hora = float(input('Insira valor hora: '))
horas_trab = float(input('Insira horas trabalhadas: '))
salario_antigo = valor_hora*horas_trab

imposto_FGTS = 0.11
imposto_INSS = 0.1

tetos_fgts = [900,1500,2500]
aumentos = [0,0.05,0.1]

imposto_IR = 0.2
for i in range(len(tetos_fgts)):
    if salario_antigo < tetos_fgts[i]:
        imposto_IR = aumentos[i]
        break

desconto_FGTS = imposto_FGTS*salario_antigo
desconto_INSS = imposto_INSS*salario_antigo
desconto_IR = imposto_IR*salario_antigo

total_descontos = desconto_INSS + desconto_IR
salario_liquido = salario_antigo - total_descontos

porc_FGTS = imposto_FGTS*100
porc_INSS = imposto_INSS*100
porc_IR = imposto_IR*100

print(f"""
        Salário Bruto: ({valor_hora} * {horas_trab})        : R$ {salario_antigo}
        (-) IR ({porc_IR}%)                     : R$   {desconto_IR}
        (-) INSS ( {porc_INSS}%)                 : R$  {desconto_INSS}
        FGTS ({porc_FGTS}%)                      : R$  {desconto_FGTS}
        Total de descontos              : R$  {total_descontos}
        Salário Liquido                 : R$  {salario_liquido}
      """)


import sys
import os
import re
import pickle

class Person:
    # Conceptual class for employees
    last = ""
    first = ""
    mi = ""
    pid = ""
    phone = ""

    def __init__(self, last, first, mi, pid, phone):
        # Constructor with all fields assigned
        self.last = last
        self.first = first
        self.mi = mi
        self.pid = pid
        self.phone = phone

    def display(self):
        # Print formatted employee information
        print("Employee ID: " + self.pid)
        print("\t" + self.first + " " + self.mi + ". " + self.last)
        print("\t" + self.phone)

def read_data(file_path):
    # Reads csv file from specified file path, returns file text
    with open(os.path.join(os.getcwd(), file_path), "r") as f:
        text = f.read()
    return text

def process_data(file_text):
    # Processes text data, returns a dictionary of Person objects indexed by pid
    person_dict = {}
    lines = file_text.split("\n")
    lines.remove(lines[0])
    for text in lines:
        person = text.split(",")
        last = person[0].title()
        first = person[1].title()
        if len(person[2]) > 0:
            mi = person[2][0].title()
        else:
            mi = "X"
        pid = person[3]
        while not re.fullmatch("[A-Z]{2}\d{4}", pid):
            print("ID invalid: " + person[3])
            print("ID is two uppercase letters followed by 4 digits")
            pid = input("Please enter a valid ID: ")
        phone = person[4]
        while not re.fullmatch("\d{3}-\d{3}-\d{4}", phone):
            print("Phone " + phone + " is invalid")
            print("Enter phone number in form 123-456-7890")
            phone = input("Enter phone number: ")
        this_person = Person(last, first, mi, pid, phone)
        if person_dict.get(pid):
            print("Error: Duplicate ID")
        else:
            person_dict[pid] = this_person
    return person_dict

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print('Please enter a data file path')
    else:
        filePath = sys.argv[1]
        fileText = read_data(filePath)
        personDict = process_data(fileText)
        pickle.dump(personDict, open("dict.p", "wb"))
        pickleDict = pickle.load(open("dict.p", "rb"))
        print("\nEmployee List: ")
        for entry in pickleDict:
            pickleDict.get(entry).display()


import pandas as pd
from common import *

def zw_original(path):
    data = pd.read_csv(path)
    name_list = get_name_zw()
    sub_data = data[name_list]
    return sub_data

def hw_original(path):
    data = pd.read_csv(path)
    name_list = get_name_hw()
    sub_data = data[name_list]
    return sub_data

def sdmc_original(path):
    data = pd.read_csv(path)
    name_list = get_name_sdmc()
    sub_data = data[name_list]
    return sub_data

def zw_sub_hw(path):
    data = pd.read_csv(path)
    temp_diff = pd.DataFrame()
    for i in np.arange(1, 7):
        name_hw = "ZX_HW{0}_{1}".format(2, i)
        for j in np.arange(1, 7):
            name_zw = "ZX_WD_{0}_{1}".format(i, j)
            temp_diff[name_zw] = data[name_zw] - data[name_hw]
    return temp_diff

def get_temp_mean(path):
    zws = zw_original(path)
    hws = hw_original(path)
    zw_mean = zws.mean(axis=1)
    hw_mean = hws.mean(axis=1)
    d = {'zw_mean': zw_mean,
         'hw_mean': hw_mean}
    df = pd.DataFrame(d)
    return df

def get_temp_sdmc_mean(path):
    zws = zw_original(path)
    hws = hw_original(path)
    sdmcs = sdmc_original(path)
    zw_mean = zws.mean(axis=1)
    hw_mean = hws.mean(axis=1)
    sdmc_mean = sdmcs.mean(axis=1)
    d = {'zw_mean': zw_mean,
         'hw_mean': hw_mean,
         'sdmc_mean': sdmc_mean}
    df = pd.DataFrame(d)
    return df

def get_piece_corr_segment(data, win):
    start = 0
    end = start + win
    corr_value = []
    while end < len(data):
        sub = data.loc[start:end,:]
        corr_value.append(abs(sub.corr()).sum().sum()/data.shape[1])
        end += win
        start += win
    return corr_value

def get_piece_corr_rolling(data, win):
    start = 0
    end = start + win
    corr_value = []
    while end<len(data):
        sub = data.loc[start:end,:]
        corr_value.append(abs(sub.corr()).sum().sum()/data.shape[1])
        end += 1
        start += 1
    return corr_value

def get_dist_p(X, Y, p):
    return np.power(X-Y, p).sum()**(1/p)

def get_piece_dist_segment(X, Y, win, p):
    if(len(X) != len(Y)):
        print("not equal length series!!!!!!")
        return
    start = 0
    end = start + win
    results = []
    while end<len(X):
        results.append(get_dist_p(X[start:end], Y[start:end], p))
        start += win
        end += win
    return results


TEN_K = ['갑', '을', '병', '정', '무', '기', '경', '신', '임', '계']
TEN = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸']
TWV_K = ['자', '축', '인', '묘', '진', '사', '오', '미', '신', '유', '술', '해']
TWV = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥']

from time import localtime, time
from math import floor

class Zodiac:

    def __init__(self, y, m, d):
        if y < 1583:
            print('EXCESS MINIMUM!!!')
        elif y > 3999:
            print('EXCESS MAXIMUM!!!')
        else:
            if m == 1:
                y = y-1
                m = 13
            elif m == 2:
                y = y-1
                m = 14
            self.y, self.m, self.d = y, m, d

    def i10w(self, i):
        wk = TEN_K[i-1]
        w = TEN[i-1]
        return [wk, w]

    def i12w(self, i):
        wk = TWV_K[i-1]
        w = TWV[i-1]
        return [wk, w]

    def zdc_y(self,):
        y10 = (self.y+7)%10
        y12 = (self.y+9)%12
        return list(zip(self.i10w(y10), self.i12w(y12)))

    def zdc_m(self,):
        m10 = (2*self.y+self.m+3)%10
        m12 = (self.m+1)%12
        return list(zip(self.i10w(m10), self.i12w(m12)))

    def zdc_d(self,):
        c, n = int(str(self.y)[0:2]), int(str(self.y)[2:])
        d10 = (4*c+floor(c/4)+5*n+floor(n/4)+floor((3*self.m+3)/5)+self.d+7)%10
        d12 = (8*c+floor(c/4)+5*n+floor(n/4)+6*self.m+floor((3*self.m+3)/5)+self.d+1)%12
        return list(zip(self.i10w(d10), self.i12w(d12)))

    def display(self):
        return self.zdc_y(), self.zdc_m(), self.zdc_d()

    def display_k(self):
        return ''.join(self.zdc_y()[0])+'('+''.join(self.zdc_y()[1])+')'+'년, '+''.join(self.zdc_m()[0])+'('+''.join(self.zdc_m()[1])+')'+'월, '+''.join(self.zdc_d()[0])+'('+''.join(self.zdc_d()[1])+')'+'일'


import uuid
from dataclasses import asdict
from datetime import datetime
from typing import List, Optional

import mongoengine as me

from echis.main import settings
from echis.modules.share_playlist import Spotify, Deezer, Share, Youtube, AbstractShare, AppleMusic

def get_interface(name: str) -> Optional[AbstractShare]:
    name_clear = name.strip().lower()
    client = {
        "spotify": Spotify,
        "deezer": Deezer,
        "youtube": Youtube,
        "apple_music": AppleMusic,
    }
    get_client = client.get(name_clear, None)
    if get_client:
        return get_client()
    return None

class SharedSongs(me.Document):
    record_id = me.UUIDField(default=uuid.uuid4(), required=False)
    title = me.StringField(required=False)
    rank = me.IntField(required=False)
    song_id = me.StringField(required=True)
    artist = me.StringField(required=False)
    cover = me.StringField(required=False)
    album = me.StringField(required=True)
    playlist_id = me.StringField(required=False)
    added_to_playlist = me.StringField(required=True)
    added_by = me.StringField(required=False)
    created_at = me.DateTimeField(default=datetime.utcnow)
    api = me.StringField(required=False)
    link = me.StringField(required=False, default="")
    is_shared = me.BooleanField(default=False)

    @staticmethod
    def fetch_playlist() -> Optional[List[Share]]:
        get_playlists: List[Playlists] = Playlists.objects(is_active=True)
        songs: List[Share] = []
        for playlist in get_playlists:
            interface = get_interface(playlist.api)
            if interface:
                client = interface
                client.fetch(playlist_id=playlist.playlist_id)
                latest: Share = client.get_latest
                if latest:
                    latest.added_by = playlist.user
                    is_exists = SharedSongs.objects(song_id=latest.song_id, api=latest.api).count()
                    if not is_exists:
                        create = SharedSongs(**asdict(latest))
                        create.is_shared = True
                        create.save()
                        songs.append(latest)
                else:
                    raise Exception("Playlist not exist")
        return songs

    @staticmethod
    def get_songs_to_play() -> List[str]:
        share: List[Share] = SharedSongs.objects().order_by(settings.SHARE_DATE_SORTED)[:settings.QUEUE_LIMIT]
        songs = []
        for song in share:
            songs.append(f"{song.artist} {song.title}")
        return songs

class Playlists(me.Document):
    record_id = me.UUIDField(default=uuid.uuid4(), unique=True)
    playlist_id = me.StringField(required=True)
    user = me.StringField(required=True)
    api = me.StringField(required=True)
    is_active = me.BooleanField(default=True)
    created_at = me.DateTimeField(default=datetime.utcnow)

    @staticmethod
    def add_playlist(playlist_id: str, username: str, api: str) -> str:
        is_exist = Playlists.objects(playlist_id=playlist_id).count()
        if not is_exist:
            client = get_interface(api)
            if client:
                playlist_resolve = client.playlist_is_exists(playlist_id)
                if playlist_resolve:
                    new_playlist = Playlists(playlist_id=playlist_id, user=username, api=api)
                    new_playlist.save()
                    return "Success, playlist has been added"
                else:
                    return "Error, playlist not found"
        else:
            return "Error, playlist already exists, playlist must be public"

    @staticmethod
    def remove_playlist(playlist_id: str, username: str, api: str) -> str:
        playlist = Playlists.objects(playlist_id=playlist_id, user=username, api=api).first()
        if playlist:
            playlist.delete()
            return "Success, playlist has been removed"
        return "Error, playlist not found"


# Food Delivery

# Food Prices
CHICKEN_MENU = 10.35
FISH_MENU = 12.40
VEGETARIAN_MENU = 8.15

# Order
chicken_menus_count = int(input())
fish_menus_count = int(input())
vegetarian_menus_count = int(input())
delivery_charge = 2.50
dessert_bill_percentage = 20

no_dessert_bill = (CHICKEN_MENU * chicken_menus_count)\
    + (FISH_MENU * fish_menus_count)\
    + (VEGETARIAN_MENU * vegetarian_menus_count)

dessert_bill = (no_dessert_bill * (dessert_bill_percentage / 100))

full_bill = no_dessert_bill + dessert_bill + delivery_charge
print(full_bill)


# coding: utf-8

# # Analysis of mixed BDF/EX time integration

# In[ ]:

get_ipython().magic('matplotlib inline')
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets.widgets import interact
from scipy.optimize import minimize
from scipy.optimize import basinhopping

# ## Introduction

# Consider the PDE:
# $$ \frac{d \phi}{d t} = L(\phi) $$
# where $L$ is a linear operator.
# First, we discretize the LHS with a backwards difference formula (BDF):
# $$ \sum \beta_i \phi^{n-i} = L(\phi^n) $$
# where $\beta$ are the BDF coefficients.
# Next, we discretize the RHS with explicit extrapolation (EX), likely motivated by discrete versions of $L$ having a high condition number:
# \begin{equation}
# \sum_{i=0} \beta_i \phi^{n-i} = \sum_{i=1} \chi_i L \phi^{n-i}
# \end{equation}
# where $\chi$ are the extrapolation coefficients.
#
# The standard coefficients, those which achieve maximal convergence order, are found below.

# In[ ]:

bdf1 = np.array([  1., -  1.,   0.,    0.,   0.,   0.,  0.])/ 1.
bdf2 = np.array([  3., -  4.,   1.,    0.,   0.,   0.,  0.])/ 2.
bdf3 = np.array([ 11., - 18.,   9., -  2.,   0.,   0.,  0.])/ 6.
bdf4 = np.array([ 25., - 48.,  36., - 16.,   3.,   0.,  0.])/12.
bdf5 = np.array([137., -200., 300., -200.,  75., -12.,  0.])/60.
bdf6 = np.array([147., -360., 450., -400., 225., -72., 10.])/60.
ex1  = np.array([0., 1.,   0.,  0.,   0., 0.,  0.])
ex2  = np.array([0., 2., - 1.,  0.,   0., 0.,  0.])
ex3  = np.array([0., 3., - 3.,  1.,   0., 0.,  0.])
ex4  = np.array([0., 4., - 6.,  4., - 1., 0.,  0.])
ex5  = np.array([0., 5., -10., 10., - 5., 1.,  0.])
ex6  = np.array([0., 6., -15., 20., -15., 6., -1.])

# To evaluate the stability, we consider model solutions with $L \tilde \phi^i = \lambda_x \phi^i$ and $\phi^{i+1} = \lambda_t \phi^i$.
# The discrete equation becomes:
# \begin{equation}
# \sum_{i=0} \beta_i \lambda_t^{-i} = \lambda_x \sum_{i=1} \chi_i \lambda_t^{-i}
# \end{equation}
# Which can easily be solved for $\lambda_x$:
# \begin{equation}
# \lambda_x = \frac{\sum_{i=0} \beta_i \lambda_t^{-i}}{\sum_{i=1} \chi_i \lambda_t^{-i}}
# \end{equation}
# The method is stable iff $\left| \lambda_t \right| \le 1$, so the stability region of $\lambda_x$ is traced by solving the above for $\lambda_t = \left\{e^{i \theta} : \theta \in [0,2\pi)\right\}$.
#
# BDF/EX schemes are frequently used to advance the convection operator, which can be formulated to be skew-symmetric with purely imaginary eigenvalues.  In this context, the stability constraint is given by the first crossing of the imaginary axis.
#
# The code-block below traces the stability region and returns the location of the first crossing of the imaginary axis.

# In[ ]:

theta = np.linspace(0, 2*np.pi, endpoint=False, num=512)
E = np.zeros((theta.shape[0], 7), dtype=complex)
i = complex(0., 1.)
E[:,0] = 1.
E[:,1] = np.exp(-i*theta)
E[:,2] = np.exp(-2*i*theta)
E[:,3] = np.exp(-3.*i*theta)
E[:,4] = np.exp(-4.*i*theta)
E[:,5] = np.exp(-5.*i*theta)
E[:,6] = np.exp(-6.*i*theta)

def stab_region(time, space, num=512, plot=True, label=""):
    sol = np.dot(E, time) / np.dot(E, space)
    if plot:
        plt.plot(np.real(sol), np.imag(sol), label=label)
        plt.grid(True)
        if label is not None:
            plt.legend()
    for i in range(1, len(theta)):
        if np.real(sol[i]) < 0.0:
            return np.imag(sol[i-1])
    return 0.

# For example, the stability regions of BDF2/EX2 and BDF3/EX3 are below:

# In[ ]:

print("The maximum convection eigenvalue for BDF2/EX3 is {}".format(
        stab_region(bdf1, ex3, label="BDF2/EX2")))
print("The maximum convection eigenvalue for BDF3/EX3 is {}".format(
        stab_region(bdf3, ex3, label="BDF3/EX3")))
print("The maximum convection eigenvalue for BDF4/EX4 is {}".format(
        stab_region(bdf4, ex4, label="BDF4/EX4")))

# From this, it is clear to see that BDF2/EX2 is not suitable for the convection operator but BDF3/EX3 is.
# Interestingly, BDF2/EX3 is stable, so this is the 2nd order scheme implemented in codes like Nek5000.

# In[ ]:

print("The maximum convection eigenvalue for BDF2/EX2 is {}".format(
        stab_region(bdf2, 2./3.*ex3+1./3.*ex2, label="BDF2/EX2")))

# ## Mixing BDF3/EX3 and BDF2/EX2

# Following the method of Vatsa et al. for BDF2OPT, we can mix the coefficients of the second and third order schemes to produce 2nd order schemes with different stability regions and leading order error coefficients.
# In this case, we have two sets of coefficients that can be mixed separately, so we need two mixing parameters: let $\alpha$ mix the extrapolation coefficients and $\beta$ mix the BDF coefficients.

# In[ ]:

def mix_bdfex_23(alpha, beta, plot=False):
    res = stab_region((1.-beta)*bdf2+beta*bdf3,
                      (1.-alpha)*ex2+alpha*ex3,
                     plot=plot);
    if plot:
        print("The eigenvalue for BDF/EX-2,3({},{}) is {}".format(alpha, beta, res))
    return res

# In[ ]:

def mix_bdfex_2all(alpha, beta, plot=False):
    res = stab_region(bdf2,
                      (1.-alpha-beta)*ex2+alpha*ex3+beta*ex4,
                     plot=plot);
    if plot:
        print("The eigenvalue for BDF/EX-2,3({},{}) is {}".format(alpha, beta, res))
    return res

# In[ ]:

interact(mix_bdfex_23, alpha=.667, beta=.48, plot=True);

# In[ ]:

interact(mix_bdfex_2all, alpha=.667, beta=.1, plot=True);

# We can maximize the stability constraint.  The constraint $\alpha \ge 0$ must be added, because $\alpha < 0$ consistently results in instability (I don't know why).

# In[ ]:

def wrap(x):
    return -mix_bdfex_23(x[0], x[1])
def accept(f_new, x_new, f_old, x_old):
    if x_new[0] < 0:
        return False
#    if x_new[1] < 0:
#        return False
    return True
res = basinhopping(wrap,
                   [1.0, 1.0],
                   accept_test=accept,
                   minimizer_kwargs={'method': 'SLSQP', 'bounds': [(0, None), (None, None)]},
                   niter=1000,
                   niter_success=500,
                   T=0.01)
mix_bdfex_23(res.x[0], res.x[1], plot=True);

# In[ ]:

plt.figure(figsize=(15,15))
mix_bdfex_23(0.00513949945148418,-1.490579000429718, plot=True);

# And plot the stability constraint in the neighborhood of the minimum:

# In[ ]:

n = 200
alphas = np.linspace(0., 1., num=n)
betas = np.linspace(-2.0, 1.0, num=2*n)
cfls = np.zeros((n,2*n))
for i in range(n):
    for j in range(2*n):
        cfls[i,j] = mix_bdfex_23(alphas[i], betas[j])
plt.imshow(cfls.transpose(), origin='lower')
plt.colorbar()
foo = np.unravel_index(np.argmax(cfls), cfls.shape)

# ## Mixing BDF/EX-N and BDF/EX-N+1

# The same procedure can be used to mix BDF/EX3 and BDF/EX4.

# In[ ]:

def mix_bdfex_34(alpha, beta, plot=False):
    res = stab_region((1.-beta)*bdf3+beta*bdf4,
                      (1.-alpha)*ex3+alpha*ex4,
                     plot=plot);
    if plot:
        print("The eigenvalue for BDF/EX-3,4({},{}) is {}".format(alpha, beta, res))
    return res

# In[ ]:

interact(mix_bdfex_34, alpha=.5, beta=.5, plot=True);

# We can maximize the stability constraint.  Again, we must impose $\alpha \ge 0$.

# In[ ]:

def wrap(x):
    return -mix_bdfex_34(x[0], x[1])
def accept(f_new, x_new, f_old, x_old):
    if x_new[0] < 0:
        return False
#    if x_new[1] < 0:
#        return False
    return True
res = basinhopping(wrap,
                   [0.5, 0.5],
                   accept_test=accept,
                   minimizer_kwargs={'method': 'SLSQP', 'bounds': [(0., None), (None, None)]},
                   niter=1000,
                   niter_success=500,
                   T=0.01)
mix_bdfex_34(res.x[0], res.x[1], plot=True);

# And plot the stability constraint in the neighborhood of the minimum:

# In[ ]:

n = 200
alphas = np.linspace(0., 1., num=n)
betas = np.linspace(-2.0, 1.0, num=2*n)
cfls = np.zeros((n,2*n))
for i in range(n):
    for j in range(2*n):
        cfls[i,j] = mix_bdfex_34(alphas[i], betas[j])
plt.imshow(cfls.transpose(), origin='lower')
plt.colorbar()
foo = np.unravel_index(np.argmax(cfls), cfls.shape)

# In[ ]:

mix_bdfex_34(0,-1.4682977182989303, plot=True)

# In[ ]:

def mix_bdfex_24(alpha, beta, plot=False):
    res = stab_region((1.-beta)*bdf2+beta*bdf4,
                      (1.-alpha)*ex2+alpha*ex4,
                     plot=plot);
    if plot:
        print("The eigenvalue for BDF/EX-2,4({},{}) is {}".format(alpha, beta, res))
    return res

# In[ ]:

def wrap(x):
    return -mix_bdfex_24(x[0], x[1])
def accept(f_new, x_new, f_old, x_old):
    if x_new[0] < 0:
        return False
#    if x_new[1] < 0:
#        return False
#    if x_new[0] + x_new[1] > 1.0:
#        return False
#    if x_new[2] < 0:
#        return False
#    if x_new[3] < 0:
#        return False
#    if x_new[2] + x_new[3] > 1.0:
#        return False
#    if x_new[1] < 0:
#        return False
    return True

res = basinhopping(wrap,
                   [1.0, 1.0],
                   accept_test=accept,
                   minimizer_kwargs={'method': 'SLSQP', 'bounds': [(0, None), (None, None)]},
                   niter=1000,
                   niter_success=500,
                   T=0.01)
mix_bdfex_24(res.x[0], res.x[1], plot=True);

# In[ ]:

def mix_bdfex_234(alpha1, alpha2, beta1, beta2, plot=False):
    res = stab_region((1.-beta1 - beta2)*bdf2+beta1*bdf3 + beta2*bdf4,
                      (1.-alpha1 - alpha2)*ex2+alpha1*ex3 + alpha2*ex4,
                     plot=plot);
    if plot:
        print("The eigenvalue for BDF/EX-2,3,4({}-{},{}-{}) is {}".format(alpha1, alpha2, beta1, beta2, res))
    return res

# In[ ]:

interact(mix_bdfex_234, alpha1=.667, alpha2=0., beta1=.48, beta2 = 0., plot=True);

# In[ ]:

plt.figure(figsize=(15,15))
mix_bdfex_234(.633, .4, -.48, 0.0, plot=True)

# In[ ]:

mix_bdfex_234(0,-0.250000001,-2.5,-3, plot=True)

# In[ ]:

def wrap(x):
    return -mix_bdfex_234(x[0], x[1], x[2], x[3])
def accept(f_new, x_new, f_old, x_old):
    if x_new[0] < 0:
        return False
#    if x_new[1] < 0:
#        return False
#    if x_new[0] + x_new[1] > 1.0:
#        return False
#    if x_new[2] < 0:
#        return False
#    if x_new[3] < 0:
#        return False
#    if x_new[2] + x_new[3] > 1.0:
#        return False
#    if x_new[1] < 0:
#        return False
    return True

res = basinhopping(wrap,
                   [1.0, 0.0, 1.0, 0.0],
                   accept_test=accept,
                   minimizer_kwargs={'method': 'SLSQP', 'bounds': [(-1, 1), (-1, 1), (-1, 1), (-1, 1)]},
                   niter=100,
                   niter_success=50,
                   T=0.01)
mix_bdfex_234(res.x[0], res.x[1], res.x[2], res.x[3], plot=True);

# In[ ]:


import os
import sys
import glob
import time
import torch
import torch.nn as nn
import numpy as np
import PIL.Image as Image
import matplotlib.pyplot as plt

def create_dir(dir):
    if not os.path.exists(dir):
        os.makedirs(dir)

def imshow(img):
    for i in range(len(img)):
        tmp_img = img[i] / 2 + 0.5     # unnormalize
        npimg = tmp_img.numpy()
        plt.figure()
        plt.imshow(np.transpose(npimg, (1, 2, 0)))
    plt.show()

def load_filelist(path, split):
    filelist = []
    # split = 'train'
    # image_dir = os.path.join('./data/cityscapes/leftimg8bit', split)
    image_dir = os.path.join(path, split)
    for city in os.listdir(image_dir):
        img_dir = os.path.join(image_dir, city)
        for file_name in os.listdir(img_dir):
            filelist.append(os.path.join(img_dir, file_name))
    filelist.sort()
    return filelist

def show_model(net):
    for idx, m in enumerate(net.modules()):
        print(idx, '->', m)

def rgb_to_ycbcr(image: torch.Tensor) -> torch.Tensor:
    r"""Convert an RGB image to YCbCr.

    Args:
        image (torch.Tensor): RGB Image to be converted to YCbCr.

    Returns:
        torch.Tensor: YCbCr version of the image.
    """

    if not torch.is_tensor(image):
        raise TypeError("Input type is not a torch.Tensor. Got {}".format(
            type(image)))

    if len(image.shape) < 3 or image.shape[-3] != 3:
        raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
                         .format(image.shape))

    r: torch.Tensor = image[..., 0, :, :]
    g: torch.Tensor = image[..., 1, :, :]
    b: torch.Tensor = image[..., 2, :, :]

    delta = .5
    y: torch.Tensor = .299 * r + .587 * g + .114 * b
    cb: torch.Tensor = (b - y) * .564 + delta
    cr: torch.Tensor = (r - y) * .713 + delta
    return torch.stack((y, cb, cr), -3)

# it has been proved that this PSNR in torch is correct when batch size is 1
class PSNR(nn.Module):
    def __init__(self, max_val):
        super(PSNR, self).__init__()

        base10 = torch.log(torch.tensor(10.0).cuda())
        max_val = torch.tensor(max_val).float().cuda()

        self.register_buffer('base10', base10)
        self.register_buffer('max_val', 20 * torch.log(max_val) / base10)

    def forward(self, a, b):
        mse = torch.mean((a.float() - b.float()) ** 2)

        if mse == 0:
            return torch.tensor(0)

        return self.max_val - 10 * torch.log(mse) / self.base10


import datetime
import json

import numpy as np
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.mail import EmailMessage
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from django.template.loader import render_to_string
from django.contrib.messages import get_messages

from absences.models import Absence, getAbsenceTypesForTemplate
from accounts.models import wtmUser
from config import settings

@login_required(login_url='home')
def createAbsenceView(request):
    try:
        if not wtmUser.objects.get(user=request.user).doUserHaveTeam():
            return render(request, 'errors/noTeamUser.html')
    except wtmUser.DoesNotExist:
        print("Something went wrong.")
    pendingAbsenceRequestsList = Absence.objects.filter(
        owner=request.user, statusType='SENTTOAPPROVE').order_by('-pk')
    allAbsenceRequestsList = Absence.objects.filter(owner=request.user).order_by('-pk')
    requesterManager = wtmUser.objects.get(user=request.user).team.manager
    absenceTypes = getAbsenceTypesForTemplate()
    if request.POST:
        if request.POST.get('action') == 'sendAbsenceRequest':
            absenceType = request.POST.get('absenceType')
            startDate = request.POST.get('startDate')
            endDate = request.POST.get('endDate')

            if (startDate == endDate):
                workDays = 1
            else:
                workDays = np.busday_count(startDate, endDate)

            if workDays <= 0:
                messages.info(
                    request, "You entered wrong dates, working days sum equal or smaller than 0.")
            else:
                createdAbsenceRequest = Absence.objects.create(
                    owner=request.user, manager=requesterManager, startDate=startDate, endDate=endDate, absenceType=absenceType, workDays=workDays)
                createdAbsenceRequest = Absence.objects.get(pk=createdAbsenceRequest.pk)
                sendEmailNewAbsenceRequestForApproval(
                    request, request.user, requesterManager)
                return JsonResponse({
                                    'djangoMessage': "Absence request has been sent to your manager.",
                                    'userName': request.user.get_full_name(),
                                    'startDate': createdAbsenceRequest.getStartDateForTemplate(),
                                    'endDate': createdAbsenceRequest.getEndDateForTemplate(),
                                    'workDays': createdAbsenceRequest.workDays,
                                    'absenceType': createdAbsenceRequest.getAbsenceRequestType(),
                                    })

    return render(request, 'absences/newAbsence.html', {'requesterManager': requesterManager,
                                                        'absenceTypes': absenceTypes,
                                                        'pendingAbsenceRequestsList': pendingAbsenceRequestsList,
                                                        'allAbsenceRequestsList': allAbsenceRequestsList
                                                        })

@login_required(login_url='home')
def absenceRequestsSentForApprovalListView(request):
    absenceRequestsList = Absence.objects.filter(
        manager=request.user, statusType='SENTTOAPPROVE')
    if request.POST:
        if request.POST.get('action') == 'approveAbsenceRequest':
            absenceRequestPk = request.POST.get('absenceRequestPk')
            absenceRequest = Absence.objects.get(pk=absenceRequestPk)
            absenceRequest.statusType = 'APPROVED'
            absenceRequest.save()
        if request.POST.get('action') == 'declineAbsenceRequest':
            absenceRequestPk = request.POST.get('absenceRequestPk')
            absenceRequest = Absence.objects.get(pk=absenceRequestPk)
            absenceRequest.statusType = 'DECLINED'
            absenceRequest.save()

    return render(request, 'absences/absenceRequestsToAccept.html', {'absenceRequestsList': absenceRequestsList})

def sendEmailNewAbsenceRequestForApproval(request, user, manager):
    emailSubject = 'Work Time manager - new absence request for approval!'
    emailBody = render_to_string('emails/absenceRequestSentMail.html', {
        'user': user,
        'manager': manager,
    })

    email = EmailMessage(subject=emailSubject, body=emailBody,
                         from_email=settings.EMAIL_FROM_USER, to=[manager.email])
    email.send()


import json
from video_conferencing.clickmeeting.actions import ClickmeetingActions
from unified.core.app import App, AuthInfo

class ClickmeetingApp(App,ClickmeetingActions):

    def __init__(self):
        super().__init__(
            name="Clickmeeting",
            description="ClickMeeting is a browser-based webinar solution, brings the power of webinars to organizations of any size, from one-person firms to multinational enterprises.",
            category="video_conferencing",
            logo="https://logo.500apps.com/clickmeeting",
            auth_info=None,
            auth_type='Basic')


import sys
import pandas as pd
from sklearn.model_selection import train_test_split
import os
import pdb
import numpy as np
import math

def pairing(odds, idx = ''):
    odds['dummy'] = 1
    odds['pair'] = odds.sort_values(['case','slice_id', 'day'],ascending=False).groupby(['case', 'day'])['slice_id'].shift()
    odds = odds[odds['slice_id'] % 2 == 1]
    odds['pair_idx'] = odds['dummy'].cumsum()
    odds['pair_idx'] = odds['pair_idx'].apply(lambda x: idx + str(x))

    #odds['pair'] = odds['pair'].astype('int')
    odds = pd.concat([odds[['case', 'slice_id', 'day', 'pair_idx', 'dummy']], odds[['case', 'pair', 'day', 'pair_idx', 'dummy']].rename({'pair': 'slice_id'}, axis = 'columns')])

    #Drop those that only have 1
    odds['pair_total'] = odds.groupby(['pair_idx'])['dummy'].sum()
    odds = odds[odds['pair_total'] != 2]
    return odds.drop(['pair_total', 'dummy'], axis = 'columns')

def dataset_split(dataset_path, output_folder, train_prop=0.7, val_prop=0.2, test_prop=0.1):
    # Default split is 70/20/10
    # Check if the splits add up to 1
    total = train_prop + val_prop + test_prop
    if abs(total - 1) > 0.0000001:
        print("Train, validation, and test proportions must add up to 1. Instead, they are", round(total, 3))

    # Create output folder if its not already created
    if not os.path.exists(output_folder):
        os.mkdir(output_folder)

    data = pd.read_csv(dataset_path, index_col=0)

    #Find pairs
    pair_ids = pairing(data)

    data = pd.merge(pair_ids, data, on = ['case', 'slice_id', 'day'])
    data['dummy'] = data.groupby(['pair_idx'])['dummy'].cumsum()
    data1 = data[data['dummy'] == 1]

    #Random sort, make sure no more than one repeat in a batch
    min_check = 0
    while min_check <= 1:
        data1 = data1.sample(frac=1).reset_index(drop=True)
        data1['batch'] = data1.index // 16
        check = data1.groupby('batch')['case'].count()
        min_check = min(check)

    data2 = pd.merge(data[data['dummy'] == 2], data1[['pair_idx', 'batch']], on = 'pair_idx')
    data = pd.concat([data1, data2]).reset_index(drop=True).sort_values(['batch', 'pair_idx'])

    n_batches = max(data1['batch'])
    val_batch = int(math.floor(val_prop * n_batches))
    test_batch = int(math.floor(test_prop * n_batches))
    train_batch = n_batches - val_batch - test_batch

    # Split into train and val and test datasets
    train = data[data['batch'] <= train_batch]
    val = data[(data['batch'] > train_batch) & (data['batch'] <= train_batch + val_batch)]
    test = data[data['batch'] > train_batch + val_batch]

    # Output train, val, test datasets
    train.to_csv(os.path.join(output_folder, "train_dataset.csv"), index=False)
    val.to_csv(os.path.join(output_folder, "val_dataset.csv"), index=False)
    test.to_csv(os.path.join(output_folder, "test_dataset.csv"), index=False)

if __name__ == '__main__':
    # usage: python data/dataset_split.py [final.csv] [output folder] [train percent] [val percent] [test percent]
    dataset_path = sys.argv[1]
    output_folder = sys.argv[2]
    try:
        train_prop = int(sys.argv[3]) / 100
        val_prop = int(sys.argv[4]) / 100
        test_prop = int(sys.argv[5]) / 100
        #print(f"Using train-val-test split of {sys.argv[3]}%-{sys.argv[4]}%-{sys.argv[5]}%")
        dataset_split(dataset_path, output_folder, train_prop, val_prop, test_prop)
    except:
        #print("Using default train-val-test split of 70%-20%-10%")
        dataset_split(dataset_path, output_folder)


#1.	Program to read a file and store the unique words in a list sorted based on the length of word in a new file along with each word length appended to it.
import re

try:
    words=[]
    with open('FirstInput.txt', 'r') as f:
        for line in f:
            for word in line.split():
                words.append(word)

    words=list(set(words))
    words=list(sorted(words, key = len))
    with open('FirstOutput.txt', 'w') as f:
        for i in words:
            f.write(i+str(",")+str(len(i)))
            f.write("\n")
except:
    print("An exception occurred")


import unittest

from parameterized import parameterized

from editDistance.edit_distance import Solution
from editDistance.edit_distance_table import Solution as TableSolution

class Tests(unittest.TestCase):
    def setUp(self):
        self.solution = Solution()
        self.table_solution = TableSolution()

    @parameterized.expand([
        ["word1", "word2", 1],
        ["a", "a", 0],
        ["a", "ab", 1],
        ["horse", "ros", 3],
        ["intention", "execution", 5],
        ])
    def test_solution(self, word1, word2, expected_result):
        self.assertEqual(expected_result, self.solution.minDistance(word1, word2))
        self.assertEqual(expected_result, self.table_solution.minDistance(word1, word2))


"""
Tools for parsing markdown docs.
"""
from bs4 import BeautifulSoup
from collections import defaultdict
from markdown_rundoc.rundoc_code import RundocCodeExtension
from rundoc.block import DocBlock, block_actions
from rundoc.commander import DocCommander
import json
import markdown
import operator
import re

def mkd_to_html(mkd, tags='', must_have_tags='', must_not_have_tags='',
        single_session='', selection_tag='rundoc_selected'):
    """Read markdown stream and return html string."""
    html_data = markdown.markdown(
        mkd,
        extensions = [
            RundocCodeExtension(
                tags=tags,
                must_have_tags=must_have_tags,
                must_not_have_tags=must_not_have_tags,
                single_session=single_session,
                selection_tag=selection_tag,
                )
            ]
        )
    return html_data

def parse_doc(input, tags="", must_have_tags="", must_not_have_tags="",
    single_session="", light=False, **kwargs):
    """Parse code blocks from markdown file and return DocCommander object.

    Args:
        input (file): Readable file-like object pointing to markdown file.
        tags (str): Hash (#) separated list of tags. Markdown code block that
            contain at least one of them will be used.
        must_have_tags (str): Like 'tags' but require markdown code block to
            contain all of them (order not important).
        must_not_have_tags (str): Like 'tags' but require markdown code block
            to contain non of them.
        light (bool): Will use light backgrond color theme if set to True.
            Defaults to False.

    Returns:
        DocCommander object.
    """

    html_data = mkd_to_html(
        input.read(),
        tags,
        must_have_tags,
        must_not_have_tags,
        single_session,
        )
    soup = BeautifulSoup(html_data, 'html.parser')
    commander = DocCommander()

    # find blocks
    def is_runnable_block(tag):
        if tag.name != 'code':
            return False
        if 'rundoc_selected' not in tag.get('class', {}):
            return False
        return not bool({
            "env",
            "environ",
            "environment",
            "secret",
            "secrets",
            }.intersection(tag.get('class', {})))
    code_block_elements = soup.findAll(is_runnable_block)
    all_code = ""
    for element in code_block_elements:
        tags_list = element.get_attribute_list('class')
        tags_list = list(filter(bool, tags_list))
        if tags_list:
            tags_list.remove('rundoc_selected')
            if single_session:
                all_code += element.getText()
            else:
                commander.add(element.getText(), tags_list, light)
    if single_session:
        commander.add(all_code, [single_session], light)

    # find environments
    def is_environment(tag):
        if tag.name != 'code':
            return False
        if 'rundoc_selected' not in tag.get('class', {}):
            return False
        return bool({'env','environ','environment'}.intersection(
            tag.get('class', {})))
    env_elements = soup.findAll(is_environment)
    env_string = "\n".join([ x.string or '' for x in env_elements ])
    commander.env.import_string(env_string)

    # find secrets
    def is_secret(tag):
        if tag.name != 'code':
            return False
        if 'rundoc_selected' not in tag.get('class', {}):
            return False
        return bool({'secret','secrets'}.intersection(tag.get('class', {})))
    secrets_elements = soup.findAll(is_secret)
    secrets_string = "\n".join([ x.string for x in secrets_elements ])
    commander.secrets.import_string(secrets_string)
    return commander

def parse_output(input, exact_timing=False, light=False, **kwargs):
    """Load json output, create and return DocCommander object.

    Each code block recorded in the otput will be parsed and only code from
    successful attempts will be turned into code blocks for new session. The
    goal is to use original or user modified inputs as a new script.

    Args:
        output (file): Readable file-like object.
        exact_timing (bool): NOT IMPLEMENTED YET!
            If True, a code block will be created for each run try
            and pause between blocks and tries will be calculated from the
            timestamps recorded in the file. The goal is to recreate all exact
            steps that users may have done. Defaults to False.
        light (bool): Will use light backgrond color theme if set to True.
            Defaults to False.

    Returns:
        DocCommander object.
    """
    output_data = input.read()
    data = json.loads(output_data)
    commander = DocCommander()
    for d in data['code_blocks']:
        doc_block = DocBlock(
            code=d['runs'][-1]['user_code'],
            tags=d['tags'],
            light=light,
            )
        commander.doc_blocks.append(doc_block)
        commander.env.extend(data['env'])
    return commander

def get_tags(input, **kwargs):
    """Read markdown file and return list of available tags."""
    tag_dict = defaultdict(int)
    html_data = mkd_to_html(input.read())
    soup = BeautifulSoup(html_data, 'html.parser')
    match = re.compile("^.+$")
    code_block_elements = soup.findAll(name='code', attrs={"class":match,})
    for element in code_block_elements:
        for class_name in element.get_attribute_list('class'):
            tag_dict[class_name] += 1
    if 'rundoc_selected' in tag_dict:
        del(tag_dict['rundoc_selected'])
    sorted_tag_dict = sorted(tag_dict.items(), key=operator.itemgetter(1),
        reverse=True)
    return sorted_tag_dict

def get_blocks(input, tags="", must_have_tags="", must_not_have_tags="",
    single_session="", light=False, pretty=False, **kwargs):
    commander = parse_doc(input, tags, must_have_tags, must_not_have_tags,
        single_session, light)
    blocks = ""
    if pretty:
        step = 0
        for block in commander.doc_blocks:
            step += 1
            blocks += "{}. [{}] {}".format(
                step, block.interpreter, '#'.join(block.tags))
            blocks += "\n=================\n"
            blocks += str(block)
            blocks += "\n"
    else:
        blocks = json.dumps(commander.get_dict(), sort_keys=True, indent=4)
    return blocks

def get_clean_doc(input):
    mkd_data = input.read()
    # clean all tags except the interpreter
    mkd_data = re.sub(
        '^(```[^#:\n]+).*$',
        '\\1',
        mkd_data,
        flags=re.MULTILINE,
        )
    return mkd_data


def LongestConseqSubseq(arr, l):
    val = []
    c = 0
    for i in range(l):
        n = 1
        while arr[i] + n in arr:
            c += 1
            n += 1
        val.append(c + 1)
        c = 0
    return max(val)
array = [7, 8, 1, 5, 4, 3]
print("Longest Consecutive Subsequence :", LongestConseqSubseq(array, len(array)))


# -*- coding: utf-8 -*-
__author__ = "Filipe Ribeiro"

import socket, sys

HOST = '127.0.0.1'  # endereço IP
PORT = 20000        # Porta utilizada pelo servidor
BUFFER_SIZE = 1024  # tamanho do buffer para recepção dos dados

def enviarValorInicial(s):
    valor = input("Digite um valor para o oponente\n")
    while (len(str(valor)) != 3 or not str(valor).isdigit()):
            valor = input("Digite um valor para o oponente\n")
    s.send(valor.encode())
    while(True):
        esperandoValorJogador = s.recv(BUFFER_SIZE).decode('utf-8')
        if(esperandoValorJogador == "hora de jogar"):
            print(esperandoValorJogador)
            break
        else:
            print(esperandoValorJogador)
def main(argv):
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.connect((HOST, PORT))
            print("Servidor executando!")
            while(True):
                foiAceito = s.recv(BUFFER_SIZE).decode('utf-8')
                if(foiAceito == "Aceito"):
                    break
                else:
                    print("esperando jogador")
            while(True):
                enviarValorInicial(s)

                enviarPalpitesVerResultados(s)

    except Exception as error:
        print("Exceção - Programa será encerrado!")
        print(error)
        return

def enviarPalpitesVerResultados(s):
    qtdPalpites = 0
    while(True):
        texto = input("Digite um palpite: ")
        if(texto=="sair"):
            s.close()
            break
        while (len(str(texto)) != 3 or not str(texto).isdigit()):
            texto = input("Digite um palpite: ")
            if(texto=="sair"):
                s.close()
                break
        s.send(texto.encode()) #texto.encode - converte a string para bytes
        data = s.recv(BUFFER_SIZE)
        texto_string = data.decode('utf-8')
        if(texto_string == "esperando palpite do outro jogador"):
            print(texto_string)
            data = s.recv(BUFFER_SIZE)

        #texto_recebido = repr(data) #converte de bytes para um formato "printável"
        texto_string = data.decode('utf-8') #converte os bytes em string
        print(texto_string)
        data = s.recv(BUFFER_SIZE)
        qtdPalpites+=1
        if (data.decode('utf-8') == "Voce ganhou" or data.decode('utf-8') == "Voce perdeu"):
            print("{} com {} palpites".format(data.decode('utf-8'), qtdPalpites))
            data = s.recv(BUFFER_SIZE)
            print(data.decode('utf-8'))
            print('vai reiniciar o jogo')
            break

def jogoUmjogador(s):
    while(True):
        texto = input("Digite um palpite\n")
        while (len(str(texto)) != 3 or not str(texto).isdigit()):
            texto = input("Digite um palpite\n")
        print("enviado:"+ str(texto))
        s.send(texto.encode()) #texto.encode - converte a string para bytes
        data = s.recv(BUFFER_SIZE)
        texto_recebido = repr(data) #converte de bytes para um formato "printável"
        texto_string = data.decode('utf-8') #converte os bytes em string
        print(texto_recebido)
        if (texto == '000' or texto_string=='T3M0'):
            print('vai encerrar o socket cliente!')
            s.close()
            break

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


movies = ["QQ","AA",1992,50,["ABC","CCD",[811123,"OK"]]]

def print_list(name,indent=False,Level=0):
    for each_lis in name:
        if isinstance(name,list):
            print_list(each_lis,indent,Level+1)
        else:
            if indent:
                for each_tab in range(Level):
                    print("\t",end='')
            print(each_lis)


def find_message(text):
    rezul = ''
    for char in text:
        if 'A' <= char <= 'Z':
            rezul += char
    return rezul

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert find_message("How are you? Eh, ok. Low or Lower? Ohhh.") == "HELLO", "hello"
    assert find_message("hello world!") == "", "Nothing"
    assert find_message("HELLO WORLD!!!") == "HELLOWORLD", "Capitals"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")


import tempfile
from PMACParser import *
import os
from IPython.display import HTML, display
import tabulate as tb

class PMAC2Py:
    def __init__(self, filepath, DEBUG=False):
        self.filepath = filepath
        self.DEBUG=DEBUG
        self.pyfile = tempfile.mkstemp(dir=os.getcwd())[1]
        self.parser = PMACParser()

    def __call__(self):
        self.initHeader()
        self.processFile()
        self.footer()

    def initHeader(self):
        with open("inc/header.py","r") as h, open(self.pyfile,"w") as f_temp:
            f_temp.write(h.read())

    def processFile(self):
        with open(self.pyfile,"a") as f_temp, open(self.filepath, "r") as  pmc_file:
#             print([self.parser.convertLine(line) for line in pmc_file.readlines() ])
            f_temp.write(
                "".join(
                    [self.parser.convertLine(line) for line in pmc_file.readlines() ]
                    )
            )
        if self.DEBUG:
            with open(self.filepath, "r") as pmc_file:
                processed_list = [[line, self.parser.convertLine(line)] for line in pmc_file.readlines()]
                # for i,line in enumerate(pmac_str.split("\n")):
                #     print(i, "   ",  line, "   ", pmc.convertLine(line))
                tb.PRESERVE_WHITESPACE = True
                table_str=(tb.tabulate(
                    processed_list,
                    showindex="always",
                    headers=["PMC", "python"],
                ))
                print(table_str)

    def footer(self):
        with open("inc/footer.py") as footer, open(self.pyfile, "a") as f_temp:
            f_temp.write(footer.read())


class Solution:
    def __init__(self):
        self.months = {
            "Jan": "01", "Feb": "02", "Mar": "03",
            "Apr": "04", "May": "05", "Jun": "06",
            "Jul": "07", "Aug": "08", "Sep": "09",
            "Oct": "10", "Nov": "11", "Dec": "12"
        }
    def reformatDate(self, date: str) -> str:
        """
        :type date: str
        :rtype: str
        """
        year = date[-4:]
        month = self.months[date[-8:-5]]
        try: day = int(date[:2])
        except: day = int(date[:1])
        day = f"0{day}" if day < 10 else f"{day}"
        return f"{year}-{month}-{day}"

# Another Solution
class Solution(object):
    def __init__(self):
        self.months = {
            "Jan": "01", "Feb": "02", "Mar": "03",
            "Apr": "04", "May": "05", "Jun": "06",
            "Jul": "07", "Aug": "08", "Sep": "09",
            "Oct": "10", "Nov": "11", "Dec": "12"
        }
    def reformatDate(self, date):
        """
        :type date: str
        :rtype: str
        """
        items = date.split(" ")
        year = items[2]
        month = self.months[items[1]]
        day = items[0][:-2]
        day = f"0{day}" if len(day)==1 else f"{day}"
        return f"{year}-{month}-{day}"


# -*- coding: utf-8 -*-
# @File  : LogisticRegression.py
# @Author: clelandgt@163.com
# @Date  : 2020-03-24
# @Desc  : 逻辑回归的实现
import numpy as np
from sklearn import datasets

class LogisticRegression:
    def __init__(self):
        self._thetas = None
        # 截距
        self.intercept = None
        # 参数系数
        self.coefs = None

    @staticmethod
    def sigmoid(t):
        return 1.0 / (1 + np.exp(-t))

    def j(self, x, y, theta):
        """目标函数"""
        try:
            sig = self.sigmoid(x.dot(theta))
            return -(np.sum(y.dot(np.log(sig)) + (1-y).dot(1-sig))) / len(x)
        except:
            # 当数据特别大，报错时，返回无穷大。
            return float('inf')

    def dj_debug(self, x, y, theta, epsilon=0.01):
        """梯度调试"""
        res = np.empty(len(theta))
        for i in range(len(theta)):
            theta_1 = theta.copy()
            theta_1[i] += epsilon
            theta_2 = theta.copy()
            theta_2[i] -= epsilon
            res[i] = (self.j(theta_1, x, y) - self.j(theta_2, x, y)) / (2 * epsilon)
        return res

    def dj(self, x, y, thetas):
        """求导(梯度)"""
        sig = self.sigmoid(x.dot(thetas))
        return (x.T).dot(sig-y)

    def gradient_descent(self, dj, x, y, initial_thetas, eta, epsilon, max_iters):
        """梯度下降"""
        thetas = initial_thetas
        while max_iters > 0:
            # 梯度gradient
            gradient = dj(x, y, thetas)
            last_thetas = thetas
            thetas = thetas - eta * gradient
            if(abs(self.j(x, y, thetas) - self.j(x, y, last_thetas)) < epsilon):
                break
            max_iters -= 1

        self._thetas = thetas
        self.intercept = thetas[0]
        self.coefs = thetas[1:]

    def fit(self, x_train, y_train, eta=0.01, epsilon=1e-8, max_iters=1e4, debug=False):
        """训练"""
        # 加上一列全为1
        X_b = np.hstack([np.ones((len(x_train), 1)), x_train])
        initial_thetas = np.zeros(X_b.shape[1])

        if debug:
            self.gradient_descent(self.dj_debug, X_b, y_train, initial_thetas, eta, epsilon, max_iters)
        else:
            self.gradient_descent(self.dj, X_b, y_train, initial_thetas, eta, epsilon, max_iters)

    def predict(self, x_predict):
        X_b = np.hstack([np.ones((len(x_predict), 1)), x_predict])
        p = self.sigmoid(X_b.dot(self._thetas))
        p[p >= 0.5] = 1
        p[p < 0.5] = 0

        return p

    def score(self, x, y):
        """accuracy=正确的数据量 / 样本量"""
        y_predict = self.predict(x)
        return np.sum(y == y_predict) / len(y)

def main():
    iris = datasets.load_iris()
    X = iris.data
    y = iris.target

    # 只保留两种莺尾花
    X = X[y[y < 2], : 2]
    y = y[y < 2]

    # 训练模型
    log_reg = LogisticRegression()
    log_reg.fit(X, y)
    print('coefs: ', log_reg.coefs)
    print('intercept: ', log_reg.intercept)
    print('Score: ', log_reg.score(X, y))

if __name__ == '__main__':
    main()


from PIL import Image, ImageDraw, ImageGrab, ImageFile
import pyautogui
import keyboard
import time
import random
import cv2

captcha_vert_r, captcha_vert_g, captcha_vert_b, captcha_vert_T = 16, 23, 41, 255 # en haut a gauche le premier pixel vert du captcha

liste_compte = []

def screen():
    capture = pyautogui.screenshot()
    capture.save(r"C:\Users\balin\OneDrive\Bureau\bot GouzouGouzou\capture.png")

def captcha_resolver():
    macro = True
    while macro == True:
        cours = True
        if keyboard.is_pressed("ctrl+!"):
            screen()
            while cours == True:
                vert_r, vert_g, vert_b = img.getpixel((827,421))
                if vert_r == captcha_vert_r and vert_g == captcha_vert_g and vert_b == captcha_vert_b:
                    for x in range(827,1086):
                        for y in range(421,504):
                            trouver_gris_r, trouver_gris_g, trouver_gris_b, trouver_gris_T = img.getpixel((x,y))
            coo = pyautogui.locateCenterOnScreen("bouton_vert.png")
            print(coo)
            pyautogui.click(coo)
        elif keyboard.is_pressed("²"):
            macro=False
        else:
            continue

def couleur(a,b):
    img = Image.open("capture.PNG")
    nr,nv,nb,nn = img.getpixel((a,b))
    print(nr,nv,nb,nn)

class running:
    def verif_bloquage():
        oui = 0
    def sus(nombre):
        print("program statut : running \nfollowing")
        macro = True
        bouclee = 0
        sortir = False
        coo_sabonner_temp = 0
        while macro == True:
            cours = True
            if keyboard.is_pressed("!"):
                boucle = 0
                while boucle < nombre:
                    coo_sabonner = pyautogui.locateCenterOnScreen("sabonner.png", confidence = 0.9)
                    bloquage = pyautogui.locateCenterOnScreen("bloquage.png")
                    if bloquage is not None:
                        print("bloquage")
                        ok = pyautogui.locateCenterOnScreen("OK.png")
                        pyautogui.click(ok)
                        time.sleep(2)
                        coo_croix = pyautogui.locateCenterOnScreen("croix.png")
                        pyautogui.click(coo_croix)
                        print("program statut : Stoped")
                        sortir = True
                        break
                    elif coo_sabonner is not None:
                        if coo_sabonner_temp == coo_sabonner:
                            pyautogui.click(coo_sabonner)
                            print("attendre : 2s")
                            time.sleep(2)
                        else:
                            time.sleep(1)
                            coo_sabonner_temp = coo_sabonner
                            pyautogui.click(coo_sabonner)
                            print("sabonner : ",boucle+1)
                            boucle += 1
                    elif boucle == nombre:
                        sortir = True
                        coo_croix = pyautogui.locateCenterOnScreen("croix.PNG")
                        if coo_croix is not None:
                            pyautogui.click(coo_croix)
                            print("croix")
                            break
                        else:
                            break
                    else:
                        print("descendre")
                        pyautogui.scroll(-200)
                        time.sleep(2)
            if sortir == True:
                break
            elif keyboard.is_pressed("p"):
                macro=False
            else:
                continue

    def desus(nombre):
        print("program statut : running \ndesus")
        macro = True
        bouclee = 0
        boucle = 0
        sortir = False
        coo_desabonner_temp = 0
        while macro == True:
            cours = True
            if keyboard.is_pressed("!"):
                while True:
                    bloquage = pyautogui.locateCenterOnScreen("bloquage.png", confidence = 0.9)
                    coo_desabonner = pyautogui.locateCenterOnScreen("desabonner.png", confidence = 0.9)
                    if bloquage is not None:
                        print("bloquage")
                        ok = pyautogui.locateCenterOnScreen("OK.png")
                        pyautogui.click(ok)
                        time.sleep(1)
                        coo_croix = pyautogui.locateCenterOnScreen("croix.png")
                        pyautogui.click(coo_croix)
                        print("program statut : Stoped")
                        sortir = True
                        break
                    elif coo_desabonner is not None:
                        if coo_desabonner_temp == coo_desabonner:
                            print("attendre : 15s")
                            time.sleep(15)
                        else:
                            while boucle < nombre:
                                print("desabonner : ",boucle+1)
                                boucle += 1
                                bouclee = boucle
                                coo_desabonner = pyautogui.locateCenterOnScreen("desabonner.png", confidence = 0.9)
                                if coo_desabonner is not None:
                                    pyautogui.click(coo_desabonner)
                                    coo_sedesabonner = pyautogui.locateCenterOnScreen("sedesabonner.png", confidence = 0.9)
                                    if coo_sedesabonner is not None:
                                        pyautogui.click(coo_sedesabonner)
                                        time.sleep(1)
                                    else:
                                        time.sleep(1)
                                else:
                                    pyautogui.scroll(-100)
                                    time.sleep(2)
                    elif bouclee == nombre:
                        sortir = True
                        print("croix")
                        coo_croix = pyautogui.locateCenterOnScreen("croix.png")
                        if coo_croix is not None:
                            pyautogui.click(coo_croix)
                            sortir = True
                            break
                    else:
                        continue
                if sortir == True:
                    break
            elif keyboard.is_pressed("p"):
                macro=False
            else:
                continue
running.sus(250)


#!/usr/bin/env python3

import html
import random

def main():

    trivia= {
         "category": "Entertainment: Film",
         "type": "multiple",
         "question": "Which of the following is NOT a quote from the 1942 film Casablanca? ",
         "correct_answer": ""Frankly, my dear, I don't give a damn."",
         "incorrect_answers": [
             ""Here's lookin' at you, kid."",
             "“Of all the gin joints, in all the towns, in all the world, she walks into mine…”",
             ""Round up the usual suspects.""
            ]
        }

    print(trivia["question"])

    answers = trivia["incorrect_answers"]
    answers.append(trivia["correct_answer"])
    random.shuffle(answers)

    key = {}
    index = "A"
    for answer in answers:
        print(f"{index}. {html.unescape(answer)}")
        key[index.lower()] = answer
        index = chr(ord(index) + 1)

    guess = input("Guess your answer:\n>")
    if key[guess.lower()] == trivia["correct_answer"]:
        print("Correct!")
    else:
        print("Incorrect.")

if __name__ == "__main__":
    main()


import os
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import pandas as pd
import tweepy
import numpy as np
from transformers import BertTokenizer
import torch
from torch import nn
from transformers import BertModel
from torch.optim import Adam
from tqdm import tqdm
from collections import Counter
import random
import joblib
from sklearn.model_selection import train_test_split
from pathlib import Path

def split_into_512_approx(users, tweet_chunks_per_user, all_info, by_tweet=False):
    """This function will take in a list of users and construct either test,
    validation, or training dataframe.  tweet_chunks_per_user per user specifies how many chunks of tweets
    we wish to include for each user.  Each tweet chunk is a concatenation of tweets by a particular user.
    This function will ensure that no tweet chunk contains more than 500 words, as BERT can only handle
    512 tokens at a time. The chunks will be constructed with the longest tweets first, on the
    assumption that longer tweets would be more likely to contain political messaging.

    We could have run BERT with individual tweets as opposed to tweet chunks, and we did try that
    many times.  We aren't exactly sure why, but chunking the tweets together seemed to produce
    better results and made computation faster.

    This function was constructed so as to ensure that tweets from any particular
    politician only appear in only the test, validation or training set, not some
    combination of the three.
    """
    df_out = pd.DataFrame(columns=['Party', 'Text', 'UserID'])
    num_dem = 0
    num_rep = 0
    counter2 = 0
    for user in users:
        temp_df = all_info.loc[all_info['UserID'] == user]
        if temp_df['Party'].iloc[0] == 'Republican Party':
            num_rep += 1
        if temp_df['Party'].iloc[0] == 'Democratic Party':
            num_dem += 1
        max_indexes = []
        temp_texts = list(temp_df['Text'])
        lengths = np.zeros(len(temp_texts))
        for i in range(0, len(temp_texts)):
            lengths[i] = len(temp_texts[i].split(' '))
        for i in range(0, len(temp_texts)):
            temp_max_indi = lengths.argmax()
            lengths[temp_max_indi] = 0
            max_indexes.append(temp_max_indi)
        counter = 0
        big_counter = 0
        working_string = ''
        for index in max_indexes:
            data = temp_df['Text'].iloc[index]
            if counter >= tweet_chunks_per_user:
                break
            if by_tweet is True:
                df_out = df_out.append({'Party': temp_df['Party'].iloc[0], 'Text': data, 'UserID': user}, ignore_index=True)
                working_string = ''
                counter += 1
            if (len((working_string + ' ' + data).split(' ')) > 500):
                df_out = df_out.append({'Party': temp_df['Party'].iloc[0], 'Text': working_string, 'UserID': user}, ignore_index=True)
                working_string = ''
                counter += 1
            else:
                working_string = working_string + ' ' + data
                counter2 += 1
    return df_out

tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
labels = {'Democratic Party':0,'Republican Party':1}

# Dataset class
class Dataset(torch.utils.data.Dataset):

    def __init__(self, df):

        self.labels = [labels[label] for label in df['Party']]
        # I changed max_length to 70 here. Was 512.
        self.texts = [tokenizer(text,
                               padding='max_length', max_length = 70, truncation=True,
                                return_tensors="pt") for text in df['Text']]

    def classes(self):
        return self.labels

    def __len__(self):
        return len(self.labels)

    def get_batch_labels(self, idx):
        # Fetch a batch of labels
        return np.array(self.labels[idx])

    def get_batch_texts(self, idx):
        # Fetch a batch of inputs
        return self.texts[idx]

    def __getitem__(self, idx):

        batch_texts = self.get_batch_texts(idx)
        batch_y = self.get_batch_labels(idx)

        return batch_texts, batch_y

class BertClassifier(nn.Module):

    def __init__(self, dropout=0.5):

        super(BertClassifier, self).__init__()

        self.bert = BertModel.from_pretrained('bert-base-cased')
        self.dropout = nn.Dropout(dropout)
        self.linear = nn.Linear(768, 2)
        self.relu = nn.ReLU()

    def forward(self, input_id, mask):

        _, pooled_output = self.bert(input_ids= input_id, attention_mask=mask,return_dict=False)
        dropout_output = self.dropout(pooled_output)
        linear_output = self.linear(dropout_output)
        final_layer = self.relu(linear_output)

        return final_layer

def train(model, train_data, val_data, learning_rate, epochs):

    train, val = Dataset(train_data), Dataset(val_data)
    # batch_size = 2 is what produced the best results for us.
    # Increasing batch_size i.e. how many attention head calculations
    # before recalculating embeddings did make the code go faster,
    # but tended to affect performance.
    train_dataloader = torch.utils.data.DataLoader(train, batch_size=2, shuffle=True)
    val_dataloader = torch.utils.data.DataLoader(val, batch_size=2)

    use_cuda = torch.cuda.is_available()
    device = torch.device("cuda" if use_cuda else "cpu")

    criterion = nn.CrossEntropyLoss()
    optimizer = Adam(model.parameters(), lr= learning_rate)

    if use_cuda:

            model = model.cuda()
            criterion = criterion.cuda()

    for epoch_num in range(epochs):

            total_acc_train = 0
            total_loss_train = 0

            for train_input, train_label in tqdm(train_dataloader):

                train_label = train_label.to(device)
                mask = train_input['attention_mask'].to(device)
                input_id = train_input['input_ids'].squeeze(1).to(device)

                output = model(input_id, mask)

                batch_loss = criterion(output, train_label.long())
                total_loss_train += batch_loss.item()

                acc = (output.argmax(dim=1) == train_label).sum().item()
                total_acc_train += acc

                model.zero_grad()
                batch_loss.backward()
                optimizer.step()

            total_acc_val = 0
            total_loss_val = 0

            with torch.no_grad():

                for val_input, val_label in val_dataloader:

                    val_label = val_label.to(device)
                    mask = val_input['attention_mask'].to(device)
                    input_id = val_input['input_ids'].squeeze(1).to(device)

                    output = model(input_id, mask)

                    batch_loss = criterion(output, val_label.long())
                    total_loss_val += batch_loss.item()

                    acc = (output.argmax(dim=1) == val_label).sum().item()
                    total_acc_val += acc

            print(
                f'Epochs: {epoch_num + 1} | Train Loss: {total_loss_train / len(train_data): .3f} \
                | Train Accuracy: {total_acc_train / len(train_data): .3f} \
                | Val Loss: {total_loss_val / len(val_data): .3f} \
                | Val Accuracy: {total_acc_val / len(val_data): .3f}')

# Note on hyperparameters: EPOCHS=5 and LR (learning rate) = 1e-6
# seems to be about right.  More EPOCHS results in overfitting with the
# size of data we were running with.  Increasing learning rate
# makes the results unstable.
EPOCHS = 5
model = BertClassifier()
LR = 1e-6

# Evaluate the model using testing data
def evaluate(model, test_data, user_IDs, save_results=False):

    test = Dataset(test_data)

    test_dataloader = torch.utils.data.DataLoader(test, batch_size=2)

    use_cuda = torch.cuda.is_available()
    device = torch.device("cuda" if use_cuda else "cpu")

    if use_cuda:

        model = model.cuda()

    total_acc_test = 0
    test_labels = []
    test_prediction = []
    correct_or_no = []
    counter = 0
    with torch.no_grad():

        for test_input, test_label in test_dataloader:
            test_label = test_label.to(device)
            test_labels.append(test_label)
            mask = test_input['attention_mask'].to(device)

            input_id = test_input['input_ids'].squeeze(1).to(device)
            output = model(input_id, mask)
            acc = (output.argmax(dim=1) == test_label).sum().item()
            if acc == 0:
                correct_or_no.append('no')
            else:
                correct_or_no.append('yes')
            for prediction in output.argmax(dim=1).flatten().tolist():
                test_prediction.append(prediction)
            total_acc_test += acc
            counter += 1
    test_data['UserID'] = user_IDs
    test_data['Predictions'] = test_prediction
    print(f'Test Accuracy: {total_acc_test / len(test_data): .3f}')

    if not save_results:
        return test_data
    else:
        test_data.to_csv(Path('Data/Raw_BERT_results/no_chunk_2_13_23.csv'))

def main():

    # First we balance the data set.
    df = pd.read_csv(Path('Data/text_party_IDs.csv'))
    temp_df_dem = df.loc[df['Party'] == 'Democratic Party']
    temp_df_rep = df.loc[df['Party'] == 'Republican Party']
    dem_list = list(set(temp_df_dem['UserID']))
    rep_list = list(set(temp_df_rep['UserID']))
    dem_list = random.sample(dem_list, len(rep_list))

    # Divide training/validation/test sets s.t. each has an equal number of dems and reps. 50/30/20 train/val/test split
    train_dems, test_dems = train_test_split(dem_list, test_size=int(.5*len(dem_list)))
    validation_dems, test_dems = train_test_split(test_dems, test_size=int(.4*len(test_dems)))
    train_reps, test_reps = train_test_split(rep_list, test_size=int(.5*len(rep_list)))
    validation_reps, test_reps = train_test_split(test_reps, test_size=int(.4*len(test_reps)))

    train_users = train_dems + train_reps
    validation_users = validation_dems + validation_reps
    test_users = test_dems + test_reps
    random.shuffle(train_users)
    random.shuffle(validation_users)
    random.shuffle(test_users)

    # call the function to construct training/val/test sets
    # on our lists of User IDs corresponding to each.
    df_train = split_into_512_approx(train_users, 73, df, by_tweet=True)
    df_val = split_into_512_approx(validation_users, 73, df, by_tweet=True)
    df_test = split_into_512_approx(test_users, 73, df, by_tweet=True)
    df_train.to_csv(Path('see_running_data/no_chunk_2_16_train.csv'))
    df_val.to_csv(Path('see_running_data/no_chunk_2_16_val.csv'))
    df_test.to_csv(Path('see_running_data/no_chunk_2_16_test.csv'))

    # Drop User IDs, save the test set IDs for evaluation.
    df_train.drop('UserID', axis=1)
    df_val.drop('UserID', axis=1)
    user_ID_add_later = list(df_test['UserID'])
    df_test.drop('UserID', axis=1)

    train(model, df_train, df_val, LR, EPOCHS)
    filename = 'trained_model_no_chunk_2_13_23.joblib'
    # serialize and save model
    joblib.dump(model, filename)
    evaluate(model, df_test, user_ID_add_later, save_results=True)
    print(LR, EPOCHS)

if __name__ == "__main__":
    main()