from __future__ import annotations

import logging
import pathlib
from dataclasses import dataclass
from datetime import datetime
from typing import cast

from vdk.api.job_input import IJobArguments
from vdk.api.plugin.core_hook_spec import JobRunHookSpecs
from vdk.api.plugin.hook_markers import hookimpl
from vdk.internal.builtin_plugins.config.vdk_config import LOG_EXCEPTION_FORMATTER
from vdk.internal.builtin_plugins.run.execution_results import ExecutionResult
from vdk.internal.builtin_plugins.run.execution_results import StepResult
from vdk.internal.builtin_plugins.run.execution_state import ExecutionStateStoreKeys
from vdk.internal.builtin_plugins.run.file_based_step import JobFilesLocator
from vdk.internal.builtin_plugins.run.file_based_step import StepFuncFactory
from vdk.internal.builtin_plugins.run.file_based_step import TYPE_PYTHON
from vdk.internal.builtin_plugins.run.file_based_step import TYPE_SQL
from vdk.internal.builtin_plugins.run.job_context import JobContext
from vdk.internal.builtin_plugins.run.job_input_error_classifier import whom_to_blame
from vdk.internal.builtin_plugins.run.run_status import ExecutionStatus
from vdk.internal.builtin_plugins.run.step import Step
from vdk.internal.core import errors
from vdk.internal.core.context import CoreContext
from vdk.internal.core.errors import BaseVdkError
from vdk.internal.core.errors import SkipRemainingStepsException
from vdk.internal.core.statestore import CommonStoreKeys

log = logging.getLogger(__name__)

@dataclass
class JobArguments(IJobArguments):
    arguments: dict

    def get_arguments(self) -> dict:
        return self.arguments

class DataJobFactory:
    @staticmethod
    def new_datajob(
        data_job_directory: pathlib.Path | None,
        core_context: CoreContext,
        name: str | None = None,
    ) -> DataJob:
        """
        Create a new data job
        :param data_job_directory: the source code of the data job that will be executed
        :param core_context: Core context of the CLI. Upon run , the data job will span child context to keep its context/state
        :param name: the name of the job. Leave it out and it will be infered from the directory name.
        """
        return DataJob(data_job_directory, core_context, name)

class DataJobDefaultHookImplPlugin:
    """
    Default implementation of main plugin hooks in Data Job Run Cycle.
    Plugins may decorate or replace some of the implementations
    """

    @staticmethod
    @hookimpl(trylast=True)
    def run_step(context: JobContext, step: Step) -> StepResult:
        start_time = datetime.utcnow()
        exception = None
        details = None
        blamee = None

        try:
            log.debug(f"Processing step {step.name} ...")
            step_executed = step.runner_func(step, context.job_input)
            log.debug("Processing step %s completed successfully" % step.name)
            status = (
                ExecutionStatus.SUCCESS
                if step_executed
                else ExecutionStatus.NOT_RUNNABLE
            )
        except SkipRemainingStepsException as e:
            status = ExecutionStatus.SKIP_REQUESTED
            details = errors.MSG_WHY_FROM_EXCEPTION(e)
            log.debug(
                f"Job execution skipped from step: {step.name}. Because skip_remaining_steps() method "
                + "was invoked"
            )
        except Exception as e:
            status = ExecutionStatus.ERROR
            blamee = whom_to_blame(e, __file__, context.job_directory)
            exception = e
            errors.report(blamee, exception)
            log.warning(f"Processing step {step.name} completed with error.")

        return StepResult(
            name=step.name,
            type=step.type,
            start_time=start_time,
            end_time=datetime.utcnow(),
            status=status,
            details=details,
            exception=exception,
            blamee=blamee,
        )

    @staticmethod
    @hookimpl(trylast=True)
    def run_job(context: JobContext) -> ExecutionResult:
        """The script that runs the actual run of the data job.
        It executes the provided steps starting from context.steps in sequential order
        """
        start_time = datetime.utcnow()
        exception = None
        blamee = None
        steps = context.step_builder.get_steps()
        step_results = []

        if len(steps) == 0:
            errors.report_and_throw(
                errors.UserCodeError(
                    "Data Job execution has failed.",
                    "Data Job has no steps.",
                    "Data job execution will not continue.",
                    "Please include at least 1 valid step in your Data Job. Also make sure you are passing the correct data job directory.",
                )
            )

        execution_status = ExecutionStatus.SUCCESS
        for current_step in steps:
            step_start_time = datetime.utcnow()
            res = None
            try:
                res = context.core_context.plugin_registry.hook().run_step(
                    context=context, step=current_step
                )
            except BaseException as e:
                blamee = whom_to_blame(e, __file__, context.job_directory)
                exception = e
                errors.report(blamee, exception)
                log.warning(
                    f"Processing step {current_step.name} completed with error."
                )
                res = StepResult(
                    name=current_step.name,
                    type=current_step.type,
                    start_time=step_start_time,
                    end_time=datetime.utcnow(),
                    status=ExecutionStatus.ERROR,
                    details=errors.MSG_WHY_FROM_EXCEPTION(e),
                    exception=e,
                    blamee=blamee,
                )

            step_results.append(res)
            # errors.clear_intermediate_errors()  # step completed successfully, so we can forget errors
            if res.status == ExecutionStatus.ERROR:
                execution_status = ExecutionStatus.ERROR
                exception = res.exception
                break
            if res.status == ExecutionStatus.SKIP_REQUESTED:
                # We keep the status as Success, but we skip all remaining steps
                break
        execution_result = ExecutionResult(
            context.name,
            context.core_context.state.get(CommonStoreKeys.EXECUTION_ID),
            start_time,
            datetime.utcnow(),
            execution_status,
            step_results,
            exception,
            blamee,
        )
        return execution_result

    @staticmethod
    @hookimpl
    def initialize_job(context: JobContext):
        # TODO: consider split into collect_steps hooks for better clarity and ease.
        # though let's first gather some data on how useful such new hooks would be.
        if context.job_directory is None:
            log.info(
                "Data Job directory is not specified. Default job initialization will be skipped."
            )
            return

        file_locator: JobFilesLocator = JobFilesLocator()
        script_files = file_locator.get_script_files(context.job_directory)

        for file_path in script_files:
            if file_path.name.lower().endswith(".sql"):
                step = Step(
                    name=file_path.name,
                    type=TYPE_SQL,
                    runner_func=StepFuncFactory.run_sql_step,
                    file_path=file_path,
                    job_dir=context.job_directory,
                )
            elif file_path.name.lower().endswith(".py"):
                # TODO: check for run method.
                step = Step(
                    name=file_path.name,
                    type=TYPE_PYTHON,
                    runner_func=StepFuncFactory.run_python_step,
                    file_path=file_path,
                    job_dir=context.job_directory,
                )
            else:
                log.info("Skipping file as it is not a valid job step: %s" % file_path)
                continue
            context.step_builder.add_step(step)

    @staticmethod
    @hookimpl
    def finalize_job(context: JobContext):
        pass

class DataJob:
    """
    Object representing a data job.
    Data Job is abstraction representing definition of a data job set by data engineer.
    Data Job is a sequence of steps executed in a certain order.
    Data JOb run cycle is encapsulated by run method.

    Prefer to use DataJobFactory to create new data job.
    """

    def __init__(
        self,
        data_job_directory: pathlib.Path | None,
        core_context: CoreContext,
        name: str | None = None,
    ):
        if data_job_directory is None and name is None:
            raise ValueError(
                "Cannot initialize DataJob. "
                "At least one of data job directory or data job name need to be set. "
            )
        self._name = data_job_directory.name if name is None else name
        self._data_job_directory = data_job_directory
        """
        We need to create child context which will contain only for this job execution.
        This is since we want to have multiple job executions within same process (for example templates executions)
        """
        self._core_context = core_context.create_child_context()
        self._plugin_hook = cast(
            JobRunHookSpecs, self._core_context.plugin_registry.hook()
        )

    @property
    def name(self):
        return self._name

    # TODO: this also can be a hook - e.g job run_cycle_algorithm
    def run(
        self, args: dict = None, template_name: str | None = None
    ) -> ExecutionResult:
        """
        This is basic implementation of Data Job run(execution) cycle algorithm.
        All stages are pluggable as hooks.
         * Initialize - Initialize job's main functionalities -e.g database connections,logging,collecting steps, etc.
         * Run Job -Takes care of starting and running a data job
         * Run steps - run the actual steps. This is where hte user code will be invoked.
         * Finalize - after the job finishes, do any finalization -clean up, send monitoring, etc.
        """
        if args is None:
            args = {}
        if template_name:
            self._core_context.state.set(
                ExecutionStateStoreKeys.TEMPLATE_NAME, template_name
            )

        if not self._core_context.plugin_registry.has_plugin(
            DataJobDefaultHookImplPlugin.__name__
        ):
            self._core_context.plugin_registry.load_plugin_with_hooks_impl(
                DataJobDefaultHookImplPlugin(), DataJobDefaultHookImplPlugin.__name__
            )

        from vdk.internal.builtin_plugins.templates.template_impl import TemplatesImpl

        job_context = JobContext(
            name=self._name,
            job_directory=self._data_job_directory,
            core_context=self._core_context,
            job_args=JobArguments(args),
            templates=TemplatesImpl(
                job_name=self.name,
                core_context=self._core_context,
                template_name=template_name,
            ),
        )
        self._plugin_hook.initialize_job(context=job_context)

        start_time = datetime.utcnow()
        step_results = []
        try:
            execution_result = self._plugin_hook.run_job(context=job_context)
            if (
                execution_result.exception
                and execution_result.status == ExecutionStatus.ERROR
            ):
                step_results = execution_result.steps_list
                raise execution_result.exception
            return execution_result
        except BaseException as ex:
            if isinstance(ex, BaseVdkError):
                config = self._core_context.configuration
                if config.get_value(LOG_EXCEPTION_FORMATTER) == "pretty":
                    ex._format(errors.pretty_vdk_error_formatter)
                else:
                    ex._format(errors.plain_vdk_error_formatter)
            blamee = whom_to_blame(ex, __file__, job_context.job_directory)
            errors.report(blamee, ex)
            log.warning(f"Data Job {self._name} completed with error.")
            log.exception(ex)
            execution_result = ExecutionResult(
                self._name,
                self._core_context.state.get(CommonStoreKeys.EXECUTION_ID),
                start_time,
                datetime.utcnow(),
                ExecutionStatus.ERROR,
                step_results,
                ex,
                blamee,
            )
            return execution_result
        finally:  # TODO: we should pass execution result to finalize_job somehow ...
            self._plugin_hook.finalize_job(context=job_context)


import numpy as np
import vtk
import pyvista as pv
from ..common import readBinaryArray, Profile, vCutter, unstructuredToPoly
from ..numtools import makeRotationTensor
import warnings
from typing import Callable, Optional

def binaryVelbar(velbar_path) -> np.ndarray:
    """Get velbar array from binary file.

    Wrapping around vpt.readBinaryArray. Assumes that the number of columns in
    the array is 5.

    Parameters
    ----------
    velbar_path : Path
        Path to velbar file.
    """
    return readBinaryArray(velbar_path, 5)

