# -*- coding: utf-8 -*-
"""
Client for communicating with the Enterprise API.
"""

import json
from collections import OrderedDict
from logging import getLogger

from edx_rest_api_client.client import EdxRestApiClient
from requests.exceptions import ConnectionError, Timeout  # pylint: disable=redefined-builtin
from slumber.exceptions import HttpNotFoundError, SlumberBaseException

from django.conf import settings

from enterprise import utils
from enterprise.api_client.lms import JwtLmsApiClient

LOGGER = getLogger(__name__)

class EnterpriseCatalogApiClient(JwtLmsApiClient):
    """
    Object builds an API client to make calls to the Enterprise Catalog API.
    """

    API_BASE_URL = settings.ENTERPRISE_CATALOG_INTERNAL_ROOT_URL + '/api/v1/'
    ENTERPRISE_CATALOG_ENDPOINT = 'enterprise-catalogs'
    GET_CONTENT_METADATA_ENDPOINT = ENTERPRISE_CATALOG_ENDPOINT + '/{}/get_content_metadata'
    REFRESH_CATALOG_ENDPOINT = ENTERPRISE_CATALOG_ENDPOINT + '/{}/refresh_metadata'
    ENTERPRISE_CUSTOMER_ENDPOINT = 'enterprise-customer'
    APPEND_SLASH = True

    def __init__(self, user=None):
        user = user if user else utils.get_enterprise_worker_user()
        super(EnterpriseCatalogApiClient, self).__init__(user)

    @JwtLmsApiClient.refresh_token
    def create_enterprise_catalog(
            self,
            catalog_uuid,
            enterprise_id,
            enterprise_name,
            title,
            content_filter,
            enabled_course_modes,
            publish_audit_enrollment_urls):
        """Creates an enterprise catalog."""
        endpoint = getattr(self.client, self.ENTERPRISE_CATALOG_ENDPOINT)
        post_data = {
            'uuid': catalog_uuid,
            'title': title,
            'enterprise_customer': enterprise_id,
            'enterprise_customer_name': enterprise_name,
            'content_filter': content_filter,
            'enabled_course_modes': enabled_course_modes,
            'publish_audit_enrollment_urls': json.dumps(publish_audit_enrollment_urls),
        }
        try:
            LOGGER.info(
                'Creating Enterprise Catalog %s in the Enterprise Catalog Service with params: %s',
                catalog_uuid,
                json.dumps(post_data)
            )
            return endpoint.post(post_data)
        except (SlumberBaseException, ConnectionError, Timeout) as exc:
            LOGGER.exception(
                'Failed to create EnterpriseCustomer Catalog [%s] in enterprise-catalog due to: [%s]',
                catalog_uuid, str(exc)
            )
            return {}

    @JwtLmsApiClient.refresh_token
    def get_enterprise_catalog(self, catalog_uuid, should_raise_exception=True):
        """
        Gets an enterprise catalog.

        Arguments:
            catalog_uuid (uuid): The uuid of an EnterpriseCatalog instance
            should_raise_exception (bool): Whether an exception should be logged if
                a catalog does not yet exist in enterprise-catalog. Defaults to True.

        Returns:
            dict: a dictionary representing an enterprise catalog
        """
        endpoint = getattr(self.client, self.ENTERPRISE_CATALOG_ENDPOINT)(catalog_uuid)
        try:
            return endpoint.get()
        except (SlumberBaseException, ConnectionError, Timeout) as exc:
            if should_raise_exception:
                LOGGER.exception(
                    'Failed to get EnterpriseCustomer Catalog [%s] in enterprise-catalog due to: [%s]',
                    catalog_uuid, str(exc)
                )
            return {}

    @staticmethod
    def get_content_metadata_url(uuid):
        """
        Get the url for the preview information for an enterprise catalog
        """
        return EnterpriseCatalogApiClient.API_BASE_URL + \
            EnterpriseCatalogApiClient.GET_CONTENT_METADATA_ENDPOINT.format(uuid)

    @JwtLmsApiClient.refresh_token
    def update_enterprise_catalog(self, catalog_uuid, **kwargs):
        """Updates an enterprise catalog."""
        endpoint = getattr(self.client, self.ENTERPRISE_CATALOG_ENDPOINT)(catalog_uuid)
        try:
            LOGGER.info(
                'Updating Enterprise Catalog %s in the Enterprise Catalog Service with params: %s',
                catalog_uuid,
                json.dumps(kwargs)
            )
            return endpoint.put(kwargs)
        except (SlumberBaseException, ConnectionError, Timeout) as exc:
            LOGGER.exception(
                'Failed to update EnterpriseCustomer Catalog [%s] in enterprise-catalog due to: [%s]',
                catalog_uuid, str(exc)
            )
            return {}

    @JwtLmsApiClient.refresh_token
    def delete_enterprise_catalog(self, catalog_uuid):
        """Deletes an enterprise catalog."""
        endpoint = getattr(self.client, self.ENTERPRISE_CATALOG_ENDPOINT)(catalog_uuid)
        try:
            return endpoint.delete()
        except HttpNotFoundError:
            LOGGER.warning(
                'Deleted EnterpriseCustomerCatalog [%s] that was not in enterprise-catalog',
                catalog_uuid
            )
            return {}
        except (SlumberBaseException, ConnectionError, Timeout) as exc:
            LOGGER.exception(
                'Failed to delete EnterpriseCustomer Catalog [%s] in enterprise-catalog due to: [%s]',
                catalog_uuid, str(exc)
            )
            return {}

    @JwtLmsApiClient.refresh_token
    def get_content_metadata(self, enterprise_customer, enterprise_catalogs=None):
        """
        Return all content metadata contained in the catalogs associated with the EnterpriseCustomer.

        Arguments:
            enterprise_customer (EnterpriseCustomer): The EnterpriseCustomer to return content metadata for.
            enterprise_catalogs (EnterpriseCustomerCatalog): Optional list of EnterpriseCustomerCatalog objects.

        Returns:
            list: List of dicts containing content metadata.
        """
        content_metadata = OrderedDict()
        enterprise_customer_catalogs = enterprise_catalogs or enterprise_customer.enterprise_customer_catalogs.all()

        for enterprise_customer_catalog in enterprise_customer_catalogs:
            catalog_uuid = enterprise_customer_catalog.uuid
            endpoint = getattr(self.client, self.GET_CONTENT_METADATA_ENDPOINT.format(catalog_uuid))
            try:
                response = endpoint.get()
                for item in utils.traverse_pagination(response, endpoint):
                    content_id = utils.get_content_metadata_item_id(item)
                    content_metadata[content_id] = item
            except (SlumberBaseException, ConnectionError, Timeout) as exc:
                LOGGER.exception(
                    'Failed to get content metadata for Catalog [%s] in enterprise-catalog due to: [%s]',
                    catalog_uuid, str(exc)
                )

        return list(content_metadata.values())

    @JwtLmsApiClient.refresh_token
    def refresh_catalogs(self, enterprise_catalogs):
        """
        Kicks off async tasks to refresh catalogs so recent changes will populate to production without needing to wait
        for the daily jobs to run

        Arguments:
            enterprise_catalogs (EnterpriseCustomerCatalog): List of EnterpriseCustomerCatalog objects to refresh

        Returns:
            Dict: Dict of async task ids for each catalog id
        """
        refreshed_catalogs = {}
        failed_to_refresh_catalogs = []
        for enterprise_customer_catalog in enterprise_catalogs:
            catalog_uuid = enterprise_customer_catalog.uuid
            endpoint = getattr(self.client, self.REFRESH_CATALOG_ENDPOINT.format(catalog_uuid))
            try:
                response = endpoint.post()
                refreshed_catalogs[catalog_uuid] = response['async_task_id']
            except (SlumberBaseException, ConnectionError, Timeout) as exc:
                LOGGER.exception(
                    'Failed to refresh catalog data for catalog [%s] in enterprise-catalog due to: [%s]',
                    catalog_uuid, str(exc)
                )
                failed_to_refresh_catalogs.append(catalog_uuid)

        return refreshed_catalogs, failed_to_refresh_catalogs

    @JwtLmsApiClient.refresh_token
    def contains_content_items(self, catalog_uuid, content_ids):
        """
        Checks whether an enterprise catalog contains the given content

        The enterprise catalog endpoint does not differentiate between course_run_ids and program_uuids so they can
        be used interchangeably. The two query parameters are left in for backwards compatability with edx-enterprise.
        """
        query_params = {'course_run_ids': content_ids}
        endpoint = getattr(self.client, self.ENTERPRISE_CATALOG_ENDPOINT)(catalog_uuid)
        return endpoint.contains_content_items.get(**query_params)['contains_content_items']

    @JwtLmsApiClient.refresh_token
    def enterprise_contains_content_items(self, enterprise_uuid, content_ids):
        """
        Checks whether an enterprise customer has any catalogs that contain the provided content ids.

        The endpoint does not differentiate between course_run_ids and program_uuids so they can be used
        interchangeably. The two query parameters are left in for backwards compatability with edx-enterprise.
        """
        query_params = {'course_run_ids': content_ids}
        endpoint = getattr(self.client, self.ENTERPRISE_CUSTOMER_ENDPOINT)(enterprise_uuid)
        return endpoint.contains_content_items.get(**query_params)['contains_content_items']

class NoAuthEnterpriseCatalogClient:
    """
    Class to build a enterprise catalog client to make calls to the discovery service.
    """

    API_BASE_URL = settings.ENTERPRISE_CATALOG_INTERNAL_ROOT_URL
    APPEND_SLASH = False

    def __init__(self):
        """
        Create an enterprise catalog client.
        """
        self.client = EdxRestApiClient(self.API_BASE_URL, append_slash=self.APPEND_SLASH)

    def get_health(self):
        """
        Retrieve health details for enterprise catalog service.

        Returns:
            dict: Response containing enterprise catalog service health.
        """
        return self.client.health.get()


import plotly.graph_objects as ply
from plotly.subplots import make_subplots
import numpy as np
from math import pi, sqrt, exp, sin

def f(x):
    return x

def f_prime(x):
    h = 0.0001
    return (f(x + h) - f(x)) / h

def I(a, b):
    n = 10000
    delta_x = (b - a) / n
    sum_ = 0
    for i in range(1, n + 1):
        sum_ += f(a + delta_x * i) + f(a + delta_x * (i - 1))
    return sum_ * delta_x / 2

def gamma(z):
    # Lanczos approximation
    # https://en.wikipedia.org/wiki/Lanczos_approximation
    g = 7
    p = [
        0.99999999999980993,
        676.5203681218851,
        -1259.1392167224028,
        771.32342877765313,
        -176.61502916214059,
        12.507343278686905,
        -0.13857109526572012,
        9.9843695780195716e-6,
        1.5056327351493116e-7
    ]

    if z < 0.5:
        if z == 0.0:
            z = 0.00000001
        y = pi / (sin(pi * z) * gamma(1 - z))  # Reflection formula
    else:
        z -= 1
        x = p[0]
        for i in range(1, len(p)):
            x += p[i] / (z + i)
        t = z + g + 0.5
        y = sqrt(2 * pi) * t ** (z + 0.5) * exp(-t) * x
    return y