def binaryStsbar(stsbar_path) -> np.ndarray:
    """Get stsbar array from binary file.

    Wrapping around vpt.readBinaryArray. Assumes that the number of columns in
    the array is 6.

    Parameters
    ----------
    stsbar_path : Path
        Path to stsbar file.
    """
    return readBinaryArray(stsbar_path, 6)

def calcReynoldsStresses(stsbar_array, velbar_array, conservative_stresses=False) -> np.ndarray:
    """Calculate Reynolds Stresses from velbar and stsbar data.

    Parameters
    ----------
    stsbar_array : ndarray
        Array of stsbar values
    velbar_array : ndarray
        Array of velbar values
    conservative_stresses : bool
        Whether the stsbar file used the
        'Conservative Stresses' option (default:False)

    Returns
    -------
    numpy.ndarray
    """
    if conservative_stresses:
        ReyStrTensor = np.empty((stsbar_array.shape[0], 6))
        ReyStrTensor[:,0] = stsbar_array[:,3] - stsbar_array[:,0]**2
        ReyStrTensor[:,1] = stsbar_array[:,4] - stsbar_array[:,1]**2
        ReyStrTensor[:,2] = stsbar_array[:,5] - stsbar_array[:,2]**2
        ReyStrTensor[:,3] = stsbar_array[:,6] - stsbar_array[:,0]*stsbar_array[:,1]
        ReyStrTensor[:,4] = stsbar_array[:,7] - stsbar_array[:,1]*stsbar_array[:,2]
        ReyStrTensor[:,5] = stsbar_array[:,8] - stsbar_array[:,0]*stsbar_array[:,2]
        # ReyStrTensor[:,5] = np.zeros_like(ReyStrTensor[:,5])
    else:
        ReyStrTensor = np.empty((stsbar_array.shape[0], 6))

        ReyStrTensor[:,0] = stsbar_array[:,0] - velbar_array[:,1]**2
        ReyStrTensor[:,1] = stsbar_array[:,1] - velbar_array[:,2]**2
        ReyStrTensor[:,2] = stsbar_array[:,2] - velbar_array[:,3]**2
        ReyStrTensor[:,3] = stsbar_array[:,3] - velbar_array[:,1]*velbar_array[:,2]
        ReyStrTensor[:,4] = stsbar_array[:,4] - velbar_array[:,1]*velbar_array[:,3]
        ReyStrTensor[:,5] = stsbar_array[:,5] - velbar_array[:,2]*velbar_array[:,3]

    return ReyStrTensor

def calcWallShearGradient(wall) -> np.ndarray:
    """Calcuate the shear gradient at the wall

    Wall shear gradient is defined as the gradient of the velocity tangent to
    the wall in the wall-normal direction. To calculate wall shear stress,
    multiply by mu.

    If the wall normal unit vector is taken to be n and the
    gradient of velocity is e_ij, then the wall shear gradient is:

        (delta_ik - n_k n_i) n_j e_kj

    where n_j e_kj is the "traction" vector at the wall. See post at
    https://www.jameswright.xyz/post/wall_shear_gradient_from_velocity_gradient/
    for derivation of method.

    Parameters
    ----------
    wall : pv.UnstructuredGrid
        Wall cells and points

    Returns
    -------
    numpy.ndarray
    """

    if 'Normals' not in wall.array_names:
        raise RuntimeError('The wall object must have a "Normals" field present.')
    if 'gradient' not in wall.array_names:
        raise RuntimeError('The wall object must have a "gradient" field present.')

        # reshape the gradient such that is is an array of rank 2 tensors
    grad_tensors = wall['gradient'].reshape(wall['gradient'].shape[0], 3, 3)

    traction_vector = np.einsum('pkj,pj->pk', grad_tensors, wall['Normals'])
    del_ik_nkni = np.identity(3) - np.einsum('pk,pi->pki', wall['Normals'], wall['Normals'])
    wall_shear_gradient = np.einsum('pik,pk->pi', del_ik_nkni, traction_vector)

    return wall_shear_gradient

def calcCf(wall, Uref, nu, rho, plane_normal='XY') -> np.ndarray:
    """Calcuate the Coefficient of Friction of the wall

    Uses vpt.calcWallShearGradient to get du/dn, then uses input values to
    calculate Cf using:

        C_f = T_w / (0.5 * rho * Uref^2)

    Parameters
    ----------
    wall : pv.PolyData
        Wall cells and points
    Uref : float
        Reference velocity
    nu : float
        Kinematic viscosity
    rho : float
        Density
    plane_normal : {'XY', 'XZ', 'YZ'}, optional
        Plane that the wall lies on. The shear stress vector will be projected
        onto it. (default: 'XY')

    Returns
    -------
    numpy.ndarray
    """
    mu = nu * rho

    wall_shear_gradient = calcWallShearGradient(wall)

    if plane_normal.lower() == 'xy':
        plane_normal = np.array([0,0,1])
        streamwise_vectors = np.array([wall['Normals'][:,1],
                                       -wall['Normals'][:,0],
                                       np.zeros_like(-wall['Normals'][:,0])]).T
    elif plane_normal.lower() == 'xz':
        plane_normal = np.array([0,1,0])
        streamwise_vectors = np.array([wall['Normals'][:,2],
                                       np.zeros_like(-wall['Normals'][:,0]),
                                       -wall['Normals'][:,0]]).T
    elif plane_normal.lower() == 'yz':
        plane_normal = np.array([1,0,0])
        streamwise_vectors = np.array([wall['Normals'][:,2],
                                       np.zeros_like(-wall['Normals'][:,0]),
                                       -wall['Normals'][:,0]]).T

        # Project tangential gradient vector onto the chosen plane using n x (T_w x n)
    Tw = mu * np.cross(plane_normal[None,:],
                       np.cross(wall_shear_gradient, plane_normal[None,:]))
    Tw = np.einsum('ej,ej->e', streamwise_vectors, Tw)

    Cf = Tw / (0.5*rho*Uref**2)
    return Cf

def compute_vorticity(dataset, scalars, vorticity_name='vorticity'):
    """(DEPRECATED) Compute Vorticity, only needed till my PR gets merged

     .. deprecated::
         Use the `compute_derivative` method in pyvista's `UnstructuredGrid` class
     """

    warnings.warn("This function is deprecated. Use the 'compute_derivative'"
                  " method in pyvista's 'UnstructuredGrid' class" , FutureWarning)
    alg = vtk.vtkGradientFilter()

    alg.SetComputeVorticity(True)
    alg.SetVorticityArrayName(vorticity_name)

    _, field = dataset.get_array(scalars, preference='point', info=True)
    # args: (idx, port, connection, field, name)
    alg.SetInputArrayToProcess(0, 0, 0, field.value, scalars)
    alg.SetInputData(dataset)
    alg.Update()
    return pv.filters._get_output(alg)

def sampleDataBlockProfile(dataBlock, line_walldists, pointid=None,
                           cutterobj=None, normal=None,
                           choosePoint: Optional[Callable[...,int]] = None) -> Profile:
    """Sample data block over a wall-normal profile

    Given a dataBlock containing a 'grid' and 'wall' block, this will return a
    PolyData object that samples 'grid' at the wall distances specified in
    line_walldists. This assumes that the 'wall' block has a field named
    'Normals' containing the wall-normal vectors.

    The location of the profile is defined by either the index of a point in
    the 'wall' block or by specifying a vtk implicit function (such as
    vtk.vtkPlane) that intersects the 'wall' object. The latter uses the
    vtk.vtkCutter filter to determine the intersection.

    Parameters
    ----------
    dataBlock : pv.MultiBlock
        MultiBlock containing the 'grid' and 'wall' objects
    line_walldists : numpy.ndarray
        The locations normal to the wall that should be sampled and returned.
        Locations are expected to be in order.
    pointid : int, optional
        Index of the point in 'wall' where the profile should be taken.
        (default: None)
    cutterobj : vtk.vtkPlane, optional
        VTK object that defines the profile location via intersection with the
        'wall'
    normal : numpy.ndarray, optional
        If given, use this vector as the wall normal.
    choosePoint : Callable(pv.PolyData) -> int, optional
        function which selects which point to return from the cutter if multiple are found

    Returns
    -------
    vtkpytools.Profile
    """

    wall = dataBlock['wall']

    if 'Normals' not in wall.array_names:
        raise RuntimeError('The wall object must have a "Normals" field present.')
    if not (isinstance(pointid, int) ^ bool(cutterobj) ): #xnor
        raise RuntimeError('Must provide either pointid or cutterobj.')

    if isinstance(pointid, int):
        wallnormal = wall['Normals'][pointid,:] if normal is None else normal
        wallnormal = np.tile(wallnormal, (len(line_walldists),1))

        sample_points = line_walldists[:, None] * wallnormal
        sample_points += wall.points[pointid]

        sample_line = pv.lines_from_points(sample_points)
        sample_line = sample_line.sample(dataBlock['grid'])
        sample_line['WallDistance'] = line_walldists

    else:
        cutterout = vCutter(wall, cutterobj)
        if cutterout.points.shape[0] != 1:
            if choosePoint == None:
                raise RuntimeError('vCutter resulted in {:d} points instead of 1. Use choosePoint to clarify which point should be used.'.format(
                    cutterout.points.shape[0]))
            else:
                index = choosePoint(cutterout)
                cutterout = unstructuredToPoly(cutterout.extract_points(index))

        wallnormal = cutterout['Normals'] if normal is None else normal

        sample_points = line_walldists[:, None] * wallnormal
        sample_points += cutterout.points

        sample_line = pv.lines_from_points(sample_points)
        sample_line = sample_line.sample(dataBlock['grid'])
        sample_line['WallDistance'] = line_walldists

        sample_line = Profile(sample_line)
        sample_line.setWallDataFromPolyDataPoint(cutterout)

    return sample_line

def wallAlignRotationTensor(wallnormal, cart_normal, plane='xy') -> np.ndarray:
    """Create rotation tensor for wall alligning quantities

    For 2D xy plane and streamwise x, cart_normal should be the y unit vector.

    Parameters
    ----------
    wallnormal : numpy.ndarray
        The normal vector at the wall
    cart_normal : numpy.ndarray
        The Cartesian equivalent to the wall normal. If the wall were "flat",
        this would be the wall normal vector.
    plane : str
        2D plane to rotate on, from 'xy', 'xz', 'yz'. (Default is 'xy')
    """

    if plane.lower() == 'xy':   rotation_axis = np.array([0, 0, 1])
    elif plane.lower() == 'xz': rotation_axis = np.array([0, 1, 0])
    elif plane.lower() == 'yz': rotation_axis = np.array([1, 0, 0])

    theta = np.arccos(np.dot(wallnormal, cart_normal))
    # Determine whether clockwise or counter-clockwise rotation
    rotation_cross = np.cross(cart_normal, cart_normal - wallnormal)
    if np.dot(rotation_cross, rotation_axis) < 0: theta *= -1

    return makeRotationTensor(rotation_axis, theta)


i = int(input())
phonebook = dict()

for _ in range(i):
    entry = list(input().split())
    phonebook[entry[0]] = entry[1]

while True:
    # We don't know in advance how many queries will come.
    # Therefore, we have to 'try'.
    try:
        query = input()
    except:
        break

    if query in phonebook:
        print(f"{query}={phonebook[query]}")
    else:
        print("Not found")


from collections import deque

def backtracking_with_mac(number_of_nodes, graph, k_coloring):
    """Backtracking with forward checking algorithm base function"""
    # Define domain for each node with all possible colors at first.
    color_assignment = [[x for x in range(k_coloring)]] * number_of_nodes
    # Start with the first node
    return backtracking_with_mac_rec(0, number_of_nodes, graph, color_assignment, k_coloring)

def backtracking_with_mac_rec(index, number_of_nodes, graph, color_assignment, k_coloring):
    """Implements backtracking with forward checking algorithm using recursion."""
    # Base case: if all nodes finished return success
    if index == number_of_nodes:
        return True, color_assignment

    color_domain_of_this_node = color_assignment.copy()
    for color in color_assignment[index]:
        # Assign the color the node
        color_assignment[index] = [color]
        # Forward checking step
        inferences, mac_color_assignment = maintaining_arc_consistency(graph, color_assignment, number_of_nodes)
        if inferences:
            # Set the new color assignment to the values obtained from forward checking
            color_assignment = mac_color_assignment
            # Move to next nodes
            solution_found, bt_color_assignment = \
                backtracking_with_mac_rec(index+1, number_of_nodes, graph, color_assignment, k_coloring)
            # If solution found return it
            if solution_found:
                return True, bt_color_assignment
            else:
                color_assignment = color_domain_of_this_node.copy()
    # This means that there is no solution exists in this path.
    return False, color_assignment

def maintaining_arc_consistency(graph, color_assignment, number_of_nodes):
    """This function extracts every possible arc and add it to the queue and check it. """
    # Initializing a queue
    q = deque()
    # Extract all possible arc and them to queue
    for node in range(number_of_nodes):
        for neighbor in graph[node]:
            q.append([node, neighbor])

    # Loop on all arcs in the queue
    while q:
        # Extract first arc into head and tail
        arc = q.popleft()
        tail, head = arc[0], arc[1]
        revised, revised_color_assignment = revise(color_assignment, tail, head)
        # If no colors left in the tail of the arc.
        if len(revised_color_assignment[tail]) == 0:
            return False, []
        # If the arc has been revised then we should add all the arcs that have tail node as its head.
        if revised:
            color_assignment = revised_color_assignment
            # For all the neighbor of tail node add their arcs(in which neighbor is tail now and tail node is head)
            for neighbor in graph[tail]:
                # Don't add the head node as the tail
                if neighbor != head:
                    arc = [neighbor, tail]
                    if not (arc in q):
                        q.append(arc)

    # All arcs are consistent
    return True, color_assignment

def revise(color_assignment, tail, head):
    """This function apply arc consistency for the given arc and return true if the tail node has been changed."""
    revised = False
    # Arc: node(Tail) -> neighbor(Head).

    # If neighbor has one color then I should remove it from tail color domain if tail also have it.
    if len(color_assignment[head]) == 1:
        if color_assignment[head][0] in color_assignment[tail]:
            # This means that the tail has the color in the head so we should remove it.
            # Remove color from the tail domain.
            temp_color_domain = color_assignment[tail].copy()
            temp_color_domain.remove(color_assignment[head][0])
            color_assignment[tail] = temp_color_domain
            revised = True
    return revised, color_assignment


#!/usr/bin/env python

import sys
from collections import defaultdict
from typing import Dict, List

def make_chain(adapters: List[int]) -> int:
    adapters = sorted(adapters)
    output = 0
    device = adapters[-1] + 3
    jolts: Dict[int, int] = defaultdict(int)
    for adapter in adapters:
        delt = adapter - output
        jolts[delt] += 1
        output = adapter
    jolts[device - output] += 1

    return jolts[1] * jolts[3]

def solve(raw: List[str]) -> int:
    return make_chain([int(line) for line in raw])

def main() -> None:
    input = [line.strip() for line in sys.stdin.readlines()]
    print(solve(input))

if __name__ == "__main__":
    main()


import random
import time

st = time.time()
loops = 0
for num in range(1, 10000):
    is_fluky = 0
    for factor in range(1, num):
        loops += 1
        if num % factor == 0:
            random.seed(factor)
            is_fluky += random.randint(1, num)
    if is_fluky == num:
        print("Fluky Number: " + str(num))
et = time.time()
print("total time elapsed is: " + str(et-st))
print(str(loops) + " total loops run")


# https://programmers.co.kr/learn/courses/30/lessons/42883

def solution(number, k):
  number_list = list(map(str, str(number)))

  for i in range(k):
    number_list.remove(min(number_list))

  answer = ''.join(number_list)

  return answer
# 리스트에서 가장 작은 수만 제거한 후 리턴 -> 가장 작은 수 제거보다 가장 큰 수를 만들어야 한다
# 1, 2번 예시 문제는 통과 되지만 3번은 통과되지 않음

def solution2(number, k):
  answer = [number[0]]

  for i in number[1:]:
    while len(answer) > 0 and answer[-1] < i and k > 0:
      k -= 1
      answer.pop()
    answer.append(i)

  if k != 0:
    answer = answer[:-k]

  return ''.join(answer)
# https://eda-ai-lab.tistory.com/465
# 스택을 사용해서 조건에 맞는 값만 넣는 방법이 있다.


# Django settings for example project.

import sys
from os.path import abspath, dirname, join

PROJECT_DIR = abspath(dirname(__file__))
grandparent = abspath(join(PROJECT_DIR, '..'))
for path in (grandparent, PROJECT_DIR):
    if path not in sys.path:
        sys.path.insert(0, path)

DEBUG = True

ADMINS = (  # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': join(PROJECT_DIR, 'local.db'),
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'UTC'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

USE_I18N = False
USE_L10N = False

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = join(PROJECT_DIR, 'media')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'

STATIC_ROOT = ''
STATIC_URL = '/static/'

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    #    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
        ],
        'OPTIONS': {
            'context_processors': [
                # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
                # list if you haven't customized them:
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.request',
                'django.contrib.messages.context_processors.messages',
            ],
            'loaders':
                ('django.template.loaders.filesystem.Loader',
                 'django.template.loaders.app_directories.Loader',)
        },
    },
]

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'zke83e4zrq*3!&*)&oqx0cq18t3*oc@z3u*u@1w%1&c0=rihp#'

MIDDLEWARE = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'example.urls'

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'sample',
    'image_helper.tests.test_app.apps.TestAppConfig',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}


import hashlib

b58 = ('123456789' +
		'ABCDEFGHJKLMNPQRSTUVWXYZ' +
		'abcdefghijkmnopqrstuvwxyz')
def toBase58(n):
	result = ''
	while n > 0:
		result = b58[n%58] + result
		n /= 58
	return result

def toBase256(n):
	result = ''
	n = int(n,16)
	while n > 0:
		result = chr(n%256) + result
		n /= 256
	return result

def OP_HASH256(s):
	x=hashlib.sha256(s)
	y=hashlib.sha256(x.digest())
	return y.hexdigest()

def OP_HASH160(s):
	x = hashlib.sha256(s)
	y = hashlib.new('ripemd160')
	y.update(x.digest())
	return y.hexdigest()

def toBase58Check(version,payload):
	extended = chr(version) + toBase256(payload)
	checksum = OP_HASH256(extended)[:8]
	extended16 = str(version)+payload+checksum
	n_leading_zeros = 1+next((i for i,x in enumerate(payload) if '0'!=x),0)/2
	result = n_leading_zeros*'1' + toBase58(int(str(version)+payload+checksum,16))
	return result

class OutputTransaction:
	def __init__(self,value,script):
		self.value = value
		if script[:6] == '76a914':
			self.template = 'public key hash'
			self.address = toBase58Check(0,script[6:46])
		elif script[:2] == '41':
			self.template = 'public key'
			public_key_hash = OP_HASH160(toBase256(script[2:2+65*2]))
			self.address = toBase58Check(0,public_key_hash)
		else:
			self.template = 'other'
			self.address = None

if __name__ == '__main__':
	import numpy as np
	test_addresses = np.loadtxt('head_balances.txt',skiprows=3,usecols=(1,2),dtype='str')
	for hash160,b58check in test_addresses:
		assert b58check == toBase58Check(0,hash160)


import ray
import subprocess
import os
import time

def set_up_s3fs(path: str = "~/results"):
    path = os.path.expanduser(path)
    if os.path.exists(path):
        return
    subprocess.Popen(
        f"rm -rf '{path}' && mkdir -p '{path}' && nohup s3fs tune-experiment-result '{path}' -o iam_role='auto' -o url='https://s3-us-west-2.amazonaws.com' -o nonempty -o dbglevel=info -f -o curldbg &",
        stdout=open(os.path.expanduser("~/s3fs_log"), "a"),
        stderr=subprocess.STDOUT,
        shell=True,
        start_new_session=True)
    time.sleep(2)
    import platform
    subprocess.Popen(f"cd '{path}' && touch '{platform.node()}'",
                     stdout=subprocess.DEVNULL,
                     stderr=subprocess.STDOUT,
                     shell=True)

def run_on_every_ray_node(func, **kwargs):
    nodes = {k for k in ray.cluster_resources() if "node:" in k}
    remote_func = ray.remote(func)
    refs = []
    for node in nodes:
        refs.append(
            remote_func.options(num_cpus=0, resources={
                node: 1
            }).remote(**kwargs))
    return ray.get(refs)


# coding=utf-8
from datetime import date
from tempfile import TemporaryDirectory
from os import path

from django.core.management import BaseCommand
from django.core.files import File
from django.db.models import Sum, Q

from documentmanagement.utils import pdflatex
from usermanagement.utils import get_shackbureau_user

class Command(BaseCommand):

    help = "generate a paper letter for all members without a validated tracking code"

    def add_arguments(self, parser):
        parser.add_argument('year', type=int)
        parser.add_argument('member_id', type=int)

    def handle(self, *args, **options):
        from usermanagement.models import Member, MemberDocument, MemberDocumentTag, AccountTransaction

        template = "documentmanagement/donationreceipt.tex"
        filename = "donationreceipt_{year}_{id:04d}_{surname}_{name}"
        additional_files = (('static/img/logo_shack_brightbg.pdf', 'img/logo_shack_brightbg.pdf'), )

        shackbureau_user = get_shackbureau_user()
        today = date.today()
        tag, created = MemberDocumentTag.objects.get_or_create(tag="Spendenbescheinigung",
                                                               defaults={"created_by": shackbureau_user})

        member_id = options['member_id']
        year = options['year']
        member = Member.objects.get(member_id=member_id)

        amount = AccountTransaction.objects \
            .filter(transaction_type="membership fee") \
            .filter(Q(booking_type="deposit") | Q(booking_type="charge back")) \
            .filter(member=member, due_date__year=year) \
            .aggregate(Sum('amount')).get('amount__sum')

        context = {'address_of_donator': member.get_postal_address(),
                   'amount': amount,
                   'day_of_donation': year,
                   'donation_type': 'allowance in money',
                   'date': today,
                   'place': 'Stuttgart'
                   }
        base_filename = filename.format(year=year,
                                        id=member.member_id,
                                        surname=member.surname,
                                        name=member.name)

        with TemporaryDirectory() as tempdirectory:
            pdf = pdflatex(base_filename=base_filename,
                           template=template,
                           context=context,
                           tempdirectory=tempdirectory,
                           additional_files=additional_files)
            print(pdf)

            with open(pdf, 'rb') as f:
                memberdocument = MemberDocument()
                memberdocument.member = member
                memberdocument.created_by = shackbureau_user
                memberdocument.description = "Spendenbescheinigung {}".format(today.isoformat())
                memberdocument.comment = "autogenerated at {}".format(today.isoformat())
                memberdocument.data_file.save(path.basename(pdf), File(f))
                memberdocument.save()
                memberdocument.tag.add(tag)
        return


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrow
from ipywidgets import interact