def D(a, x):
    def binomial_coeffs(p, k):
        if p > 0:
            return (-1)**k * gamma(p + 1) / (gamma(k + 1) * gamma(p - k + 1))
        return gamma(-p + k) / (gamma(k + 1) * gamma(-p))

    # Grunwald Letnikov method
    # bounds of integral are 0 and x
    if a == 0.0:
        return f(x)
    h = x / 142
    sum_GL = 0
    for m in range(142):
        sum_GL += f(x - m*h) * binomial_coeffs(a, m)
    if a > 0:
        return sum_GL / (h ** a)
    elif a < 0:
        return sum_GL * (h ** -a)

def main():
    num_of_points = 50
    num_of_steps = 30
    x_vals = np.arange(0.0001, 10.0, 10.0 / num_of_points)
    fig = make_subplots(rows=1, cols=2, specs=[[{'type': 'scatter'}, {'type': 'scatter3d'}]])

    fig.add_trace(
        ply.Scatter(
            name='f(x)',
            visible=True,
            line=dict(color='#00FF00'),
            x=x_vals,
            y=f(x_vals)
        ),
        row=1, col=1
    )

    fig.add_trace(
        ply.Scatter(
            name='f\'(x)',
            visible=True,
            line=dict(color='#FF0000'),
            x=x_vals,
            y=f_prime(x_vals)
        ),
        row=1, col=1
    )

    fig.add_trace(
        ply.Scatter(
            name='∫f(x)dx',
            visible=True,
            line=dict(color='#0000FF'),
            x=x_vals,
            y=I(0.0, x_vals)
        ),
        row=1, col=1
    )

    steps = []
    c = 0
    color_step = 255 // (num_of_steps // 2)
    for i in np.linspace(-1.0, 1.0, num_of_steps):
        if i < 0:
            blue = 255 - color_step * c
            rgb = 'rgb(0,{0},{1})'.format(255 - blue, blue)
        else:
            green = 255 - color_step * (c - num_of_steps // 2)
            rgb = 'rgb({0},{1},0)'.format(255 - green, green)

        DI = D(i, x_vals)
        fig.add_trace(
            ply.Scatter(
                name='alpha = ' + str(round(i, 2)),
                visible=False,
                line=dict(color=rgb, dash='dot'),
                x=x_vals,
                y=DI
            ),
            row=1, col=1
        )

        fig.add_trace(
            ply.Scatter3d(
                line=dict(color=rgb, width=20),
                x=[c] * num_of_points,
                y=x_vals,
                z=DI
            ),
            row=1, col=2
        )

        # Extremely scuffed but whatever
        step = dict(
            method='update',
            args=[dict(visible=[True] * 3 + [False, True] * num_of_steps)]
        )
        step['args'][0]['visible'][2 * c + 3] = True
        steps.append(step)
        c += 1

    fig.data[0].visible = True
    sliders = [dict(
        active=0,
        steps=steps
    )]

    fig.update_layout(
        sliders=sliders,
        showlegend=False,
        scene=dict(
            xaxis_title='step',
            yaxis_title='x',
            zaxis_title='f(x)',
            xaxis=dict(range=[-1, num_of_steps + 1]),
            yaxis=dict(range=[0.0, 10.0]),
            zaxis=dict(range=[-40, 40])
        )
    )

    fig.update_yaxes(range=[-20, 20], secondary_y=False)

    fig.show()

if __name__ == '__main__':
    main()


import http.client, urllib.parse
import time
import json

conn = http.client.HTTPConnection('api.positionstack.com')
elapsed_time = []
start_time = time.time()
fail = []

access_key = input("Please ask Vivek To Provide")

with open("address.txt") as file:
    for item in file:
        print(item)
        params = urllib.parse.urlencode({
            'access_key': access_key,
            'query': item,
            'limit': 1,
        })

        conn.request('GET', '/v1/forward?{}'.format(params))
        res = conn.getresponse()
        data = res.read()
        time.sleep(3)
        pos_stack_api = data.decode('utf8').replace("'", '"')
        json_output = json.loads(pos_stack_api)
        if len(json_output['data']) > 0:
            try:
                lat, long = json_output["data"][0]['latitude'], json_output["data"][0]['longitude']
            except TypeError:
                print("\nOverloading server. Retrying after pause...\n")
                elapsed_time.append(time.time() - start_time)
                fail.append(1)
                time.sleep(60)
                continue
        else:
            print("\nLocation added!\n")
            elapsed_time.append(time.time() - start_time)
            fail.append(item)
            break
        print("The latitude and longitude of Address: " + str(item) + " are " + str(lat) + " and " + str(long))


def _execve(self, program, argv, envp):
        """
        Load `program` and establish program state, such as stack and arguments.

        :param program str: The ELF binary to load
        :param argv list: argv array
        :param envp list: envp array
        """
        argv = [] if argv is None else argv
        envp = [] if envp is None else envp

        logger.debug(f"Loading {program} as a {self.arch} elf")

        self.load(program, envp)
        self._arch_specific_init()

        self._stack_top = self.current.STACK
        self.setup_stack([program] + argv, envp)

        nprocs = len(self.procs)
        nfiles = len(self.files)
        assert nprocs > 0
        self.running = list(range(nprocs))

        # Each process can wait for one timeout
        self.timers = [None] * nprocs
        # each fd has a waitlist
        self.rwait = [set() for _ in range(nfiles)]
        self.twait = [set() for _ in range(nfiles)]

        # Install event forwarders
        for proc in self.procs:
            self.forward_events_from(proc)


def cancel(self, pk=None, fail_if_not_running=False, **kwargs):
        """Cancel a currently running job.

        Fails with a non-zero exit status if the job cannot be canceled.
        You must provide either a pk or parameters in the job's identity.

        =====API DOCS=====
        Cancel a currently running job.

        :param pk: Primary key of the job resource to restart.
        :type pk: int
        :param fail_if_not_running: Flag that if set, raise exception if the job resource cannot be canceled.
        :type fail_if_not_running: bool
        :param `**kwargs`: Keyword arguments used to look up job resource object to restart if ``pk`` is not
                           provided.
        :returns: A dictionary of two keys: "status", which is "canceled", and "changed", which indicates if
                  the job resource has been successfully canceled.
        :rtype: dict
        :raises tower_cli.exceptions.TowerCLIError: When the job resource cannot be canceled and
                                                    ``fail_if_not_running`` flag is on.
        =====API DOCS=====
        """
        # Search for the record if pk not given
        if not pk:
            existing_data = self.get(**kwargs)
            pk = existing_data['id']

        cancel_endpoint = '%s%s/cancel/' % (self.endpoint, pk)
        # Attempt to cancel the job.
        try:
            client.post(cancel_endpoint)
            changed = True
        except exc.MethodNotAllowed:
            changed = False
            if fail_if_not_running:
                raise exc.TowerCLIError('Job not running.')

        # Return a success.
        return {'status': 'canceled', 'changed': changed}


import logging, time,os, datetime, platform
from logging.handlers import RotatingFileHandler

def path_converter(input_string):
        if platform.system() == 'Windows':
                return input_string.replace("/", "\\")
        else:
                return input_string.replace("\\", "/")

class Logger():
    def __init__(self, log_file):
        dateTag = datetime.datetime.now().strftime("%Y-%b-%d_%H-%M-%S")
        self.log_location = path_converter(log_file + "\oauth-output-%s.log" % dateTag)
        self.log_file = open(self.log_location, "w+", 1)
        self.render_output = []
        self.log("OAuth Troubleshooting Tool v0.1\n\n")
        self.log("DISCLAIMER: This is an open source tool meant to help verify OAuth client connections. It is not intended for production use.\n\n\n")

    def log(self, message : str, type="INFO"):
        if type == "INFO":
            print(message.replace("\n","",1))
            self.log_file.write(message)
            self.render_output.append(message.encode('utf-8'))
        if type == "ERROR":
            message += ("\n\tWARNING: You should consult with your internal IT team to resolve this issue."
                        "\n\tErrors indicate that there are problems with your OAuth client configuration outside of Veeva Vault.\n\n")
            print(message.replace("\n","",1))
            self.log_file.write(message)
            self.render_output.append(message.encode('utf-8'))


input_numbers = int(input())

odd_sum = 0
even_sum = 0

for index in range(0, input_numbers):
    number = int(input())
    if index % 2 == 0:
        even_sum = even_sum + number
    else:
        odd_sum = odd_sum + number

difference = abs(even_sum-odd_sum)

if even_sum == odd_sum:
    print('Yes')
    print(f'Sum = {even_sum}')
else:
    print('No')
    print(f'Diff = {difference}')


import sys
import os

PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))

import unittest
import random
from src.pypfp.pfp import MultiProcessor
from src.pypfp import Result
import traceback
import inspect
import time

CONTEXT = {
    'counter1': [0,9,8,7,6,5],  # SUM=35
    'counter2': [2,4,6,8]       # PRODUCT=384
}

def counter1(q, context: dict, args: dict):
    r = Result(function_name=inspect.currentframe().f_code.co_name)
    r.result = dict()
    r.result['Count'] = 0
    r.result['Answer'] = None
    elements = list()
    if inspect.currentframe().f_code.co_name in context:
        elements = context[inspect.currentframe().f_code.co_name]
    count = len(elements)
    r.result['Count'] = count
    if args is not None:
        if 'Operation' in args:
            if args['Operation'].upper() == 'ADD':
                r.result['Answer'] = 0
                for num in elements:
                    r.result['Answer'] += num
            elif args['Operation'].upper() == 'MULTIPLY':
                r.result['Answer'] = 1
                for num in elements:
                    r.result['Answer'] *= num
    time.sleep(0.3)
    try:
        q.put(r)
    except:
        traceback.print_exc()

def counter2(q, context: dict, args: dict):
    r = Result(function_name=inspect.currentframe().f_code.co_name)
    r.result = dict()
    r.result['Count'] = 0
    r.result['Answer'] = None
    elements = list()
    if inspect.currentframe().f_code.co_name in context:
        elements = context[inspect.currentframe().f_code.co_name]
    count = len(elements)
    r.result['Count'] = count
    if args is not None:
        if 'Operation' in args:
            if args['Operation'].upper() == 'ADD':
                r.result['Answer'] = 0
                for num in elements:
                    r.result['Answer'] += num
            elif args['Operation'].upper() == 'MULTIPLY':
                r.result['Answer'] = 1
                for num in elements:
                    r.result['Answer'] *= num
    try:
        q.put(r)
    except:
        traceback.print_exc()

class DummyQueue:

    def __init__(self):
        self.result = None

    def put(self, result):
        self.result = result