# Define the size of the grid
n = 20

# Initialize the grid
x, y = np.meshgrid(np.arange(n), np.arange(n))

# Initialize the directions of the arrows to simulate ferromagnetism
u = np.ones((n, n))
v = np.zeros((n, n))

# Define the zones for the ferromagnetic domains
zones = [
    {"rows": slice(0, n//4), "cols": slice(0, n//2), "angle": 0},
    {"rows": slice(0, n//4), "cols": slice(n//2, n), "angle": np.pi/4},
    {"rows": slice(n//4, n//2), "cols": slice(0, n//2), "angle": np.pi/2},
    {"rows": slice(n//4, n//2), "cols": slice(n//2, n), "angle": 3*np.pi/4},
    {"rows": slice(n//2, 3*n//4), "cols": slice(0, n//2), "angle": np.pi},
    {"rows": slice(n//2, 3*n//4), "cols": slice(n//2, n), "angle": 5*np.pi/4},
    {"rows": slice(3*n//4, n), "cols": slice(0, n//2), "angle": 3*np.pi/2},
    {"rows": slice(3*n//4, n), "cols": slice(n//2, n), "angle": 7*np.pi/4},
]

def plot_arrows(B):
    # Adjust the direction of the arrows based on the zones and applied magnetic field
    for zone in zones:
        u[zone["rows"], zone["cols"]] = np.cos(zone["angle"] + B)
        v[zone["rows"], zone["cols"]] = np.sin(zone["angle"] + B)

    fig, ax = plt.subplots(figsize=(8, 8))

    # Plot the arrows
    for i in range(n):
        for j in range(n):
            arrow = FancyArrow(j, i, u[i, j], v[i, j], color='k', width=0.01)
            ax.add_patch(arrow)

    # Set the limits and labels
    ax.set_xlim(0, n)
    ax.set_ylim(0, n)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_title('Ferromagnetism Simulation with B = {:.2f}'.format(B))

    plt.show()

# Use ipywidgets to add a slider for the applied magnetic field
interact(plot_arrows, B=(0, 2*np.pi, 0.1));


import os
from enum import Enum
from typing import Literal, Mapping, Tuple

import pandas as pd
import pytorch_lightning as pl
import torch
import torchvision
from torch.utils.data import DataLoader, Dataset
from typing_extensions import TypeGuard

class SensitiveAttribute(Enum):
    """All datasets use one or more of these attributes and are binarized in the
    following way. We expect the csv files to have a column with the same name as
    the Key field in the mapping below."""

    sex = {0: "Male", 1: "Female", "Key": "Sex"}
    age = {0: "0-60", 1: "60+", "Key": "Age"}
    race = {0: "White", 1: "Non-White", "Key": "Race"}
    skintype = {0: "Types 1-3", 1: "Types 4-6", "Key": "SkinType"}

# NB, we also expect the csv file to have a column named "Path" with the paths from
# data_dir to images and a column named "binaryLabel" with the disease label

class AvailableDataset(Enum):
    """Register datasets by adding them and their available sensitive attributes here."""

    chexpert = [SensitiveAttribute.sex, SensitiveAttribute.age, SensitiveAttribute.race]
    mimic = [SensitiveAttribute.sex, SensitiveAttribute.age, SensitiveAttribute.race]
    ham10000 = [SensitiveAttribute.sex, SensitiveAttribute.age]
    papila = [SensitiveAttribute.sex, SensitiveAttribute.age]
    fitzpatrick17k = [SensitiveAttribute.skintype]

def is_valid_sensitive_attribute(
    a: SensitiveAttribute, ds: AvailableDataset
) -> TypeGuard[SensitiveAttribute]:
    if a not in ds.value:
        raise ValueError(f"Invalid sensitive attribute {a} for dataset {ds}")
    return True

class FairnessDataset(Dataset):
    def __init__(
        self,
        split_dir: str,
        data_dir: str,
        split: Literal["train", "val", "test"],
        sensitive_attribute: SensitiveAttribute,
        dataset_name: AvailableDataset,
        label_noise: float = 0.0,
    ) -> None:
        super().__init__()
        assert is_valid_sensitive_attribute(sensitive_attribute, dataset_name)

        split_path = os.path.join(split_dir, f"{split}.csv")
        self.split_df = pd.read_csv(split_path)
        self.data_dir = data_dir
        self.sensitive_attribute = sensitive_attribute

        # we pre-compute which labels to flip to prevent the same individuals from
        # having different labels in different epochs
        self.labels_to_flip = []
        if label_noise > 0.0:
            for idx, row in self.split_df.iterrows():
                # only positive labels in group 1 are flipped
                if (
                    row["binaryLabel"] == 1
                    and row[self.sensitive_attribute.value["Key"]] == 1
                    and torch.rand(1).item() < label_noise
                ):
                    self.labels_to_flip.append(idx)

        print(f"Flipping {len(self.labels_to_flip)} labels in {split} set.")

    def __getitem__(self, idx) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
        img_path = os.path.join(self.data_dir, self.split_df.iloc[idx]["Path"])
        img = torchvision.io.read_image(
            img_path, mode=torchvision.io.image.ImageReadMode.RGB
        )

        label = self.split_df.iloc[idx]["binaryLabel"]
        label = torch.tensor(label, dtype=torch.long)

        if idx in self.labels_to_flip:
            label = 1 - label

        subgroup = self.split_df.iloc[idx][self.sensitive_attribute.value["Key"]]
        subgroup = torch.tensor(subgroup, dtype=torch.long)

        return img, label, subgroup

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

class FairnessDataModule(pl.LightningDataModule):
    def __init__(
        self,
        split_dir: str,
        data_dir: str,
        sensitive_attribute: str,
        dataset_name: str,
        batch_size: int,
        num_workers: int,
        pin_memory: bool,
        label_noise: float = 0.0,
    ) -> None:
        """
        Args:
            split_dir (str): Path to directory containing train.csv, val.csv, and
                test.csv for the given dataset.
            data_dir (str): Path to directory containing the dataset images.
            sensitive_attribute (str): Case-insensitive name of the sensitive attribute
                to use. It will be converted into a SensitiveAttribute enum.
            dataset_name (str): Case-insensitive name of the dataset to use. It will be
                converted into an AvailableDataset enum.
            batch_size (int): Batch size to use.
            num_workers (int): Number of workers to use for data loading.
            pin_memory (bool): Whether to pin memory for data loading.
            label_noise (float): Probability of mislabelling the positive class in
                subgroup 1. Applied on training and validation set but never on test
                set. Defaults to 0.0.
        """
        super().__init__()
        self.split_dir = split_dir
        self.data_dir = data_dir
        self.batch_size = batch_size
        self.num_workers = num_workers
        self.pin_memory = pin_memory

        self.sensitive_attribute = SensitiveAttribute[sensitive_attribute.lower()]
        self.dataset_name = AvailableDataset[dataset_name.lower()]

        self.label_noise = label_noise

    def setup(self, stage: str) -> None:
        assert stage in ("fit", "test")
        assert is_valid_sensitive_attribute(self.sensitive_attribute, self.dataset_name)

        if stage == "fit":
            # train and val datasets have label noise
            self.train_dataset = FairnessDataset(
                self.split_dir,
                self.data_dir,
                "train",
                self.sensitive_attribute,
                self.dataset_name,
                self.label_noise,
            )
            self.val_dataset = FairnessDataset(
                self.split_dir,
                self.data_dir,
                "val",
                self.sensitive_attribute,
                self.dataset_name,
                self.label_noise,
            )
        elif stage == "test":
            self.test_dataset = FairnessDataset(
                self.split_dir,
                self.data_dir,
                "test",
                self.sensitive_attribute,
                self.dataset_name,
            )

    def train_dataloader(self) -> DataLoader:
        return DataLoader(
            self.train_dataset,
            batch_size=self.batch_size,
            num_workers=self.num_workers,
            pin_memory=self.pin_memory,
            shuffle=True,
        )

    def val_dataloader(self) -> DataLoader:
        return DataLoader(
            self.val_dataset,
            batch_size=self.batch_size,
            num_workers=self.num_workers,
            pin_memory=self.pin_memory,
            shuffle=False,
        )

    def test_dataloader(self) -> DataLoader:
        return DataLoader(
            self.test_dataset,
            batch_size=self.batch_size,
            num_workers=self.num_workers,
            pin_memory=self.pin_memory,
            shuffle=False,
        )

    def get_subgroup_names(self) -> Mapping[int, str]:
        return self.sensitive_attribute.value


for c in range(0, 3):
    tabuada = int(input("Quer ver a tuabuada de qual valor? "))
    print("_"*15)
    if tabuada < 0:
        break
    for c in range(1, 11):
        valor = tabuada * c
        print(f"{tabuada} x {c} = {valor}")
    print("_"*15)
print("Programa de tabuada encerrado, volte sempre.")


from pathlib import Path
import matplotlib.pyplot as plt

import numpy as np
import tensorflow as tf
import keras
from keras import Model
from tensorflow.keras import backend as K
from tensorflow.keras.utils import load_img, img_to_array, save_img
from keras.applications import VGG19
from keras.applications.vgg19 import preprocess_input

from utils import deprocess_image, save_animation

# Load images
content_image_path = Path('data') / 'src' / 'content' / 'autumn_road.jpg'
style_image_path = Path('data') / 'src' / 'style' / 'waves.jpg'
output_folder = Path('data') / 'output'

original_width, original_height = keras.utils.load_img(content_image_path).size
print(original_width, original_height)

img_height = 300
img_width = round(original_width * img_height / original_height)
print(img_width, img_height)

base_image = img_to_array(load_img(content_image_path, target_size=(img_height, img_width), interpolation='bicubic'))
style_image = img_to_array(load_img(style_image_path, target_size=(img_height, img_width), interpolation='bicubic'))

fig, ax = plt.subplots(1, 2, figsize=(12, 5))
ax[0].imshow(base_image / 255.0)
ax[0].axis('off')
ax[0].set_title('Base Image')
ax[1].imshow(style_image / 255.0)
ax[1].axis('off')
ax[1].set_title('Style Image')

fig.show()

# Define VGG model
vgg = VGG19(weights='imagenet', include_top=False)
output_dict = {layer.name: layer.output for layer in vgg.layers}
model = Model(inputs=vgg.input, outputs=output_dict)

def content_loss_fn(base_features, combined_features):
    """Compute MSE loss between `base_features` and `combined_features`"""
    return tf.reduce_sum(tf.square(base_features - combined_features))

def variance_loss_fn(img):
    height, width = img.shape[1:3]
    a = tf.square(img[:, height - 1, :width - 1, :] - img[:, 1:, :width - 1, :])
    b = tf.square(img[:, height - 1, :width - 1, :] - img[:, :height - 1, 1:, :])

    return tf.reduce_sum(a + b)

def style_loss_fn(style_img, combined_img):
    def gram_matrix(feature_matrix):
        flattened_feature_matrix = K.batch_flatten(K.permute_dimensions(feature_matrix, (2, 0, 1)))
        gram = K.dot(flattened_feature_matrix, K.transpose(flattened_feature_matrix))
        return gram

    style_img_gram_matrix = gram_matrix(style_img)
    combined_img_gram_matrix = gram_matrix(combined_img)

    return tf.reduce_sum(tf.square(style_img_gram_matrix - combined_img_gram_matrix))

# Parameters
content_loss_weight = 1e-5
style_loss_weight = 2.5e-3
variance_loss_weight = 1e-6

init_methods = ['content', 'style', 'noise']
reconstruction_types = ['content', 'style', 'both']

init_method = 'content'  # One of 'content', 'style' or 'noise'
reconstruction_type = 'both'  # One of 'content', 'style' or 'both'
epochs = 2000
num_epochs_per_save = 100
learning_rate = 2.0

style_feature_layers = ['block1_conv1', 'block2_conv1', 'block3_conv1', 'block4_conv1', 'block5_conv1']
content_feature_layer = 'block2_conv2'

base_image_tensor = preprocess_input(np.expand_dims(base_image.copy(), axis=0))
style_image_tensor = preprocess_input(np.expand_dims(style_image.copy(), axis=0))

if init_method not in init_methods:
    raise ValueError('Initialization method {init_method} not supported, choose one of {*init_methods}')

if reconstruction_type not in reconstruction_types:
    raise ValueError('Reconstructing {reconstruction_type} not supported, choose one of {*reconstruction_methods}')

if init_method == 'content':
    combined_image_tensor = tf.Variable(base_image_tensor.copy())
elif init_method == 'noise':
    combined_image_tensor = tf.Variable(np.random.random(base_image_tensor.shape), dtype=np.float32)
else:
    combined_image_tensor = tf.Variable(style_image_tensor.copy())

content_losses = []
style_losses = []
variance_losses = []

total_losses = []

optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate, beta_1=0.5)

for epoch in range(epochs + 1):
    with tf.GradientTape() as tp:
        input_tensor = tf.concat([base_image_tensor, style_image_tensor, combined_image_tensor], 0)
        features = model(input_tensor)

        content_features_base_image = features[content_feature_layer][0]
        content_features_combined_image = features[content_feature_layer][2]

        content_loss = content_loss_weight * content_loss_fn(content_features_base_image, content_features_combined_image)

        style_loss = 0.0
        for layer in style_feature_layers:
            style_features_style_image = features[layer][1]
            style_features_combined_image = features[layer][2]
            channels = 3
            size = img_height * img_width
            style_loss_l = style_loss_fn(style_features_style_image, style_features_combined_image)
            style_loss_l = style_loss_l / (4.0 * (channels ** 2) * (size ** 2))
            style_loss += style_loss_l / (len(style_feature_layers))

        style_loss = style_loss_weight * style_loss

        variance_loss = variance_loss_fn(combined_image_tensor)
        variance_loss = variance_loss_weight * variance_loss

        content_losses.append(content_loss)
        style_losses.append(style_loss)
        variance_losses.append(variance_loss)

        if reconstruction_type == 'content':
            total_loss = content_loss
        elif reconstruction_type == 'style':
            total_loss = style_loss
        else:
            total_loss = content_loss + style_loss + variance_loss

        total_losses.append(total_loss.numpy())

    print(f"[Epochs: {epoch}/{epochs}] Total loss: {total_loss:.2f}, content loss: {content_loss:.2f}, style loss: {style_loss:.4f}, variance loss: {variance_loss:.2f}")
    grad = tp.gradient(total_loss, combined_image_tensor)
    optimizer.apply_gradients([(grad, combined_image_tensor)])

    # Apply Gradients
    if epoch % num_epochs_per_save == 0:
        # Save combined image
        combined_image = combined_image_tensor.numpy()[0]
        combined_image = deprocess_image(combined_image)
        fname = output_folder / f"{content_image_path.stem}_and_{style_image_path.stem}" / reconstruction_type / f'regenerate__{epoch:04}.png'
        fname.parent.mkdir(parents=True, exist_ok=True)
        save_img(fname, combined_image)

save_animation(output_folder, content_image_path, style_image_path, reconstruction_type)

fig, ax = plt.subplots(2, 2, figsize=(10, 10))
ax[0, 0].plot(np.log10(total_losses), '-.')
ax[0, 0].set_title('Total loss')
ax[0, 1].plot(np.log10(content_losses[1:]), '-.')
ax[0, 1].set_title('Content Loss')
ax[1, 0].plot(np.log10(style_losses), '-.')
ax[1, 0].set_title('Style Loss')
ax[1, 1].plot(np.log10(variance_losses), '-.')
ax[1, 1].set_title('Total variance loss')

fig.suptitle('Training losses', fontsize=15)

fig.savefig(output_folder / f"{content_image_path.stem}_and_{style_image_path.stem}" / reconstruction_type / 'training_losses.png')


from app.database import get_db

def output_formatter(results):
    out = []
    for result in results:
        res = {
            "id": result[0],
            "summary": result[1],
            "description": result[2],
            "is_done": result[3]
        }
        out.append(res)
    return out

def scan():
    conn = get_db()
    cursor = conn.execute("SELECT * FROM task WHERE is_done=0", ())
    results = cursor.fetchall()
    cursor.close()
    return output_formatter(results)

def select_by_id(task_id):
    conn = get_db()
    cursor = conn.execute("SELECT * FROM task WHERE id=?", (task_id, )) # comma! ## passing data to the question mark
    results = cursor.fetchall()
    cursor.close()
    if results:
        return output_formatter(results)[0]
    return {}

def insert(task_data):
    conn = get_db()
    task_tuple = (
        task_data.get("summary"),
        task_data.get("description")
    )
    statement = """
        INSERT INTO task (
            summary,
            description
        ) VALUES (?, ?)
    """
    conn.execute(statement, task_tuple)
    conn.commit()

def update_by_id(task_data, task_id):
    conn = get_db()
    task_tuple = (      # purpose to map into statement.
        task_data.get("summary"),
        task_data.get("description"),
        task_data.get("is_done"),
        task_id
    )
    statement = """
        UPDATE task SET
            summary = ?,
            description = ?,
            is_done = ?
        WHERE id = ?
    """

    conn.execute(statement, task_tuple)
    conn.commit()

    def delete_by_id(task_id):
        conn = get_db()
        conn.execute("DELETE FROM task WHERE id=?", (task_id, )) # comma
        conn.commit()


from typing import List
from File import File
from Directory import Directory
from ListVisitor import ListVisitor
from MyVisitor import MyVisitor
from FileTreatMentException import FileTreatMentException

def main():
    try:
        print('Making root entries...')
        rootdir = Directory('root')
        bindir = Directory('bin')
        tmpdir = Directory('tmp')
        usrdir = Directory('usr')
        rootdir.add(bindir)
        rootdir.add(tmpdir)
        rootdir.add(usrdir)
        bindir.add(File("vi", 10000))
        bindir.add(File('latex', 20000))
        rootdir.accept(ListVisitor())

        print('')
        print('Making user entries...')
        yuki = Directory('yuki')
        hanako = Directory('hanako')
        tomura = Directory('tomura')
        usrdir.add(yuki)
        usrdir.add(hanako)
        usrdir.add(tomura)
        yuki.add(File('diary.html', 100))
        yuki.add(File('Compisite.java', 200))
        hanako.add(File('memo.tex', 300))
        tomura.add(File('game.doc', 400))
        tomura.add(File('junk.mail', 500))
        rootdir.accept(MyVisitor())

    except FileTreatMentException as e:
        print(e)

if __name__ == '__main__':
    main()


from config import *
from DatabaseModule.database_manipulation import load_from_mongo, load_from_mongo_sorted
DESC = -1
ASC = 1

def facebook_get_likes_count(page_name):
    """
    Reads from database the number of likes for a page

    :param page_name:
    :return: number of likes
    """
    debug_print("EXEC facebook_get_likes_count method :")
    if page_name is not None:
        criteria = {"name": "%s" % page_name}
        projection = {"likes": 1, "_id": 0}
        result = load_from_mongo(mongo_db="facebook",mongo_db_coll="pages_info", criteria=criteria,projection=projection)

        return result[0]["likes"]

def facebook_get_talkingabout_count(page_name):
    """
    Reads from database the number of the parameter talking about(facebook) for a page

    :param page_name:
    :return: talking_about_count - number of people talking about your page
    """
    debug_print("EXEC facebook_get_talkingabout_count method :")
    if page_name is not None:
        criteria = {"name": "%s" % page_name}
        projection = {"talking_about_count": 1, "_id": 0}
        result = load_from_mongo(mongo_db="facebook",mongo_db_coll="pages_info",criteria=criteria,projection=projection)
        talking_about_count = result[0]["talking_about_count"]
        return talking_about_count

def facebook_get_posts_from_database(from_user=None, page_name=None, limit=None):  # get posts for certain period for certain users/or not
    """
    Reads posts from database writen by a certain user posted on a certain page
    :parameter: from_user - the name of the user that wrote the post
    :parameter: page_name - the name of the page the post was posted to
    :parameter: limit - number of maximum number of posts
    :return: result - posts
    """
    debug_print("EXEC facebook_get_posts_from_database method :")
    if from_user is not None:
        criteria = {"from.name": from_user}
    else:
        criteria = None
        #must create a list of sets with [('field',value),('field2',value2)] for multiple sorting parameters
    sort_params = [("created_time", -1)] # sort by DESC order , from latest to older

    result = load_from_mongo_sorted(mongo_db="facebook", mongo_db_coll=page_name, sort_params=sort_params, limit=limit, criteria=criteria)
    #print("res: form data ", result)
    return result

def facebook_get_posts_for_month(page_name, month):
    """
    Reads posts from database for a given page writen in a certain month.
    Used when looking for a post written in a certain period.

    :parameter: page_name - the name of the page the post was posted to
    :parameter: month - the month the page was created on
    :return: result - posts
    """
    debug_print("EXEC facebook_get_posts_for_month method :")

    regex = "2014-%s-.*" % month  # regex for searching dates in database
    criteria = {"created_time": {"$regex": regex}}

    #must create a list of sets with [('field',value),('field2',value2)] for multiple sorting parameters
    sort_params = [("created_time", -1)]  # sort by DESC order , from latest to older

    result = load_from_mongo_sorted(mongo_db="facebook", mongo_db_coll=page_name, sort_params=sort_params, criteria=criteria)
    return result

def facebook_sort_pages(pages, order=DESC):
    """ Sorts the list of pages first by number of likes then by number of people talking about it
    :parameter pages - list of pages to sort
    :parameter order - order in which the list should be sorted. values: ASC and DESC
    :returns pages - sorted ist of pages
    """
    debug_print("EXEC facebook_sort_pages method :")
    #print pages
    #sort statuses by likes, then by num of people talking about it
    if order == DESC:
        for i in range(0, len(pages)):
            for j in range(i, len(pages)):
                if int(pages[i]['likes']) < int(pages[j]['likes']):
                    pages[i], pages[j] = pages[j], pages[i]
                elif int(pages[i]['likes']) == int(pages[j]['likes']):
                    if int(pages[i]['talking_about_count']) < int(pages[j]['talking_about_count']):
                        pages[i], pages[j] = pages[j], pages[i]
    elif order == ASC:
         for i in range(0, len(pages)):
            for j in range(i, len(pages)):
                if int(pages[i]['likes']) > int(pages[j]['likes']):
                    pages[i], pages[j] = pages[j], pages[i]
                elif int(pages[i]['likes']) == int(pages[j]['likes']):
                    if int(pages[i]['talking_about_count']) > int(pages[j]['talking_about_count']):
                        pages[i], pages[j] = pages[j], pages[i]
    return pages


#!/usr/bin/python3
import pyautogui
import random
import time
import os

if __name__ == "__main__":

  with open("mouse_m.txt","a") as f:
      p_currentMouseX, p_currentMouseY = pyautogui.position()
      time_p = time.time()
      while True:
          currentMouseX, currentMouseY = pyautogui.position()
          time_now = time.time()

          if currentMouseX != p_currentMouseX and currentMouseY != p_currentMouseY:
            print(currentMouseX, currentMouseY, time_now - time_p)
            f.write(f"{currentMouseX} {currentMouseY} {time_now - time_p}")
            f.write("\n")
            p_currentMouseX = currentMouseX
            p_currentMouseY = currentMouseY
            time_p = time_now

          time.sleep(0.05)


from django.conf.urls import url, include
from getpaid.views import NewPaymentView, FallbackView
from getpaid.utils import import_backend_modules

app_name = 'getpaid'
namespace = app_name

includes_list = []
for backend_name, urls in import_backend_modules('urls').items():
    backend_url_regex = r'^%s/' % backend_name
    backend_namespace = backend_name.split('.')[-1]
    backend_url = url(
        backend_url_regex,
        include(urls, app_name=app_name, namespace=backend_namespace)
    )
    includes_list.append(backend_url)

urlpatterns = [
    url(
        r'^new/payment/(?P<currency>[A-Z]{3})/$',
        NewPaymentView.as_view(),
        name='new-payment'
    ),
    url(
        r'^payment/success/(?P<pk>\d+)/$',
        FallbackView.as_view(success=True),
        name='success-fallback'
    ),
    url(
        r'^payment/failure/(?P<pk>\d+)$',
        FallbackView.as_view(success=False),
        name='failure-fallback'
    ),
] + includes_list


# coding=utf-8
__author__ = 'lxn3032'

import json
import requests
from requests.exceptions import ConnectionError

from hrpc.exceptions import TransportDisconnected

from hrpc.transport import Transport

class HttpTransport(Transport):
    def __init__(self, endpoint, client):
        super(HttpTransport, self).__init__(endpoint, client)
        self.connect()

    def send(self, req, timeout=None):
        req['session_id'] = self.session_id
        try:
            r = requests.post(self.endpoint, data=json.dumps(req), headers={'Content-Type': 'application/json'},
                              timeout=timeout)
            self.rpc_client.put_response(r.json())
        except (ConnectionError, ValueError) as e:
            raise TransportDisconnected(e)

    def connect(self):
        self.connected = True

    def disconnect(self):
        self.connected = False

    def ping(self):
        try:
            r = requests.post(self.endpoint, data='', timeout=1)
            return True
        except:
            return False

    def __str__(self):
        msg = '<hrpc.__builtin__.transport over http> endpoint: {}'.format(self.endpoint)
        return msg


import os
import unittest

import pytest

from sparknlp.annotator import *
from sparknlp.base import *
from test.util import SparkContextForTest

@pytest.mark.fast
class ChunkTokenizerTestSpec(unittest.TestCase):

    def setUp(self):
        self.session = SparkContextForTest.spark

    def runTest(self):
        document_assembler = DocumentAssembler() \
            .setInputCol("text") \
            .setOutputCol("document")
        tokenizer = Tokenizer() \
            .setInputCols(["document"]) \
            .setOutputCol("token")
        entity_extractor = TextMatcher() \
            .setInputCols(['document', 'token']) \
            .setOutputCol("entity") \
            .setEntities(path="file:///" + os.getcwd() + "/../src/test/resources/entity-extractor/test-chunks.txt")
        chunk_tokenizer = ChunkTokenizer() \
            .setInputCols(['entity']) \
            .setOutputCol('chunk_token')

        pipeline = Pipeline(stages=[document_assembler, tokenizer, entity_extractor, chunk_tokenizer])

        data = self.session.createDataFrame([
            ["Hello world, my name is Michael, I am an artist and I work at Benezar"],
            ["Robert, an engineer from Farendell, graduated last year. The other one, Lucas, graduated last week."]
        ]).toDF("text")

        pipeline.fit(data).transform(data).show()


import tensorflow as tf
import scipy

g = tf.Graph()

def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

def conv2d(x, W, stride):
  return tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding='VALID')

with g.as_default():
  x = tf.placeholder(tf.float32, shape=[None, 66, 200, 3])
  y_ = tf.placeholder(tf.float32, shape=[None, 1])

  x_image = x

  #first convolutional layer
  W_conv1 = weight_variable([5, 5, 3, 24])
  b_conv1 = bias_variable([24])

  h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1, 2) + b_conv1)

  #second convolutional layer
  W_conv2 = weight_variable([5, 5, 24, 36])
  b_conv2 = bias_variable([36])

  h_conv2 = tf.nn.relu(conv2d(h_conv1, W_conv2, 2) + b_conv2)

  #third convolutional layer
  W_conv3 = weight_variable([5, 5, 36, 48])
  b_conv3 = bias_variable([48])

  h_conv3 = tf.nn.relu(conv2d(h_conv2, W_conv3, 2) + b_conv3)

  #fourth convolutional layer
  W_conv4 = weight_variable([3, 3, 48, 64])
  b_conv4 = bias_variable([64])

  h_conv4 = tf.nn.relu(conv2d(h_conv3, W_conv4, 1) + b_conv4)

  #fifth convolutional layer
  W_conv5 = weight_variable([3, 3, 64, 64])
  b_conv5 = bias_variable([64])

  h_conv5 = tf.nn.relu(conv2d(h_conv4, W_conv5, 1) + b_conv5)

  #FCL 1
  W_fc1 = weight_variable([1152, 1164])
  b_fc1 = bias_variable([1164])

  h_conv5_flat = tf.reshape(h_conv5, [-1, 1152])
  h_fc1 = tf.nn.relu(tf.matmul(h_conv5_flat, W_fc1) + b_fc1)

  keep_prob = tf.placeholder(tf.float32)
  h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

  #FCL 2
  W_fc2 = weight_variable([1164, 100])
  b_fc2 = bias_variable([100])

  h_fc2 = tf.nn.relu(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

  h_fc2_drop = tf.nn.dropout(h_fc2, keep_prob)

  #FCL 3
  W_fc3 = weight_variable([100, 50])
  b_fc3 = bias_variable([50])

  h_fc3 = tf.nn.relu(tf.matmul(h_fc2_drop, W_fc3) + b_fc3)

  h_fc3_drop = tf.nn.dropout(h_fc3, keep_prob)

  #FCL 3
  W_fc4 = weight_variable([50, 10])
  b_fc4 = bias_variable([10])

  h_fc4 = tf.nn.relu(tf.matmul(h_fc3_drop, W_fc4) + b_fc4)

  h_fc4_drop = tf.nn.dropout(h_fc4, keep_prob)

  #Output
  W_fc5 = weight_variable([10, 1])
  b_fc5 = bias_variable([1])

  y = tf.multiply(tf.atan(tf.matmul(h_fc4_drop, W_fc5) + b_fc5), 2) #scale the atan output


"""
.. index:: Extensions; index_styling

==============================
PSphinxTheme.ext.index_styling
==============================

Overview
========
**improves css styling for genindex**

This Sphinx extension intercepts & modifies the general index data before it is rendered to html, adding some additional css
classes to help *P-SphinxTheme* (e.g. :doc:`/main_theme`) provide additional per-type styling for index entries.

Internals
=========
This extension adds the following css classes to ``genindex.html``:

- For all entries referencing an ``attribute``, ``method``, ``class``, ``function``, or ``module``:

  - The text containing the type of the entry (e.g. ``attribute`` or ``method``) is wrapped in a

   :samp:`<span class="category {type}">...</span>` tag.

  - If the entry contains a location (e.g. ``myclass in module myapp``), the ``myapp`` portion is wrapped in a

   ``...`` tag.

- Entries which don't fit into one of the above categories are not modified.

"""
from re import (
   compile as re_compile,
)

# noinspection PyPep8Naming
from jinja2 import (
   escape,
   Markup as literal,
)

prefix = r'^(?P<name>.*)\('
suffix = r'\)$'
_attr_re = re_compile(prefix + r'(?P<left>)(?P<loc>.*)(?P<right> attribute)' + suffix)
_meth_re = re_compile(prefix + r'(?P<left>)(?P<loc>.*)(?P<right> method)' + suffix)
_fc_re = re_compile(prefix + r'(?P<left>class in |in module )(?P<loc>.*)(?P<right>)' + suffix)
_mod_re = re_compile(prefix + r'module' + suffix)

def format_index_name(name):
   """ format_index_name

   :param name:
   :return:
   """
   loc = ''
   type_ = ''
   left = ''
   right = ''
   while True:
      m = _attr_re.match(name)
      if m:
         name, left, loc, right = m.group('name', 'left', 'loc', 'right')
         type_ = 'attribute'
         break
      m = _meth_re.match(name)
      if m:
         name, left, loc, right = m.group('name', 'left', 'loc', 'right')
         type_ = 'method'
         break
      m = _fc_re.match(name)
      if m:
         name, left, loc, right = m.group('name', 'left', 'loc', 'right')
         if left.startswith('class'):
            type_ = 'class'
         else:
            type_ = 'function'
         break
      m = _mod_re.match(name)
      if m:
         name = m.group('name')
         left = 'module'
         loc = right = ''
         type_ = 'module'
         break
      return name
   if loc:
      loc = literal('') + escape(loc) + literal('')
   cat = left + loc + right
   return escape(name) + literal('') + escape(cat) + literal('')

# noinspection PyUnusedLocal
def mangle_index(app, pagename, templatename, ctx, event_arg):
   """ mangle_index

   :param app:
   :param pagename:
   :param templatename:
   :param ctx:
   :param event_arg:
   :return:
   """
   if pagename != 'genindex':
      return
   fmt = format_index_name
   for key, entries in ctx['genindexentries']:
      for idx, entry in enumerate(entries):
         name, (links, subitems) = entry
         entries[idx] = fmt(name), (links, subitems)
         for idx_, entry_ in enumerate(subitems):
            name, links = entry_
            subitems[idx_] = fmt(name), links

def setup(app):
   """ register extension
   """
   app.connect('html-page-context', mangle_index)


import socket
import queue

sock = socket.socket()
sock.bind(('', 9090))
sock.listen(1)
q = []

while True:
    print("listening")
    conn, addr = sock.accept()
    print('connected:', addr)
    while True:
        data = conn.recv(1024)
        if not data:
            conn.close()
            break
        queue.push(q, data)
        print(q)
        conn.send("Done".encode())


from solution import SOLUTION
import constants as c
import copy
import os

class PARALLEL_HILL_CLIMBER:

    def __init__(self):

        os.system("rm brain*.nndf")
        os.system("rm fitness*.txt")

        self.nextAvailableID = 0
        self.parents = {}

        for i in range(c.populationSize):
            self.parents[i] = SOLUTION(self.nextAvailableID)
            self.nextAvailableID += 1

    def Evolve_For_One_Generation(self):
        self.Spawn()
        self.Mutate()
        self.Evaluate(self.children)
        self.Print()
        self.Select()

    def Evolve(self):
        self.Evaluate(self.parents)
        for currentGeneration in range(c.genNum):
            self.Evolve_For_One_Generation()

    def Spawn(self):
        self.children = {}
        for i in range(c.populationSize):
            self.children[i] = copy.deepcopy(self.parents[i])
            self.children[i].Set_ID(self.nextAvailableID)
            self.nextAvailableID += 1

    def Mutate(self):
        for i in range(c.populationSize):
            self.children[i].Mutate()

    def Select(self):
        for i in range(c.populationSize):
            if float(self.children[i].fitness) < float(self.parents[i].fitness):
                self.parents[i] = copy.deepcopy(self.children[i])

    def Print(self):
        for i in range(c.populationSize):
            print("Parent Fitness: " + self.parents[i].fitness + " | Child Fitness: " + self.children[i].fitness + "\n")

    def Show_Best(self):
        bestFitness = float("inf")
        bestFitnessKey = None

        for i in range(c.populationSize):
            if float(self.parents[i].fitness) < bestFitness:
                bestFitness = float(self.parents[i].fitness)
                bestFitnessKey = i

        self.parents[bestFitnessKey].Start_Simulation("GUI")

    def Evaluate(self, solutions):
        for i in range(c.populationSize):
            solutions[i].Start_Simulation("DIRECT")

        for i in range(c.populationSize):
            solutions[i].Wait_For_Simulation_To_End()


#쉬운계단수
#수가 1씩차이나는거 45656

N = int(input())
# arr = [0 for i in range(N+1)]

# for i in range(N+1):

arr = [0,1,1,1,1,1,1,1,1,1]
for i in range(N-1):
    newarr = [0 for i in range(10)]
    for j in range(10):
        if j == 0:
            newarr[1] += arr[0]
        elif j == 9:
            newarr[8] += arr[9]
        else:
            newarr[j+1] += arr[j]
            newarr[j-1] += arr[j]
    for i in range(10):
        arr[i] = newarr[i]%1000000000

print(sum(arr)%1000000000)


from enum import Enum, auto

class View(Enum):
    MENU = auto()
    LETTERS = auto()
    FIGURES = auto()

class Ev(Enum):
    KEY_PRESSED = auto()
    NEW_FIGURES_GAME = auto()
    NEW_LETTERS_GAME = auto()
    GOAL_ACHIEVED = auto()
    END_TIMER = auto()
    GO_TO_MENU = auto()
    QUIT = auto()

win_size = win_width, win_height = 1600, 900
plaque_size = plaque_width, plaque_height = win_width // 15, win_width // 13
frame_rate = 60
menu_bg_color = (40, 40, 40)
game_bg_color = (70, 70, 120)
bg_color = menu_bg_color

n_letters = 10
n_figures = 6


from time import sleep
from django.core.management.base import BaseCommand
from smm.models import Newsletter
from datetime import datetime, timedelta

class Command(BaseCommand):
    def handle(self, *args, **options):
        news = Newsletter.objects.all()
        today = datetime.now().date()
        for new in news:
            last = new.logs.all().order_by('-last_attempt').first()
            if last and last.last_attempt.date() + timedelta(days=new.frequency) > today:
                send(new)
            sleep(5)

def send(newsletter):
    print(f"Отправка рассылки для {newsletter}")


import sys
from contextlib import suppress
from datetime import date
from datetime import datetime
from datetime import timedelta
from datetime import timezone
from decimal import Decimal
from enum import Enum
from typing import Any
from typing import Callable
from typing import Mapping
from typing import Type
from typing import TypeVar

import cattr
import dateutil.parser
from attr import fields
from pytimeparse.timeparse import timeparse  # type: ignore
from typing_extensions import get_args

T = TypeVar("T")  # pylint: disable=invalid-name
NoneType = type(None)

class ReversedEnum(Enum):
    ...

class StructureError(ValueError):
    pass

class PEP563NotImplementedError(StructureError, NotImplementedError):
    pass

class Converter(cattr.Converter):
    """cattrs converter patched to correctly load complex attrs structures.

    Keep in mind that __future__.annotations import is not supported when using this class!
    """

    def __init__(self):
        super().__init__()

        self.register_structure_hook(Decimal, self._structure_decimal)
        self.register_unstructure_hook(Decimal, self._unstructure_decimal)

        self.register_structure_hook(NoneType, lambda obj, cls: obj)

        self.register_structure_hook(datetime, self._structure_datetime)
        self.register_unstructure_hook(datetime, self._unstructure_datetime)
        self.register_structure_hook(date, self._structure_date)
        self.register_unstructure_hook(date, self._unstructure_date)
        self.register_structure_hook(timedelta, self._structure_timedelta)
        self.register_unstructure_hook(timedelta, self._unstructure_timedelta)
        self.register_structure_hook(ReversedEnum, self._structure_reversed_enum)
        self.register_unstructure_hook(ReversedEnum, self._unstructure_reversed_enum)

    def structure_attrs_fromdict(self, obj: Mapping, cl: Type[T]) -> T:
        """Instantiate an attrs class from a mapping.

        Raises human-readable StructureError exceptions on failure.
        """
        try:
            # self._eval_str_types(cl)
            return super().structure_attrs_fromdict(obj or {}, cl)
        # NOTE: If exception has occurred while structuring nested attrs class raise it directly without further processing
        except StructureError:
            raise
        except Exception as exc:
            last_frame_locals = sys.exc_info()[2].tb_next.tb_frame.f_locals  # type: ignore
            human_class = last_frame_locals["cl"].__qualname__

            if isinstance(exc, TypeError) and "required keyword-only" in str(exc):
                exc_message = " ".join(str(exc).split()[1:])
                message = f"Cannot structure {human_class}: {exc_message}"
            else:
                value = last_frame_locals["val"]
                try:
                    human_type = last_frame_locals["a"]["type"].__name__
                except (KeyError, TypeError, AttributeError):
                    human_type = str(last_frame_locals["a"].type)
                message = f"Cannot structure {human_class}: {value} is not an instance of {human_type}"

            raise StructureError(message) from exc

    @classmethod
    def _eval_str_types(cls, attrs_class: Type[T]) -> None:
        """Evaluate Attribute.type from string annotations.

        When using attr.dataclass(kw_only=True) decorator attrs set type of generated Optional attribs to their string
        representations making impossible for cattrs to correctly structure them. This class fixes this issue evaluating
        strings back into Type objects before structuring.
        """
        for attrib in attrs_class.__attrs_attrs__:  # type: ignore
            if isinstance(attrib.type, str):
                try:
                    object.__setattr__(attrib, "type", eval(attrib.type))  # pylint: disable=eval-used
                except NameError as exc:
                    raise PEP563NotImplementedError("`Postponed Evaluation of Annotations is not supported") from exc

    @staticmethod
    def _get_dis_func(union: Type) -> Callable[..., Type]:
        """Fetch or try creating a disambiguation function for a Union.

        This algorithm is more strict than default Converter"s one and will fail if data contains redundant attributes.
        However lots of complex edge cases are covered.
        """
        union_types = get_args(union)
        if NoneType in union_types:  # type: ignore
            union_types = tuple(e for e in union_types if e is not NoneType)  # type: ignore

        if not all(hasattr(e, "__attrs_attrs__") for e in union_types):
            raise StructureError(
                f"Cannot structure {union}: only unions of attr classes are supported currently. Register a structure hook manually."
            )

        if len(union_types) < 2:
            raise StructureError(f"Cannot structure {union}: at least two classes required.")

        cls_and_attrs = [(cl, {at.name for at in fields(cl)}) for cl in union_types]

        if len([attrs for _, attrs in cls_and_attrs if len(attrs) == 0]) > 1:
            raise StructureError(f"Cannot structure {union}: at least two classes have no attributes.")

        cls_and_attrs.sort(key=lambda c_a: len(c_a[1]))

        def _dis_func(data: Mapping) -> Type:
            if not isinstance(data, Mapping):
                raise StructureError(f"Cannot structure {union}: only mappings are supported as input.")
            for cls, cls_keys in cls_and_attrs:
                if all([data_key in cls_keys for data_key in data]):
                    return cls
            raise StructureError(f"Cannot structure {union}: {data} does not match any of generic arguments")

        return _dis_func

    @staticmethod
    def _structure_decimal(obj: Any, cls: Type) -> Decimal:
        return cls(str(obj))

    @staticmethod
    def _unstructure_decimal(obj: Decimal) -> str:
        return str(obj)

    @staticmethod
    def _structure_datetime(obj: Any, cls: Type) -> datetime:  # pylint: disable=unused-argument
        with suppress(ValueError, TypeError):
            return datetime.utcfromtimestamp(float(obj)).replace(tzinfo=timezone.utc)
        with suppress(dateutil.parser.ParserError):
            return dateutil.parser.parse(obj)
        raise ValueError

    @staticmethod
    def _unstructure_datetime(obj: datetime) -> float:
        return obj.timestamp()

    @staticmethod
    def _structure_date(obj: Any, cls: Type) -> date:  # pylint: disable=unused-argument
        with suppress(ValueError, TypeError):
            return date.fromtimestamp(float(obj))
        with suppress(dateutil.parser.ParserError):
            dt = dateutil.parser.parse(obj)  # pylint: disable=invalid-name
            return date(year=dt.year, month=dt.month, day=dt.day)
        raise ValueError

    @staticmethod
    def _unstructure_date(obj: date) -> float:
        return datetime(obj.year, obj.month, obj.day, tzinfo=timezone.utc).timestamp()

    @staticmethod
    def _structure_timedelta(obj: Any, cls: Type) -> timedelta:  # pylint: disable=unused-argument
        with suppress(ValueError, TypeError):
            return timedelta(seconds=int(obj))
        with suppress(TypeError):
            return timedelta(seconds=timeparse(obj))
        raise ValueError

    @staticmethod
    def _unstructure_timedelta(obj: timedelta) -> float:
        return obj.total_seconds()

    @staticmethod
    def _structure_reversed_enum(obj: str, cls: Type[ReversedEnum]) -> ReversedEnum:
        return cls[obj]

    @staticmethod
    def _unstructure_reversed_enum(obj: ReversedEnum) -> str:
        return obj.name


#### Import dependencies for os.path.join()
import os
import csv

### Define PyPoll's variables
votes_total=0
candidates_list=[]
candidate_votes={}
num_of_winner=0
winner_list=[]
winner=""

### Read in a .csv file
csv_file=os.path.join("Resources", "election_data.csv")
with open(csv_file,"r") as csv_file:
           csv_reader=csv.reader(csv_file,delimiter=',')
           #skip header
           next(csv_reader)
           for row in csv_reader:
               votes_total += 1

               candidate=row[2]

               if candidate not in candidates_list:
                   candidates_list.append(candidate)
                   candidate_votes[candidate] = 1

               candidate_votes[candidate]=candidate_votes[candidate] +1

winner1 = [(value, key) for key, value in candidate_votes.items()]
winner=max(winner1)[1]

#### output file
election_file = os.path.join("analysis", "election_data.txt")
with open(election_file, "w") as outfile:

    print("Election Results")
    print("-------------------------")
    print("Total votes %d" % votes_total)
    print("-------------------------")

    #voter_output1=
    #voter_output2=
    outfile.write("Election Results\n")
    outfile.write("-------------------------\n")

    for candidate in candidate_votes:
        votes = candidate_votes[candidate]
        vote_percentage = float(votes)/float(votes_total)*100
        #if (votes > num_of_winner):
         #   winner_count = votes
          #  winner2 = candidate
        voter_output = f"{candidate}: {vote_percentage:.3f}% ({votes})\n"

        #print("Total votes %d" % votes_total)
        #print("-------------------------")
        print(voter_output)

        outfile.write(voter_output)

    winner_summary = (
        f"Winner: {winner}\n"
        #f"Winner: max(winner1)[1]\n"
    )
    outfile.write("-------------------------\n")
    print("-------------------------")
    print(winner_summary)
    outfile.write(winner_summary)
    outfile.write("-------------------------\n")

print("-------------------------")

#print(f"Winner:  {votes_per_candidate[0][0][0]}")
#print("-------------------------")


'''
Created on 10.10.2016

@author: michael
'''
import unittest
from injector import Injector
from alex_test_utils import TestEnvironment, MODE_SIMPLE,\
    load_table_data
from alexandriabase import AlexBaseModule
from alexandriabase.daos import DaoModule
from alexplugins.systematic.tkgui import SystematicGuiPluginModule
from alexplugins.systematic import SYSTEMATIC_DAO_KEY, SYSTEMATIC_SERVICE_KEY,\
    SYSTEMATIC_PDF_GENERATION_SERVICE_KEY

class TestDaoModuleConfiguration(unittest.TestCase):

    def setUp(self):
        self.env = TestEnvironment(mode=MODE_SIMPLE)

    def tearDown(self):
        self.env.cleanup()

    def test_configuration(self):

        injector = Injector([
                        AlexBaseModule(),
                        DaoModule(),
                        SystematicGuiPluginModule()
                         ])

        injector.get(SYSTEMATIC_DAO_KEY)
        injector.get(SYSTEMATIC_SERVICE_KEY)
        injector.get(SYSTEMATIC_PDF_GENERATION_SERVICE_KEY)

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()


from pxr import *

import struct
import sys
import os.path
import time

import usdUtils

__all__ = ['usdMaterialWithObjMtl']

def linesContinuation(fileHandle):
    for line in fileHandle:
        line = line.rstrip('\n')
        line = line.rstrip()
        while line.endswith('\\'):
            thisLine = line[:-1]
            nextLine = next(fileHandle).rstrip('\n')
            nextLine = nextLine.strip()
            line = thisLine + ' ' + nextLine
        yield line

def usdMaterialWithObjMtl(converter, filename):
    if not os.path.isfile(filename):
        usdUtils.printWarning("Can't load material file. File not found: " + filename)
        return

    with open(filename, errors='ignore') as file:
        material = None

        primvarName = 'st'
        wrapS = usdUtils.WrapMode.repeat
        wrapT = usdUtils.WrapMode.repeat
        scaleFactor=None

        for line in linesContinuation(file):
            line = line.strip()
            if not line or '#' == line[0]:
                continue

            arguments = list(filter(None, line.split(' ')))
            command = arguments[0]
            arguments = arguments[1:]

            if 'newmtl' == command:
                primvarName = 'st'
                wrapS = usdUtils.WrapMode.repeat
                wrapT = usdUtils.WrapMode.repeat
                scaleFactor=None

                matName = ' '.join(arguments)
                converter.setMaterial(matName)
                material = usdUtils.Material(matName)
                converter.materialsByName[matName] = material
            elif material is not None:
                if 'Kd' == command:
                    diffuseColor = arguments
                    if usdUtils.InputName.diffuseColor in material.inputs:
                        material.inputs[usdUtils.InputName.diffuseColor].scale = diffuseColor
                    else:
                        material.inputs[usdUtils.InputName.diffuseColor] = diffuseColor
                        scaleFactor = diffuseColor
                elif 'd' == command:
                    material.inputs[usdUtils.InputName.opacity] = arguments[0] if len(arguments) > 0 else 1
                elif 'map_Kd' == command:
                    textureFilename = usdUtils.resolvePath(' '.join(arguments), converter.srcFolder, converter.searchPaths)
                    material.inputs[usdUtils.InputName.diffuseColor] = usdUtils.Map('rgb', textureFilename, None, primvarName, wrapS, wrapT, scaleFactor)
                elif 'map_bump' == command or 'bump' == command:
                    textureFilename = usdUtils.resolvePath(' '.join(arguments), converter.srcFolder, converter.searchPaths)
                    material.inputs[usdUtils.InputName.normal] = usdUtils.Map('rgb', textureFilename, None, primvarName, wrapS, wrapT)
                elif 'map_ao' == command:
                    textureFilename = usdUtils.resolvePath(' '.join(arguments), converter.srcFolder, converter.searchPaths)
                    material.inputs[usdUtils.InputName.occlusion] = usdUtils.Map('rgb', textureFilename, None, primvarName, wrapS, wrapT)
                elif 'map_metallic' == command:
                    textureFilename = usdUtils.resolvePath(' '.join(arguments), converter.srcFolder, converter.searchPaths)
                    material.inputs[usdUtils.InputName.metallic] = usdUtils.Map('rgb', textureFilename, None, primvarName, wrapS, wrapT)
                elif 'map_roughness' == command:
                    textureFilename = usdUtils.resolvePath(' '.join(arguments), converter.srcFolder, converter.searchPaths)
                    material.inputs[usdUtils.InputName.roughness] = usdUtils.Map('rgb', textureFilename, None, primvarName, wrapS, wrapT)


import lamplib
import time
import sys
import random
speed = float(sys.argv[1])
dim = 1
#lamps = ('28','3C','3B','3A','39','38','29','73','33','4F','12','21','1B','2A','32','31','24','23','14','30','10')
lamps = ('28','3C','3B','3A','39','38','29','73','33','4F','32','24','31','30','10')
#lamps = ('33','4F','32','31','30','10')
lamp = 0
l = len(lamps)

lamplib.fade('00',0,0,0,20.*speed)
while 1:
    lamp += 1
    off = lamps[lamp%l]
    on  = lamps[(lamp+5)%l]
    r = int(random.random()*255/dim)
    g = int(random.random()*255/dim)
    b = int(random.random()*255/dim)
    #lamplib.fade(on,0,0,255,30.*speed)
    lamplib.fade(on,r,g,b,10.*speed)
    lamplib.fade(off,0,0,0,10.*speed)
    time.sleep(6./speed)

while 1:
    fadeOff(lamps[lamp])
    lamp+=1
    if lamp == len(lamps):
        lamp = 0
    lamplib.fade(lamps[lamp],127,0,127,300.*speed)
    time.sleep(0.25/speed)
    lamplib.fade(lamps[lamp],255,0,0,150.*speed)
    #time.sleep(0.25/speed)

#    fadeOn(lamps[lamp])
    time.sleep(2./speed)


"""
Sum of all Subarrays
https://www.geeksforgeeks.org/sum-of-all-subarrays/
"""
from typing import List
from test_tool import assert_value

class Solution:
    def subarraySum(self, arr: List[int]) -> int:
        res = 0
        n = len(arr)
        for i in range(n):
            res += (i + 1) * (n - i) * arr[i]

        return res

    def _subarraySum_brute_force(self, arr: List[int]) -> int:
        res = 0
        n = len(arr)
        for start in range(n):
            curr = 0
            for end in range(start, n):
                curr += arr[end]
                res += curr
        return res

assert_value(20, Solution().subarraySum, arr=[1, 2, 3])


from datetime import date
from dateutil.relativedelta import relativedelta

class Timing:

    def calc_growth_begin_date(
        self,
        growth_begin_month: int,
        analysis_start_date: date
    ) -> date:
        return analysis_start_date+relativedelta(months=growth_begin_month-1)

    def __init__(
        self,
        analysis_length_years: int,
        analysis_start_date: date,
        growth_begin_month: int,
        residual_months: int=12
    ):
        self.analysis_length_years = analysis_length_years
        self.analysis_length_months = analysis_length_years * 12

        self.analysis_start_date = analysis_start_date
        self.analysis_start_month = 1
        self.residual_months = residual_months

        self.growth_begin_month = growth_begin_month
        self.growth_begin_date = self.calc_growth_begin_date(growth_begin_month, analysis_start_date)

    def json(self):
        return self.__dict__


class Solution:
    def minCostClimbingStairs(self, cost):
        # dfs 不带记忆化，超时
        ans = float("inf")

        def helper(cur, res):
            nonlocal ans
            if cur >= len(cost):
                if res < ans:
                    ans = res
                return
            helper(cur + 1, res + cost[cur])
            helper(cur + 2, res + cost[cur])

        helper(0, 0)
        helper(1, 0)
        return ans

cost = [3,5,2,19,7]
print(Solution().minCostClimbingStairs(cost))

746. 使用最小花费爬楼梯-3.py

746. 使用最小花费爬楼梯-3.py


import pandas as pd
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.decomposition import NMF

# Enable oneDNN optimization
TF_ENABLE_ONEDNN_OPTS=1

# List of GPUs set up for acceleration
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))

# Seed for reproducibility
np.random.seed(5)

# Loading TCGA-BRCA data
data_matrix = pd.read_csv("../Data/TCGA_BRCA_0toAvg.csv", index_col=0)
data_tensor = tf.constant(data_matrix, dtype=tf.float32)

# NMF function
def compute_nmf(data, rank, max_iter=200, lr=0.01):
    rows, cols = data.shape
    W = tf.Variable(tf.abs(tf.random.normal((rows, rank))), dtype=tf.float32)
    H = tf.Variable(tf.abs(tf.random.normal((rank, cols))), dtype=tf.float32)
    optimizer = tf.optimizers.Adam(lr)

    for iteration in range(max_iter):
        with tf.GradientTape() as tape:
            WH = tf.matmul(W, H)
            loss = tf.reduce_sum(tf.square(data - WH))
        gradients = tape.gradient(loss, [W, H])
        optimizer.apply_gradients(zip(gradients, [W, H]))
    return W, H, loss.numpy()

# Compute NMF for a range of ranks
ranks = range(1, 50)
errors = []

for rank in ranks:
    W, H, error = compute_nmf(data_tensor, rank)
    errors.append(error)
    print(f"Rank {rank} error: {error}")

# Display errors
for rank, error in zip(ranks, errors):
    print(f"Rank {rank}: {error}")

plt.figure(figsize=(10, 6))
plt.plot(ranks, errors, marker='o', linestyle='-')
plt.title('Reconstruction Error vs Rank')
plt.xlabel('Rank')
plt.ylabel('Reconstruction Error')
plt.grid(True)
plt.savefig('"../Figures/rank_evolution_plot.pdf', format='pdf', bbox_inches='tight')
pd.DataFrame(errors).to_csv("../Results/RecErrors.csv", index=False)