class TestBasicMultiProcessing(unittest.TestCase):

    def test_counter1_basic_test(self):
        q = DummyQueue()
        counter1(q=q, context=CONTEXT, args=None)
        self.assertIsNotNone(q.result.result)
        self.assertIsInstance(q.result, Result)
        self.assertIsInstance(q.result.result, dict)
        self.assertTrue('Count' in q.result.result)
        self.assertTrue('Answer' in q.result.result)
        self.assertIsInstance(q.result.result['Count'], int)
        self.assertTrue(q.result.result['Count'] > 0)
        self.assertEqual(6, q.result.result['Count'])

    def test_counter2_basic_test(self):
        q = DummyQueue()
        counter2(q=q, context=CONTEXT, args=None)
        self.assertIsNotNone(q.result.result)
        self.assertIsInstance(q.result, Result)
        self.assertIsInstance(q.result.result, dict)
        self.assertTrue('Count' in q.result.result)
        self.assertTrue('Answer' in q.result.result)
        self.assertIsInstance(q.result.result['Count'], int)
        self.assertTrue(q.result.result['Count'] > 0)
        self.assertEqual(4, q.result.result['Count'])

    def test_multiprocessing(self):
        m = MultiProcessor(context=CONTEXT)
        m.register_function(f=counter1, f_args={'Operation': 'ADD'})
        m.register_function(f=counter2, f_args={'Operation': 'MULTIPLY'})
        m.execute_parallel()
        self.assertEqual(len(m.results), 2)
        for result in m.results:
            self.assertIsInstance(result, Result)
            self.assertTrue(result.function_name in CONTEXT)
            expected_count = len(CONTEXT[result.function_name])
            expected_answer = 0
            if result.function_name == 'counter1':
                expected_answer = 35
            elif result.function_name == 'counter2':
                expected_answer = 384
            self.assertEqual(expected_count, result.result['Count'])
            self.assertEqual(expected_answer, result.result['Answer'])

# EOF


import argparse
import os
import sys

def input_generator(input_file_name: str, message: str):
	chunksize = 20
	if not input_file_name:
		for item in message:
			yield item
	else:
		with open(input_file_name, "r") as f:
			while True:
				chunk = f.read(chunksize)
				for item in chunk:
					yield item
				if not chunk:
					break

def crypt(img_name: str, input_file_name: str, output_img_name: str) -> None:
	img_size = os.stat(img_name).st_size
	message = ""
	if input_file_name:
		text_size = os.stat(input_file_name).st_size
	else:
		print("Enter your text")
		message = sys.stdin.read()
		text_size = len(message)

	degree = int(input("Enter degree(1/2/4/8): "))

	if text_size >= img_size * degree / 8 - 54:
		print("Text is too long!")
		return

	with open(img_name, "rb") as img_bmp, open(output_img_name, "wb") as edited_bmp:

		first54 = img_bmp.read(54)
		edited_bmp.write(first54)

		img_mask = (255 << degree) % 256
		text_mask = 3 << (8 - degree)

		for symbol in input_generator(input_file_name, message):
			symbol = ord(symbol)
			for chunks in range(0, 8, degree):  #write one symbol from message to img
				img_byte = int.from_bytes(img_bmp.read(1), sys.byteorder) & img_mask
				bits = symbol & text_mask
				bits >>= (8-degree)

				img_byte |= bits

				edited_bmp.write(img_byte.to_bytes(1, sys.byteorder))
				symbol <<= degree
		edited_bmp.write(img_bmp.read())

def decrypt(img_name: str, output_file_name: str) -> None:
	with open(img_name, "rb") as img, open(output_file_name, "w") as output_file:
		degree = int(input("Enter degree(1/2/4/8): "))
		img_mask = 2**degree - 1
		symb_number = int(input("Enter length: "))
		img.seek(54)

		for i in range(symb_number):
			cur_symb = 0
			for chunks in range(0, 8, degree):  #write one symbol from message to img
				img_byte = int.from_bytes(img.read(1), sys.byteorder) & img_mask
				cur_symb <<= degree
				cur_symb |= img_byte
			output_file.write(chr(cur_symb))

def main():
	parser = argparse.ArgumentParser()
	parser.add_argument("img_name", help="full input image name")
	parser.add_argument("outfile", help="full output file name")
	parser.add_argument("-a", "--action", help="what to do", choices=["crypt", "decrypt"], required=True)
	parser.add_argument("-i", "--inputfile", help="source text file")

	args = parser.parse_args()

	command = args.action
	img_name = args.img_name
	outputfile = args.outfile
	inputfile = args.inputfile
	if command == "crypt":
		crypt(img_name, inputfile, outputfile)
	elif command == "decrypt":
		decrypt(img_name, outputfile)

if __name__ == "__main__":
	main()


import yaml
import yamale
import pprint
import jsbeautifier

pp = pprint.PrettyPrinter(indent=4)
def pretty_print(*args, **kwargs):
    pp.pprint(*args, **kwargs)

def update_recursive(target, src):
    for k, v in src.items():
        if type(v) == dict:
            if k not in target:
                target[k] = {}
            update_recursive(target[k], src[k])
        else:
            target[k] = v

def load_configs():
    with open('dialects/typescript.yaml') as f:
        configs = {}
        features = {}
        for config in yaml.load_all(f):
            for root in config.keys():
                if root.startswith('feature '):
                    features[' '.join(root.split(' ')[1:])] = config[root]
                else:
                    configs[root] = config[root]
    return configs, features

def load_config(lang, *features):
    features = set(features)
    configs, config_features = load_configs()

    def build_dep_order(lang):
        if lang not in configs:
            raise Exception("invalid language target '%s'"%lang)
        config = configs[lang]
        deps = config['inheirit'] if 'inheirit' in config else []
        if type(deps) != list:
            deps = [deps]
        dep_order = []
        for dep in reversed(deps):
            dep_order += build_dep_order(dep)
        dep_order += [lang]
        return dep_order

    # build lang dependencies in order
    config = {}
    for dep in build_dep_order(lang):
        # print("Adding dep %s"%dep)
        update_recursive(config, configs[dep])
        # pretty_print(config)

    # add feature deps
    for feature in features:
        # print("adding feature %s"%feature)
        update_recursive(config, config_features[feature])
        # pretty_print(config)
    return config

def generate(config, names, state, actions):
    syntax = config['syntax']
    # print(list(config.keys()))
    type_conv = config['types']['decl']
    type_conv = { k: v.strip() for k, v in type_conv.items() }

    def format_type(t):
        if type(t) == dict:
            return type_conv['dict'].replace('...', ', '.join([
                '%s: %s'%(k, format_type(v))
                for k, v in t.items()
            ]))
        if type(t) == list:
            return type_conv['list'].replace('...', ', '.join(
                map(format_type, t)))
        if t in type_conv:
            return type_conv[t]
        return t

    def gen_interface(name, members):
        return (syntax['interface-decl'].strip()
            .replace('$name', name)
            .replace('$body', ' '.join([
                syntax['interface-elem'].strip()
                    .replace('$name', name)
                    .replace('$type', format_type(type))
                    for name, type in members.items()
                ])))

    def gen_enum(name, elements):
        return (syntax['enum']['decl'].strip()
            .replace('$type', name)
            .replace('$body', ' '.join([
                (syntax['enum']['decl_elem_0']
                if i == 0 else
                syntax['enum']['decl_elem'])
                    .strip()
                    .replace('$elem', elem)
                for i, elem in enumerate(elements)
            ])))

    def gen_fcn(name, params, return_type, body):
        return (syntax['fcn-signatures'].strip()
            .replace('$name', name)
            .replace('$params', ', '.join([
                syntax['type-signatures'].strip()
                    .replace('$var', name)
                    .replace('$type', format_type(type))
                for name, type in params.items()
            ]))
            .replace('$return-type', return_type)
            .replace('$body', body))

    def printjs(js):
        print(js)
        # print(jsbeautifier.beautify(js))

    printjs(gen_interface(names['StateType'], state))
    for name, action in actions.items():
        elem = 'ACTION_ELEM'
        params = { 'type': syntax['enum']['decl_type']
            .replace('$type', names['ActionEnumType'])
            .replace('$elem', elem)
        }
        params.update(action['params'])
        printjs(gen_interface(name, params))
    printjs(gen_enum(names['ActionEnumType'], [
        action for action in actions.keys()
    ]))
    for name, action in actions.items():
        printjs(gen_fcn(name, action['params'], name+'Action',
            syntax['action-ctor-body'].strip()
                .replace('$type', name+'Action')
                .replace('$elem', 'ACTION_ELEM')
                .replace('$params', ', '.join(action['params'].keys()))
            ))

    State, Actions = names['StateType'], names['ActionEnumType']

    def build_action(name, result):
        # print(name, result)
        if type(result) == dict:
            for key, expr in result.items():
                return (config['action-extensions'][key].strip()
                    .replace('$var', name)
                    .replace('$expr', expr))
        return str(result)

    State, Action = names['StateType'], names['ActionEnumType']
    printjs(gen_fcn('reducer', { 'state': State, 'action': Action }, State,
        syntax['enum']['match'].strip()
            .replace('$expr', 'state.type')
            .replace('$body', ' '.join([
                syntax['enum']['match-case'].strip()
                    .replace('$type', 'ActionType')
                    .replace('$elem', 'ACTION_ELEM')
                    .replace('$expr', syntax['reducer-state-return'].strip()
                        .replace('$cases', ''.join([
                            syntax['reducer-state-var'].strip()
                                .replace('$var', name)
                                .replace('$expr', build_action(name, result))
                            for name, result in action['reduce'].items()
                        ])))
                for action_name, action in actions.items()
            ])
        )))

if __name__ == '__main__':
    # load_config()
    for options in [
        [ 'typescript' ],
        [ 'typescript', 'typescript-enums' ],
        [ 'javascript' ],
    ]:
        print()
        print(options)
        generate(load_config(*options),
            { 'StateType': 'FooState', 'ActionEnumType': 'FooActions' },
            { 'foo': 'string', 'bar': [{ 'a': 'number', 'b': 'string' }] },
            {
                'add pillows': { 'params': { 'a': 'number' }, 'reduce': { 'foo': { 'append': 'fubar' } } },
                'add more pillows': { 'params': { 'a': 'number' }, 'reduce': { 'foo': '"fubar"' } },
            }
        )
    # pretty_print(load_config('typescript', 'string-enums'))


import os

from src.utils import utils

if __name__ == '__main__':

    # lang = 'java'
    lang = 'python'

    # corpus = 'wanetal'
    corpus = 'huetal'

    original_path = f'../../resources/corpora/{lang}/{corpus}/original'
    processed_path = f'../../resources/corpora/{lang}/{corpus}/processed'
    splitted_path = f'../../resources/corpora/{lang}/{corpus}/original'

    if not os.path.exists(processed_path):
        os.mkdir(processed_path)

    if not os.path.exists(splitted_path):
        os.mkdir(splitted_path)

    train_portion = 0.7
    valid_portion = 0.5

    print('\nProcessing Python corpus:')

    utils.split_python_dataset(original_path, splitted_path, train_portion, valid_portion)


import argparse
import boto3
import datetime
import pytz

default_objs = set(["rubrik_cluster_lock.txt", "rubrik_encryption_key_check.txt"])

class S3Client(object):
    def __init__(self, profile):
        self._session = boto3.Session(profile_name=profile)
        self.s3 = self._session.resource("s3")

    def list_buckets(self, visitor):
        for b in self.s3.buckets.all():
            #print("processing bucket '{}'".format(b.name))

            # try:
            #     num = sum(1 for _ in b.objects.limit(3))
            #     if num == 0:
            #         print("failed to load objects for {}".format(b.name))
            # except Exception as ex:
            #     print("failed to load objects for {}: {}".format(b.name, ex))
            #     continue

            visitor(b)

    @staticmethod
    def delete_bucket(bucket):
        print("deleting {}".format(bucket.name))
        try:
            bucket.objects.all().delete()
        except Exception as ex:
            print("failed to delete objects {}".format(ex))
            return

        try:
            bucket.delete()
        except Exception as ex:
            print("failed to delete bucket {}".format(ex))
            return

    @staticmethod
    def is_bucket_too_old(bucket, days):
        num = sum(1 for _ in bucket.objects.limit(3))
        if num > 2:
            # has objects other than the default objects
            return False

        days_ago = pytz.UTC.localize(datetime.datetime.now()) - datetime.timedelta(days=days)
        for o in bucket.objects.all():
            if o.key not in default_objs:
                # has objects other than the default objects
                return False

            if o.last_modified > days_ago:
                # object has been modified recently
                return False

        if bucket.creation_date > days_ago:
            # buckets has been created recently
            return False

        return True

    @staticmethod
    def is_bucket_deletable(bucket, prefix, days):
        if prefix != "" and bucket.name.startswith(prefix):
            return S3Client.is_bucket_too_old(bucket, 5)

        return S3Client.is_bucket_too_old(bucket, days)

    @staticmethod
    def delete_bucket_if_necessary(bucket):
        if not S3Client.is_bucket_too_old(bucket, 21):
            return

        print("bucket {} will be deleted".format(bucket.name))
        S3Client.delete_bucket(bucket)

def parse_args():
    parser = argparse.ArgumentParser(description='cleanup the s3 buckets for AppFlows')
    parser.add_argument(
        '--profile', '-p',
        dest='profile',
        type=str,
        help='the name of the AWS profile')
    parser.add_argument(
        '--name', '-n',
        dest='prefix',
        type=str,
        default="",
        help='the prefix of the AWS s3 buckets to be check and removed')
    parser.add_argument(
        '--days', '-d',
        dest='days',
        type=str,
        help='the age of the AWS s3 buckets to be removed (days)')
    parser.add_argument(
        '--not-dry-run',
        dest='not_dry_run',
        action='store_true',
        help='delete the found buckets')
    return parser.parse_args()

def main():
    args = parse_args()
    names_to_be_deleted = []

    buckets_to_be_deleted = []

    def handle(bucket):
        print("\"{}\",".format(bucket.name))
        if "appflows-ui-" in bucket.name:
            buckets_to_be_deleted.append(bucket)
        if not S3Client.is_bucket_deletable(bucket, args.prefix, 5):
            return

        #print("found bucket {} to be deleted".format(bucket.name))
        #buckets_to_be_deleted.append(bucket)

    s3 = S3Client(args.profile)
    s3.list_buckets(handle)

    print("buckets to be deleted:")
    for b in buckets_to_be_deleted:
        print("\t{}".format(b.name))

    if args.not_dry_run:
        print("deleting buckets:")
        for b in buckets_to_be_deleted:
            S3Client.delete_bucket(b)

if __name__ == "__main__":
    main()


from newsfetch import fetchTodayNews
from dotenv import load_dotenv
from datetime import date
import os
import time
import yagmail

ARTICLES_PER_DAY = 8
ALL_RECIPIENTS = [
    'jesalgandhi9988@gmail.com',
    'customdailynews@gmail.com',
    'jgandhi5@stevens.edu'
]

def generate_html(body):
    html = '''

                    The Daily Eight

Eight trending stories condensed, packaged, and delivered to your inbox every morning at 8 a.m.

                {content}

Thank you for reading today's issue.

Contact Me

Jesal Gandhi © 2022

    '''

    content = ''

    for k, v in body.items():
        # article title
        content += '
' + str(k+1) + ': ' + v[0] + '
 \n'

        # article photos
        for photo in v[2]:
            if 'resizer' not in photo:
                string = ' '.format(source=photo)
                content += string

        # article text
        content += '
' + v[1].strip('\n') + '
'

    return html.format(content=content).replace("\n", "")

def send_articles():
    load_dotenv()
    yag = yagmail.SMTP(os.getenv('GMAIL_USERNAME'), os.getenv('GMAIL_APP_PASSWORD'))
    body = fetchTodayNews(ARTICLES_PER_DAY)
    today = date.today().strftime("%B %d, %Y")

    html = generate_html(body)

    yag.send(bcc=ALL_RECIPIENTS, subject=today, contents=html)

    print(fetchTodayNews(ARTICLES_PER_DAY))
    print('Emails sent!')


def addSteps(dir, len, w, l, rx, ry, ax, ay):
    if dir == 'u':
        ry += len
        ay += len
        if ay >= l - 1:
            ay = l - 1
    elif dir == 'd':
        ry -= len
        ay -= len
        if ay < 0:
            ay = 0
    elif dir == 'r':
        rx += len
        ax += len
        if ax >= w - 1:
            ax = w - 1
    elif dir == 'l':
        rx -= len
        ax -= len
        if ax < 0:
            ax = 0
    return rx, ry, ax, ay

while True:
    dimensions = [int(inpt) for inpt in input().strip().split(" ")]
    (w, l) = (dimensions[0], dimensions[1])
    if w == 0 or l == 0:
        break
    (ax, ay) = (0, 0)
    (rx, ry) = (0, 0)

    numSteps = int(input())
    for i in range(numSteps):
        steps = input().strip().split(" ")
        steps[1] = int(steps[1])
        rx, ry, ax, ay = addSteps(steps[0], steps[1], w, l, rx, ry,ax,ay)
    print("Robot thinks " + str(rx) + " " + str(ry))
    print("Actually at " + str(ax) + " " + str(ay))


from flask import session
from flask_login import current_user
from Library.PagerModule import Pager
from Library.SearchModule import Searcher
from Library.StyleModuleF import Style
from Library.LoggerModule import debug
from Library.BeanModule import Cuser
import jsonpickle
from flask_login import current_user

jsons = ['pager', 'searcher', 'cuser']
strgs = ['settings', 'settings-expire']

def skey(key):
    if hasattr(current_user, 'id'):
        return key + '_' + str(current_user.id)
    else:
        return key

class Sessioner():
    def __init__(self, version):
        self.version = version
        debug('version=' + version + ', session.version=' + session.get(skey('version'), ''))

    def get(self, key):
        debug('getting key=' + key)
        ukey = skey(key)
        vkey = skey('version')

        if vkey not in session or session[vkey] != self.version:
            debug('getting version key ' + vkey + ' not in session, set version and delete keys')
            session[vkey] = self.version
            self.deleteAllKeys()

        if ukey not in session:
            #
            # Create and populate new session variable
            #
            if key == 'pager':
                #obj = Pager()
                session[ukey] = jsonpickle.encode(Pager())
            elif key == 'searcher':
                #obj = Searcher()
                session[ukey] = jsonpickle.encode(Searcher())
            elif key == 'cuser':
                if current_user.is_authenticated:
                    session[ukey] = jsonpickle.encode(Cuser('user', current_user.id))
                else:
                    session[ukey] = jsonpickle.encode(Cuser('user', 0))

        if key in jsons:
            rtn = jsonpickle.decode(session[ukey])
            rtn.setInit()
            return rtn
        else:
            return session.get(ukey)

    def getWithArgs(self, key, args):
        obj = self.get(key)
        obj.setArgs(args)
        self.put(key, obj)
        return obj

    def put(self, key, obj):
        debug('putting ' + key + '=' + str(obj))
        ukey = skey(key)
        if key in jsons:
            session[ukey] = jsonpickle.encode(obj)
        else:
            session[ukey] = obj

    def deleteAllKeys(self):
        keys = jsons + strgs
        for key in keys:
            ukey = skey(key)
            if ukey in session:
                session.pop(ukey)


from numpy import array
from numpy.linalg import inv

from gui import App

def best_sqr_approx(X: list, Y: list, W: list, n: int):
    N = len(X)
    n += 1
    if n >= N:
        n = N

    Y_hat = array([[
        sum(W[k] * Y[k] * X[k] ** i for k in range(N))
        for i in range(n)
    ]])

    mat = [[sum(W[k] * X[k] ** (i + j) for k in range(N))
            for j in range(n)
        ] for i in range(n)
    ]

    mat = inv(mat)
    A = Y_hat.dot(mat).flatten()

    def functor(x):
        y = 0
        for i, a in enumerate(A):
            y += a * x ** i
        return y

    return functor

# Q6
def best_sqr_approx_nm(X: list, Y: list, W: list, n: int):
    def make_functor(A: list):
        def functor(x):
            y = 0
            for i, a in enumerate(A):
                y += a * x ** i
            return y
        return functor

    def error(functor):
        err = 0
        for x, y, w in zip(X, Y, W):
            err += w * (y - functor(x))**2
        return err

    N = len(X)
    err_list = []

    max_power = 10
    for n in range(2, max_power):
        for m in range(1, n):
            Y_hat = array([[
                sum(W[k] * Y[k] * X[k] ** i for k in range(N))
                for i in (0, n, m)
            ]])

            mat = [[sum(W[k] * X[k] ** (i + j) for k in range(N))
                    for j in (0, n, m)
                ] for i in (0, n, m)
            ]

            mat = inv(mat)
            errA = Y_hat.dot(mat).flatten()

            A = [0] * (1 + max(n, m))
            A[0], A[n], A[m] = errA

            err = error(make_functor(A))
            err_list.append((err, n, m, A))

    best_err = sorted(err_list, key=lambda e: e[0])[0]
    err, n, m, A = best_err
    print(n, m)
    return make_functor(A)

App().feed_approximator(best_sqr_approx).mainloop()


#Xavier Rouleau
# Pour le gestionnaire d'événement
from PyQt5.QtCore import pyqtSlot
# Importer la boite de dialogue
import UI_PY.Dialog_enclos
from PyQt5 import QtWidgets
from PyQt5.QtCore import pyqtSlot
from Classes.Classe_Enclos import *

######################################################
###### DÉFINITIONS DE LA CLASSE Fenetrelistview ######
######################################################

def cacher_labels_erreur(objet):
    objet.label_erreur_numero_enclos_existe.setVisible(False)
    objet.label_erreur_numero_enclos_existe_pas.setVisible(False)
    objet.label_erreur_validation_numero_enclos.setVisible(False)
    objet.label_erreur_nom_enclos.setVisible(False)

def verifier_enclos(enclos):
    index = 0
    for enclos_ls in Enclos.ls_enclos:
        if enclos_ls.Numero_enclos == enclos.Numero_enclos:
            return True, index
        index += 1
    return False, index

class Fenetreenclos(QtWidgets.QDialog, UI_PY.Dialog_enclos.Ui_Dialog):
    def __init__(self, parent=None):
        """
        Constructeur de la fenêtre qui affiche la liste des étudiants
        """
        super(Fenetreenclos, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle("Boîte de dialogue Enclos")
        cacher_labels_erreur(self)

    @pyqtSlot()
    def on_pushButton_Ajouter_enclos_clicked(self):
        enclos = Enclos()
        enclos.Numero_enclos = self.lineEdit_numero_enclos.text()
        enclos.Nom_enclos = self.lineEdit_nom_enclos.text()
        enclos.Taille = self.comboBox_taille_enclos.currentText()
        enclos.Type = self.comboBox_type_enclos.currentText()
        enclos.Localisation = self.comboBox_localisation.currentText()

        existe, index = verifier_enclos(enclos)
        if existe:
            self.label_erreur_numero_enclos_existe.setVisible(True)

        if enclos.Numero_enclos == "":
            self.lineEdit_numero_enclos.clear()
            self.label_erreur_validation_numero_enclos.setVisible(True)

        if enclos.Nom_enclos == "":
            self.lineEdit_nom_enclos.clear()
            self.label_erreur_nom_enclos.setVisible(True)

        if enclos.Numero_enclos != "" and enclos.Nom_enclos != "" and not existe:
            Enclos.ls_enclos.append(enclos)
            self.lineEdit_numero_enclos.clear()
            self.lineEdit_nom_enclos.clear()
            cacher_labels_erreur(self)

    @pyqtSlot()
    def on_pushButton_supprimer_enclos_clicked(self):
        enclos = Enclos()
        enclos.Numero_enclos = self.lineEdit_numero_enclos.text()

        existe, index = verifier_enclos(enclos)

        if not existe:
            self.label_erreur_numero_enclos_existe_pas.setVisible(True)
        else:
            Enclos.ls_enclos.pop(index)
            cacher_labels_erreur(self)


import sys
sys.stdin = open('input', 'r')
#values()이용해도됨
bracket_left = ['(','{','[']
#key() 이용해도됨
bracket_right = [')','}',']']

bracket_dict = {')':'(','}':'{',']':'['}

T = int(input())
for tc in range(1,T+1):
    stack = []
    sentence = input()
    #sentence의 각각 원소 하나 씩 탐색
    for bracket in sentence:
        #만약 bracket이 열린괄호면 stack에 넣고
        if bracket in bracket_left:
            stack.append(bracket)
        #만약 bracket이 닫힌괄호고 stack이 비어있으면 탐색 끝 0출력
        elif bracket in bracket_right:
            if not stack:
                print(f'#{tc} 0')
                break
            #bracket이 닫힌괄호인데 stack이 안비어잇을때
            else:
                #stack의 마지막 값과 bracket의 value값이 동일하면 stack pop하기
                if stack[-1] == bracket_dict.get(bracket):
                    stack.pop()
                #아니면 0출력
                else:
                    print(f'#{tc} 0')
                    break
    #for esle구문 위의 출력이 break없이 끝났을때 stack이 남아잇으면 0 아니면 1
    else:
        if len(stack) != 0:
            print(f'#{tc} 0')
        else:
            print(f'#{tc} 1')


import json
print("hello world!")
f = open("json/lan.json", encoding='utf-8')
jsondata = json.load(f)
ss = ''
for key in jsondata['data']:

    # ss = ss + "area" + str(key['id']) + "=" + str(key['name_zh']) + '\n'
    # ss = ss + "area" + str(key['id']) + "=" + str(key['name_en']) + '\n'
    ss = ss + str(key['nId']) + "=" + str(key['sName']) + '\n'
print(ss)


bl_info = {
    "name": "Rigging Tools",
    "author": "Wayne Wu",
    "version": (2, 3, 1),
    "blender": (2, 75, 0),
    "location": "View3D > Tools",
    "description": "Rigging Tools",
    "warning": "The addon still in progress! Make a backup!",
    "wiki_url": "https://tangentanimation.sharepoint.com/wiki/Pages/Rigging%20Tool.aspx",
    "category": "Tangent"}

import bpy
from bpy.types import Panel, Operator, PropertyGroup
import bone_tools
import mesh_tools

class ArmatureLayerGUI(Panel):
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category = 'TA - Rigging'
    bl_label = "Armature Layers"

    @classmethod
    def poll(cls, context):
        return context.object and context.object.type == 'ARMATURE'

    def draw(self, context):
        layout = self.layout

        arm = context.active_object.data
        layout.prop(arm, "pose_position", expand=True)

        col = layout.column()
        col.label(text="Layers:")
        col.prop(arm, "layers", text="")
        col.label(text="Protected Layers:")
        col.prop(arm, "layers_protected", text="")

class ExceptionsProperty(PropertyGroup):
    """
    A property class for exception
    """
    exception = bpy.props.StringProperty(name="Exception", default = "")
    index = bpy.props.IntProperty(name="Index")

class BONE_ToolProperty(PropertyGroup):
    bpy.types.Object.bone_change_prefix = bpy.props.BoolProperty(name = "Change Prefix", description= "Check this to allow changing the prefix of the bones", default = False)
    bpy.types.Object.bone_old_prefix = bpy.props.StringProperty(name = "Old Prefix", default = "ctl.")
    bpy.types.Object.bone_new_prefix = bpy.props.StringProperty(name = "New Prefix", default = "acc.")
    bpy.types.Object.bone_new_scale = bpy.props.FloatProperty(name = "Scale", default = 1.5)
    bpy.types.Object.boneshape_apply = bpy.props.BoolProperty(name = "Assign", description ="Assign bone shape if selected, otherwise will remove bone shape for the selected bones", default = False)
    bpy.types.Object.bone_show_wireframe = bpy.props.BoolProperty(name = "Wireframe", description = "Bone is drawn as wireframe", default = True)
    bpy.types.Object.boneshape_shape_name = bpy.props.StringProperty(name = "Shape name")
    try:
        bpy.utils.register_class(ExceptionsProperty) #Need to find a way around this
    except:
        pass
    bpy.types.Object.bone_exceptions = bpy.props.CollectionProperty(type = ExceptionsProperty)
    bpy.types.Object.bone_deform_enable = bpy.props.BoolProperty(name = "Enable", description = "Will enable deform for selected bones if checked, otherwise will remove", default = False)
    bpy.types.Object.bone_source = bpy.props.StringProperty(name = "Source Bone")
    bpy.types.Object.bone_stretch_volume = bpy.props.EnumProperty(
        items = [('VOLUME_XZX', 'XZX', "volume_xzx"), ('VOLUME_X', "X", "volume_x"),('VOLUME_Z','Z', "volume_z"), ('NO_VOLUME','NO VOLUME', "no_volume")],
        name = "Stretch To Volume"
        )

class BONE_ToolsGUI(Panel):
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category = 'TA - Rigging'
    bl_label = "Bone Tools"

    @classmethod
    def poll(cls, context):
        return context.object and context.object.type == 'ARMATURE'

    def draw(self, context):
        layout = self.layout
        col = layout.column()

        ################################BOX1#########################
        row = col.row(align = True)
        box = row.box()
        row = box.row(align = True)
        col2 = row.column(align = True)
        row = col2.row(align = True)
        row.label("Bone Attributes (Based on Selection)")
        row = col2.row(align = True)
        row.operator("object.bone_lock", text = "Lock", icon = 'LOCKED')
        row.operator("object.bone_unlock", text = "Unlock", icon = 'UNLOCKED')
        row = col2.row(align = True)
        row.operator("object.bone_flip", text = "Flip", icon = 'FULLSCREEN_ENTER' )
        row.operator("object.bone_set_xzy", text = "Set XZY", icon = 'NDOF_TURN')

        row = box.row(align = True)
        row.alignment = 'LEFT'
        row.prop(context.object, "bone_deform_enable")
        if bpy.context.object.bone_deform_enable:
            row.operator("object.bone_deform", text = "Enable Deform", icon = 'ZOOMIN')
        else:
            row.operator("object.bone_deform", text = "Remove Deform", icon = 'X')
        row = box.row(align = True)
        col2 = row.column(align = False)
        i = 0
        while i < len(bpy.context.object.bone_exceptions):
            col2.prop(context.object.bone_exceptions[i], "exception", icon = 'GROUP_BONE')
            i = i + 1 #First Exception
        row = col2.row(align = True)
        row.operator("object.add_bone_exception", text="Add Exception")
        row.operator("object.remove_bone_exception", text = "", icon = "X")

        ###################################BOX2##########################
        row = col.row(align = True)
        box = row.box()
        col2 = box.column()
        row = col2.row()
        row.label("Bone Parenting (Based on Selection)")
        row = col2.row(align = True)
        row.prop(context.object, "bone_change_prefix")
        if bpy.context.object.bone_change_prefix:
            row = col2.row(align = True)
            row.prop(context.object, "bone_old_prefix" )
            row = col2.row(align = True)
            row.prop(context.object, "bone_new_prefix")
        row = col2.row(align = True)
        row.prop(context.object, "bone_new_scale")
        row = col2.row(align = True)
        row.operator("object.parent_bones", text = "Create Parent Bones", icon = 'CONSTRAINT_BONE')
        row = col2.row()
        row.separator()
        #Section 3
        row = col2.row()
        row.label("Bone Shape (Based on Selection)")
        row = col2.row(align = True)
        row.prop(context.object, "boneshape_apply")
        if bpy.context.object.boneshape_apply:
            row.prop(context.object, "bone_show_wireframe")
            row = col2.row(align = True)
            row.prop_search(context.object, "boneshape_shape_name", bpy.context.scene, 'objects', text = "Shape", icon = 'OBJECT_DATA')
        row = col2.row(align = True)
        if bpy.context.object.boneshape_apply:
            row.operator("object.bone_shape", text = "Assign Bone Shape", icon = 'ZOOMIN' )
        else:
            row.operator("object.bone_shape", text = "Remove Bone Shape", icon = 'X')

        #####################################BOX3###############################
        row = col.row()
        box = row.box()
        col2 = box.column(align = True)
        col2.label("Bone Constraints (Based on Selection)")
        row = col2.row(align = True)
        row.alignment = 'EXPAND'
        row.label(icon = 'CONSTRAINT_BONE')
        row.operator("object.mute_bone_constraints", text = "Mute", icon = "RESTRICT_VIEW_ON")
        row.operator("object.unmute_bone_constraints", text = "Unmute", icon = "RESTRICT_VIEW_OFF")
        col2 = box.column()
        col2.label(text="Stretch To")
        row = col2.row(align = True)
        row.label(text ="RESET")
        row.operator("object.reset_stretch_all", text = "All")
        row.operator("object.reset_stretch_selected", text = "Selected")
        row = col2.row(align = True)
        row.alignment = 'EXPAND'
        row.prop_menu_enum(context.object, "bone_stretch_volume", text = bpy.context.object.bone_stretch_volume)
        #row.prop(context.object, "bone_stretch_volume")
        row.operator("object.stretch_volume_change_all", text = "All")
        row.operator("object.stretch_volume_change_selected", text = "Selected")
        row = col.row()

        ########################################BOX4#############################
        if bpy.context.selected_pose_bones:
            row = col.row(align = False)
            box = row.box()
            box.prop_search(context.object, "bone_source", bpy.context.object.pose, 'bones', text="Source", icon = 'BONE_DATA')
            box.operator("object.copy_driver", text = "Copy Constraint Drivers", icon = "GHOST")

class BONE_AddException(Operator):
    bl_idname = "object.add_bone_exception"
    bl_description = "Add exception"
    bl_label = "Add_Exception"
    bl_options = {'UNDO'}

    def invoke(self, context, event):
        new_exception = bpy.context.object.bone_exceptions.add()
        i = len(bpy.context.object.bone_exceptions) - 1
        new_exception.index = i
        return{'FINISHED'}

class BONE_RemoveException(Operator):
    bl_idname = "object.remove_bone_exception"
    bl_description = "Remove the last exception"
    bl_label = "Remove Exception"
    bl_options = {'UNDO'}

    def invoke(self, context, event):
        index = len(bpy.context.object.bone_exceptions) - 1
        bpy.context.object.bone_exceptions.remove(index)
        return{'FINISHED'}

class BONE_Flip(Operator):
    bl_idname = "object.bone_flip"
    bl_label = "Flip Bones"
    bl_description = "Flip the selected bones head to tail, tail to head"
    bl_option = {'UNDO'}
    def invoke (self, context, event):
        bone_tools.bone_flip(compile_bone_exceptions())
        return {'FINISHED'}

class BONE_Deform(Operator):
    bl_idname = "object.bone_deform"
    bl_label = "Enable Deform Bone to selected"
    bl_description = "Enable/Disable Bone Deform for the selected bones"
    bl_option = {'UNDO'}

    @classmethod
    def poll(cls, context):
        return bpy.context.selected_pose_bones

    def invoke (self, context, event):
        if bpy.context.active_object.mode != 'POSE':
            bpy.ops.object.mode_set(mode='POSE')

        for item in bpy.context.selected_pose_bones:
            if not item.name.startswith(compile_bone_exceptions()):
                if bpy.context.object.bone_deform_enable:
                    item.bone.use_deform = True
                else:
                    item.bone.use_deform = False

        return {'FINISHED'}

class BONE_Lock(Operator):
    bl_idname = "object.bone_lock"
    bl_label = "Lock Bone Transformations"
    bl_description = "Lock the transformations of the selected bones"
    bl_option = {'UNDO'}

    def invoke (self, context, event):
        bone_tools.bone_lock(compile_bone_exceptions(), True)
        return {'FINISHED'}

class BONE_Unlock(Operator):
    bl_idname = "object.bone_unlock"
    bl_label = "Unlock Bone Transformations"
    bl_description = "Unlock the transformations of the selected bones"
    bl_option = {'UNDO'}

    def invoke (self, context, event):
        bone_tools.bone_lock(compile_bone_exceptions(), False)
        return {'FINISHED'}

class BONE_Parenting(Operator):
    bl_idname = "object.parent_bones"
    bl_label = "Parent_Bone"
    bl_description = "Create a parented bones at the same spot with given scale"
    bl_option = {'UNDO'}

    def invoke (self, context, event):
        obj = bpy.context.object
        bone_tools.bone_parenting(obj.bone_change_prefix, obj.bone_new_prefix, obj.bone_old_prefix, obj.bone_new_scale)
        return {'FINISHED'}

class BONE_Shape(Operator):
    bl_idname = "object.bone_shape"
    bl_label = "Remove_Assign_BoneShape"
    bl_description = "Assign/Remove Custom Bone Shape to selected bones"
    bl_option = {'UNDO'}

    def invoke (self, context, event):
        shape_name = bpy.context.object.boneshape_shape_name
        if bpy.context.object.boneshape_apply:
            if not shape_name:
                self.report({'ERROR'}, "No Shape Name Entered")
            else:
                bone_tools.bone_shape(shape_name, bpy.context.object.bone_show_wireframe)
        else:
            bone_tools.bone_shape()
        return {'FINISHED'}

class BONE_SetXZY(Operator):
    bl_idname = "object.bone_set_xzy"
    bl_label = "Set_XZY"
    bl_description = "Set rotation mode to XZY for all bones in the selected objects"
    bl_option = {'UNDO'}

    def invoke (self, context, event):

        for item in bpy.context.object.pose.bones:
            if not item.name.startswith(compile_bone_exceptions()):
                item.rotation_mode = 'XZY'
        return {'FINISHED'}

class BONE_MuteConstraints(Operator):

    bl_idname = "object.mute_bone_constraints"
    bl_label = "Mute_Bone_Constraints"
    bl_description = "Mute constraints on the selected bone"
    bl_option = {'UNDO'}

    def invoke (self, context, event):
        bone_tools.mute_bone_constraint(True)
        return {'FINISHED'}

class BONE_UnmuteConstraints(Operator):

    bl_idname = "object.unmute_bone_constraints"
    bl_label = "Unmute_Bone_Constraints"
    bl_description = "Unmute constraints on the selected bone"
    bl_option = {'UNDO'}

    def invoke (self, context, event):
        bone_tools.mute_bone_constraint(False)
        return {'FINISHED'}

class BONE_CopyConstraintDriver(Operator):
    bl_idname = "object.copy_driver"
    bl_label = "Copy Drivers after copying constraints"
    bl_description = "Copy source bone's constraint drivers to selected bones"
    bl_option = {'UNDO'}

    @classmethod
    def poll(cls, context):
        return bpy.context.object.bone_source

    def invoke (self, context, event):
        bone_tools.copy_driver(bpy.context.object.bone_source)
        return {'FINISHED'}

class BONE_ResetStretchAll(Operator):
    bl_idname = "object.reset_stretch_all"
    bl_label = "Reset_Stretch_All"
    bl_description = "Reset stretch to constraint to all pose bones"
    bl_option = {'UNDO'}

    def invoke (self, context, event):
        bone_tools.reset_stretch_constraint('ALL')
        return {'FINISHED'}

class BONE_ResetStretchSelected(Operator):
    bl_idname = "object.reset_stretch_selected"
    bl_label = "Reset Stretch Selected"
    bl_description = "Reset stretch to constraint to selected pose bones"
    bl_option = {'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.selected_pose_bones

    def invoke (self, context, event):
        bone_tools.reset_stretch_constraint()
        return {'FINISHED'}

class BONE_StretchVolumeChangeAll(Operator):
    bl_idname = "object.stretch_volume_change_all"
    bl_label = "Stretch_Volume_Change_All"
    bl_description = "Change Stretch To Constriant's Volume to all bones"
    bl_option = {'UNDO'}

    def invoke (self, context, event):
        bone_tools.change_stretch_volume(bpy.context.object.bone_stretch_volume,'ALL')
        return {'FINISHED'}

class BONE_StretchVolumeChangeSelected(Operator):
    bl_idname = "object.stretch_volume_change_selected"
    bl_label = "Stretch_Volume_Change_Selected"
    bl_description = "Change Stretch To Constriant's Volume to selected bones"
    bl_option = {'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.selected_pose_bones

    def invoke (self, context, event):
        bone_tools.change_stretch_volume(bpy.context.object.bone_stretch_volume)
        return {'FINISHED'}

class Mesh_ToolsProperties(PropertyGroup):
    class DriverSettings(PropertyGroup):
        driver_target = bpy.props.StringProperty(name = "Driver Target")
        driver_target_datapath = bpy.props.StringProperty(name = "Driver Target Datapath")
        driver_subtarget = bpy.props.StringProperty(name = "Driver Target Subtarget")
        driver_datapath = bpy.props.StringProperty(name = "Datapath")
        driver_expression = bpy.props.StringProperty(name = "Expression", default = "-var+1")

    try:
        bpy.utils.register_class(DriverSettings)
    except: pass

    bpy.types.Scene.driver_settings = bpy.props.PointerProperty(type = DriverSettings)

class MESH_ToolsGUI(Panel):
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category = 'TA - Rigging'
    bl_label = "Mesh Tools"

    #*TODO Create a pointer property to point to these
    bpy.types.Object.weight_mirror_side = bpy.props.EnumProperty(
        items = [('LEFT', 'L', "left"), ('RIGHT', 'R', "right")],
        name = "Source Side"
        )

    def draw(self, context):
        layout = self.layout
        col = layout.column()
        row = col.row(align = True)
        row.label(text="Modifiers")

        row = col.row(align = True)
        row.operator("object.mesh_remove_modifiers", text = "Remove Modifiers", icon = "X")

        row = col.row(align = True)
        row.operator("object.mesh_add_dummy", text = "Add Dummy Modifier", icon = "POSE_DATA")
        row = col.row(align = True)
        row.operator("object.lock_transformations", text = "Transformation", icon = 'LOCKED').lock = True
        row.operator("object.lock_transformations", text = "Transformation", icon = 'UNLOCKED').lock = False
        row = col.row(align = True)
        row.label(text="Vertex Groups")
        row = col.row()
        row.label("Source Side:")
        row.prop(context.object, "weight_mirror_side", text = "Source Side", expand = True)
        row = col.row()
        row.operator("object.weight_mirror", text = "Weight Mirror", icon = 'WPAINT_HLT')
        row = col.row() #Small Gap

        box = col.box()
        col2 = box.column(align = True)
        col2.label(text="Cycles Render")
        row = col2.row(align = True)
        row.alignment = 'LEFT'
        row.label(text="Ray Visibility", icon = "SEQ_CHROMA_SCOPE")
        row.operator("object.ray_viz_on", text = "ON")
        row.operator("object.ray_viz_off", text = "OFF")

        row = col.row()
        box = row.box()
        row = box.row()
        col2 = row.column(align = True)
        col2.label("Create Driver: Target")
        col2.prop_search(context.scene.driver_settings, "driver_target", context.scene, "objects", text = "Object", icon = 'OBJECT_DATA')
        if context.scene.driver_settings.driver_target:
            obj = context.scene.objects[context.scene.driver_settings.driver_target]
            if obj.type == 'ARMATURE':
                col2.prop_search(context.scene.driver_settings, "driver_subtarget", obj.pose, "bones", text = "Bone", icon = 'BONE_DATA')
            col2.prop(context.scene.driver_settings, "driver_target_datapath", text = "Datapath", icon = 'RNA')
            col2.prop(context.scene.driver_settings, "driver_expression", text = "Expression")
        row = box.row(align = True)
        row.prop(context.scene.driver_settings, "driver_datapath", text = "Datapath", icon = 'RNA')
        row.operator("object.create_driver", text = "Create Driver", icon = 'ZOOMIN')

class MESH_RemoveModifiers(Operator):
    bl_idname = "object.mesh_remove_modifiers"
    bl_label = "Remove the modifiers and particle systems"
    bl_description = "Remove all modifiers and all particle systems"
    bl_option = {'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.object and context.object.type == 'MESH'

    def invoke (self, context, event):
        mesh_tools.remove_modifiers()
        return {'FINISHED'}

class MESH_LockTransformation(Operator):
    bl_idname = "object.lock_transformations"
    bl_label = "lock_transformations_selected_mesh"
    bl_description = "Lock Transformations for selected objects"
    bl_option = {'UNDO'}

    lock = bpy.props.BoolProperty(name = "state")
    def invoke (self, context, event):
        mesh_tools.lock_objects(self.lock)
        return {'FINISHED'}

class MESH_AddDummy(Operator):
    bl_idname = "object.mesh_add_dummy"
    bl_description = "Add Simple Deform Modifier to the end of the selected object's modifier stack"
    bl_label = "Character_Add_Dummy"
    bl_options = {'UNDO'}

    def invoke(self, context, event):
        mesh_tools.put_dummy()

        return {"FINISHED"}

class MESH_ObjectRayVizOff(Operator):
    bl_idname = "object.ray_viz_off"
    bl_label = "Object_Ray_Viz_off"
    bl_options = {'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.object and context.object.type == 'MESH'

    def invoke(self, context, event):
        mesh_tools.object_ray_viz(False)

        return {"FINISHED"}

class MESH_ObjectRayVizOn(Operator):
    bl_idname = "object.ray_viz_on"
    bl_label = "Object_Ray_Viz_on"
    bl_options = {'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.object and context.object.type == 'MESH'

    def invoke(self, context, event):
        mesh_tools.object_ray_viz(True)

        return {"FINISHED"}

class MESH_WeightMirroring(Operator):
    bl_idname = "object.weight_mirror"
    bl_label = "Mirror Weight across the X Axis"
    bl_options = {'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.object and context.object.type == 'MESH'

    def invoke(self, context, event):
        weight = mesh_tools.WeightMirroring(bpy.context.object.weight_mirror_side)
        weight.execute()
        return {"FINISHED"}

class OBJ_CreateDriver(Operator):
    bl_idname = "object.create_driver"
    bl_label = "Create Drivers"
    bl_description = "Create the same driver on the selected meshes"
    bl_options = {'UNDO'}

    @classmethod
    def poll(cls, context):
        settings = context.scene.driver_settings
        return (
            context.object
            and context.object.mode == 'OBJECT'
            and settings.driver_target_datapath
            and settings.driver_datapath)

    def execute(self, context):
        settings = context.scene.driver_settings
        for obj in bpy.context.selected_objects:
            self.create_driver(
                obj,
                settings.driver_datapath,
                settings.driver_expression,
                settings.driver_target_datapath,
                settings.driver_target,
                settings.driver_subtarget)

        return {'FINISHED'}

    def invoke(self, context, event):
        return self.execute(context)

    def create_driver(self, obj, data_path, expression, custom_prop_name, target_id, subtarget = None):
        new_driver = obj.driver_add(data_path)
        new_driver.driver.expression = expression
        try:
            var = new_driver.driver.variables[0]
        except:
            var = new_driver.driver.variables.new()
        var.name = "var"
        target = var.targets[0]
        target.id = bpy.context.scene.objects[target_id]
        if subtarget:
            target.bone_target = subtarget
        target.data_path = custom_prop_name

class CLEAN_ToolsGUI(Panel):
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category = 'TA - Rigging'
    bl_label = "Clean Up Tools"

    bpy.types.Scene.clear_action_name = bpy.props.StringProperty(name = "Clear Action Name")

    def draw(self, context):
        layout = self.layout
        col = layout.column()
        row = col.row(align = True)
        row.label(icon = 'LINKED')
        row.operator("object.character_remove_dependencies", text = "Clear Dependencies", icon = 'X')
        row = col.row(align = True)
        row.label(icon= 'SPLITSCREEN')
        row.operator("screen.delete_none_default", text = "Delete Screens", icon = 'X')
        row = col.row(align = True)
        row.prop_search(context.scene, "clear_action_name", bpy.data, "actions", text = "Action")
        row.operator("action.clear_action", text = "Remove", icon = "X")

class CLEAN_RemoveDependency(Operator):
    bl_idname = "object.character_remove_dependencies"
    bl_label = "Character_Remove_Dependencies"
    bl_description = "Remove all dependencies at the rig level"
    bl_options = {"UNDO"}

    def invoke(self, context, event):
        error_list = self.remove_dependencies()
        if error_list:
            for error in error_list:
                self.report({'ERROR'}, error)
        return {"FINISHED"}

    def remove_dependencies(self):
        """
        Remove all dependencies at the armature level
        """
        error=[]
        for armature in bpy.data.armatures:
            if armature.name.startswith('rig'):
                try:
                    armature.animation_data
                except:
                    print("ERROR: no animation data(driver)")
                else:
                    try:
                        for d in armature.animation_data.drivers:
                            if d.data_path.endswith('.hide') or d.data_path.endswith('.bbone_in') or d.data_path.endswith('.bbone_out'):
                                try:
                                    armature.driver_remove(d.data_path)
                                    #print("%s removed" %d.data_path)
                                except TypeError: #driver path is broken
                                    for var in d.driver.variables:
                                        d.driver.variables.remove(var)
                                    try:
                                        d.data_path = 'bones[\"ctl.god.C\"].hide'      #change data_path target to ctl.god.C so that it's deletable
                                    except:
                                        print("No such datapath")
                                        break
                                    else:
                                        armature.driver_remove(d.data_path)
                            else:
                                error.append("Driver(Armature %s) pointed to %s will not be removed" %(armature.name, d.data_path))
                    except AttributeError:
                        print("No driver")
                    for layer in armature.layers:
                       layer = True
                    try:
                        for b in bpy.data.objects[armature.name].pose.bones:
                            b.bone.hide = False
                    except KeyError:
                        pass
                    i = 0
                    while (i < 32):
                        if 7 < i < 16 or i > 23:
                            armature.layers[i] = False
                        i = i + 1

        for obj in bpy.data.objects:
            if obj.name.startswith('rig'):
                try:
                    for d in obj.animation_data.drivers:
                        if not d.is_valid:
                            error.append("Driver(Object %s) Datapath %s is broken" %(obj.name, d.data_path))
                except AttributeError:
                    pass
        return error

class CLEAN_ClearAction(Operator):
    bl_idname = "action.clear_action"
    bl_label = "Clear_action"
    bl_description = "Clear all users in an action and remove it"
    bl_options = {'UNDO'}

    def execute(self, context):

        action = bpy.data.actions[bpy.context.scene.clear_action_name]
        action.user_clear()
        bpy.data.actions.remove(action)

        return {'FINISHED'}

    def invoke(self, context, event):
        return self.execute(context)

class CLEAN_DeleteScreens(Operator):
    bl_idname = "screen.delete_none_default"
    bl_label = "Delete_None_Default"
    bl_description = "Delete None Default screens"
    bl_options = {'UNDO'}

    def execute(self, context):

        default_screens = [
            "3D View Full",
            "Animation",
            "Composition",
            "Default",
            "Game Logic",
            "Motion Tracking",
            "Scripting",
            "UV Editing",
            "Video Editing",
            ]

        i = 0
        while(i<len(bpy.data.screens)):
            bpy.ops.screen.screen_set(delta = 1)
            if bpy.context.screen.name not in default_screens:
                bpy.ops.screen.delete()
            i = i + 1
        bpy.context.window.screen = bpy.data.screens["Default"]
        return {'FINISHED'}

    def invoke(self, context, event):
        return self.execute(context)

def compile_bone_exceptions():

    strings = []
    try:
        bpy.context.object.bone_exceptions
    except:
        pass
    else:
        for b in bpy.context.object.bone_exceptions:
            strings.append(b.exception)
    if not strings:
        #string is empty
        strings.append("\t\t\t")
    str = tuple(strings)
    return str

def register():
    bpy.utils.register_module(__name__)

def unregister():
    bpy.utils.unregister_module(__name__)

if __name__ == "__main__":
    register()


import sys

if (len(sys.argv) != 2):
    print("Usage: python genList.py <N>")
    exit()

import praw

SUBREDDITS=['amiugly', 'teenamiugly']

r = praw.Reddit('bot1', user_agent='0')

for sub in SUBREDDITS:
    for post in r.subreddit(sub).new(limit=int(sys.argv[1])/len(SUBREDDITS)):
        print(post.id)


import os
import time
from unittest import mock

import pytest

from cumulusci.core.config import BaseProjectConfig, TaskConfig, UniversalConfig
from cumulusci.core.exceptions import TaskOptionsError
from cumulusci.tasks.metadata.ee_src import CreateUnmanagedEESrc, RevertUnmanagedEESrc
from cumulusci.utils import temporary_dir

class TestCreateUnmanagedEESrc:
    @mock.patch("cumulusci.tasks.metadata.ee_src.remove_xml_element_directory")
    def test_run_task(self, remove_xml_element_directory):
        with temporary_dir() as path:
            revert_path = os.path.join(
                os.path.dirname(path), os.path.basename(path) + "_revert"
            )
            project_config = BaseProjectConfig(
                UniversalConfig(), config={"noyaml": True}
            )
            task_config = TaskConfig(
                {"options": {"path": path, "revert_path": revert_path}}
            )
            task = CreateUnmanagedEESrc(project_config, task_config)
            task()
            remove_xml_element_directory.assert_has_calls(
                [
                    mock.call("availableFields", path, "*.object"),
                    mock.call("visibility[.='Protected']", path, "*.object"),
                ]
            )

    def test_run_task__path_not_found(self):
        project_config = BaseProjectConfig(UniversalConfig(), config={"noyaml": True})
        task_config = TaskConfig({"options": {"path": "bogus", "revert_path": "bogus"}})
        task = CreateUnmanagedEESrc(project_config, task_config)
        with pytest.raises(TaskOptionsError):
            task()

    def test_run_task__revert_path_already_exists(self):
        with temporary_dir() as path, temporary_dir() as revert_path:
            project_config = BaseProjectConfig(
                UniversalConfig(), config={"noyaml": True}
            )
            task_config = TaskConfig(
                {"options": {"path": path, "revert_path": revert_path}}
            )
            task = CreateUnmanagedEESrc(project_config, task_config)
            with pytest.raises(TaskOptionsError):
                task()

class TestRevertUnmanagedEESrc:
    def test_run_task(self, tmp_path):
        revert_path = tmp_path / "revert"
        revert_path.mkdir()
        file_path = revert_path / "file"
        file_path.write_text("content")

        path = tmp_path / "path"
        path.mkdir()
        project_config = BaseProjectConfig(UniversalConfig(), config={"noyaml": True})
        task_config = TaskConfig(
            {"options": {"path": str(path), "revert_path": str(revert_path)}}
        )
        task = RevertUnmanagedEESrc(project_config, task_config)
        task()
        assert (path / "file").exists()

    def test_run_task__revert_path_not_found(self):
        project_config = BaseProjectConfig(UniversalConfig(), config={"noyaml": True})
        task_config = TaskConfig({"options": {"path": "bogus", "revert_path": "bogus"}})
        task = RevertUnmanagedEESrc(project_config, task_config)
        with pytest.raises(TaskOptionsError):
            task()

    def test_revert_with_update(self, tmp_path):
        """
        Test the 'update' behavior of RevertUnmanagedEESrc task with temporary directories.

        This test creates a source and a destination directory each with one
        file. The file in the source directory has an older timestamp. After
        running RevertUnmanagedEESrc, it checks that the destination file is not
        overwritten by the older source file, confirming the update logic.
        """
        source_dir = tmp_path / "source"
        source_dir.mkdir()
        source_file = source_dir / "testfile.txt"
        source_file.write_text("original content")

        dest_dir = tmp_path / "dest"
        dest_dir.mkdir()
        dest_file = dest_dir / "testfile.txt"
        dest_file.write_text("modified content")

        # Ensure the source file has an older timestamp
        past_time = time.time() - 100
        # Use os.utime to modify the timestamp
        source_file.touch()
        os.utime(str(source_file), (past_time, past_time))

        project_config = BaseProjectConfig(UniversalConfig(), config={"noyaml": True})
        task_config = TaskConfig(
            {"options": {"path": str(dest_dir), "revert_path": str(source_dir)}}
        )
        task = RevertUnmanagedEESrc(project_config, task_config)
        task()

        # Verify that the destination file was not updated (due to older source file)
        assert dest_file.read_text() == "modified content"


from pacti.contracts import PolyhedralIoContract
from pacti import write_contracts_to_file

contract1 = PolyhedralIoContract.from_strings(
    input_vars=["i"],
    output_vars=["o"],
    assumptions=["|i| <= 2"],
    guarantees=["o - i <= 0", "i - 2o <= 2"])

contract2 = PolyhedralIoContract.from_strings(
    input_vars=["o"],
    output_vars=["o_p"],
    assumptions=["o <= 0.2", "-o <= 1"],
    guarantees=["o_p - o <= 0"])

system_contract = contract1.compose(contract2)
print(system_contract)

contract1_n = PolyhedralIoContract.from_strings(
    input_vars=["i"],
    output_vars=["o"],
    assumptions=["|i| <= 2"],
    guarantees=["|o| <= 3"])

write_contracts_to_file([contract1, contract2], ["c1", "c2"], "hola.json")
write_contracts_to_file([contract1, contract2], ["c1", "c2"], "hola_n.json", True)


import json
from sklearn.metrics import classification_report
import torch
import seaborn as sn
import matplotlib.pyplot as plt
import time
from pathlib import Path

def topKAccuracy(guess, target, rank=1):
    sorted_guess, indices = torch.sort(guess)
    hits = 0.0
    for i in range(len(sorted_guess)):
        for k in range(rank):
            if target[i] == indices[i][k]:
                hits += 1
    return round((hits/len(guess)) * 100, 2)

def metrics(guess, target):
    pred = torch.zeros((guess.size(0)), dtype=torch.long)
    for i, el in enumerate(guess):
        pred[i] = torch.argmax(el)
    return classification_report(target, pred, zero_division=0)

def confusionMatrix(target, guess, model_name):
    matrix = [[0 for _ in range(56)] for _ in range(56)]
    for i, element in enumerate(target):
        col = torch.argmax(guess[i])
        matrix[element.item()][col] += 1
    plt.clf()
    sn.heatmap(matrix, cmap="YlGnBu")
    plt.title(model_name + " Confusion Matrix")
    plt.xlabel("Predicted values")
    plt.ylabel("Actual values")
    plt.savefig("data/cm/" + model_name + "_cm.png", dpi=600)

def loadJson(path, ablate=0):
    start_time = time.time()
    # leggo i json dal path e ritono i tensor di local, global e target
    loc = torch.empty([392, 750, 188], dtype=torch.float)
    glob = torch.empty([392, 1])
    targ = torch.empty((392), dtype=torch.long)
    index = 0
    for i in range(3):
        with open(path + "data" + str(i) + ".json") as file:
            data = json.load(file)
        for anim_i, anim in enumerate(data["Items"]):  # 392
            # local
            for frame_i, frame in enumerate(anim["frames"]):  # 750
                temp = []
                if ablate == 0:
                    temp += frame.pop("positions")
                    temp += frame.pop("accelerations")
                    temp += frame.pop("velocities")
                    temp += frame.values()
                elif ablate == 1:
                    temp.append(frame["hunchback"])
                    temp.append(frame["outToeingL"])
                    temp.append(frame["outToeingR"])
                elif ablate == 2:
                    temp += frame["positions"]
                    temp += frame["accelerations"]
                    temp += frame["velocities"]
                elif ablate == 3:
                    temp.append(frame["bodyOpennessU"])
                    temp.append(frame["bodyOpennessL"])
                    temp.append(frame["bctU"])
                    temp.append(frame["bctL"])
                    temp.append(frame["bctF"])
                if (loc.shape != torch.Size([392, 750, len(temp)])):
                    loc, _ = torch.split(
                        loc, [len(temp), 188-len(temp)], dim=2)
                loc[index][frame_i] = torch.tensor(temp)
            # global
            glob[index] = torch.tensor(anim["mediaLungPass"])
            # target
            targ[index] = anim["index"]
            index += 1
    print("\n--- JSON loaded in %s seconds ---" % (time.time() - start_time))
    return loc, glob, targ


# Creates a dictionary object of filenames and first lines of files in the given directory

import os

def read_files(dir_path=os.getcwd()):
    files = os.listdir(dir_path)
    dir_dict = {}
    for f in files:
        filepath = '{}/{}'.format(dir_path, f)
        if os.path.isfile(filepath):
            openfile = open(filepath)
            dir_dict[f] = openfile.readline()
            openfile.close()

    return dir_dict


import ast
import numpy as np

#Some entries in the Dataset are given in JSON format
#Here we extract the relevant parts of those lists (whatever name is given)
#Following columns may have JSON Format: genres, production_companies, production_countries, spoken_languages
def extractDict(input):
    outputList = []
    tempList = []
    input = str(input).replace("[","")
    input = str(input).replace("]","")
    if input == "":
        return
    dictentry = input
    input = ast.literal_eval(dictentry)
    if type(input) == tuple:
        for i in input:
          tempList = i.items()
          for x in tempList:
            if "english_name" in x:
                outputList.append(x[1])
            elif "name" in x:
                outputList.append(x[1])
    else:
        tempList = input.items()
        for x in tempList:
            if "english_name" in x:
                outputList.append(x[1])
            elif "name" in x:
                outputList.append(x[1])
    return outputList

#cleanup the dataframe by replacing 0 with NaN and making lists prettier
def cleanup(df):
    df["budget"] = df["budget"].replace(0, np.nan)
    df["revenue"] = df["revenue"].replace(0, np.nan)
    df["vote_average"] = df["vote_average"].replace(0, np.nan)
    df["vote_count"] = df["vote_count"].replace(0,np.nan)
    df["genres"] = df["genres"].apply(extractDict)
    df["production_companies"] = df["production_companies"].apply(extractDict)
    df["production_countries"] = df["production_countries"].apply(extractDict)
    df["spoken_languages"] = df["spoken_languages"].apply(extractDict)
    return df


'''
Convert raw proteome TSVs to ones with the "Description" field split into its
constituent parts, and missing fields replaced with "NULL".
'''

import re
import sys

def quote(s):
    return "\"{}\"".format(s)

def reformat_tsv(input_tsv_fname, output_fname):
    out_lines = []
    with open(input_tsv_fname, 'r') as f:
        headers = [
            re.sub("\s+", "_", h) for h in f.readline().strip().split("\t")]

        raw_headers = headers[0:]

        metadata_keys = ["OS", "GN", "PE", "SV"]
        description_idx = headers.index("Description")
        for nh in reversed(metadata_keys):
            headers.insert(description_idx+1, nh)

        out_lines.append("\t".join(headers))

        for line in f:
            line_list = line.strip().split("\t")

            line_list = ["NULL" if x=="" else x for x in line_list]

            line_dict = {h:l for h,l in zip(raw_headers, line_list)}

            full_description = line_dict["Description"]
            description = quote(" ".join(full_description.split("=")[0].split()[0:-1]))
            metadata_pattern = re.compile(r'([A-Z]{2}=.*)+')
            metadata = re.search(metadata_pattern, full_description).group()
            rev_items_pattern = re.compile(r'.+?=[A-Z]{2} ?')

            items = dict([
                tuple(
                    map(
                        lambda x:re.sub("\s+", "_", x.strip()),
                        i.split("=")))
                for i in reversed(
                    [s[::-1] for s in re.findall(
                        rev_items_pattern, metadata[::-1])])])

            out_line = "\t".join(
                line_list[0:description_idx] \
                + [description] \
                + [items.get(k, "NULL") for k in metadata_keys] \
                + line_list[description_idx+1:])

            out_lines.append(out_line)

    with open(output_fname, 'wa') as out:
        out.write("\n".join(out_lines))

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("input_tsv_fname")
    parser.add_argument("output_fname")
    args = parser.parse_args()

    reformat_tsv(args.input_tsv_fname, args.output_fname)


import json
# unaccented_string = unidecode.unidecode(accented_string)

ratio1 = 1.3633
ratio2 = 2.4935
ratio3 = 2.3967

with open("../public/js/locations.json", "r", encoding="utf8") as json_file:
    data = json.load(json_file)

for i in range(0,len(data)):
        for j in range (0,len(data[i]["destinations"])):
            if data[i]["name"] == "home":
                ratio = ratio1
            elif data[i]["name"] == "objects":
                ratio = ratio3
            else:
                ratio = ratio2
            if "coords" in data[i]["destinations"][j]:
                new_coord = [str(round(float(coord)/ratio)) for coord in data[i]["destinations"][j]["coords"].split(',')]
                data[i]["destinations"][j]["coords"] = ",".join(new_coord)

with open("new_locations.json", "w", encoding="utf8") as json_file:
    json.dump(data, json_file, ensure_ascii=False)