

import sys
from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast


if TYPE_CHECKING:
     import sqlitea

     import sqlalchemy


lowercase_									=    datasets.utils.logging.get_logger(__name__)


@dataclass
class 					A		(				datasets.BuilderConfig					):







    """simple docstring"""





    lowerCamelCase						      =				None
    lowerCamelCase						      =				None
    lowerCamelCase						      =				None
    lowerCamelCase						      =				True
    lowerCamelCase						      =				None
    lowerCamelCase						      =				None
    lowerCamelCase						      =				None
    lowerCamelCase						      =				1_00_00
    lowerCamelCase						      =				None


    def 		snake_case__	( self					:			Tuple						)->       Optional[int]:





        '''simple docstring'''







        if self.sql is None:
            raise ValueError('sql must be specified'						)
        if self.con is None:
            raise ValueError('con must be specified'						)


    def 		snake_case__	( self					:			Dict,lowercase_					:			dict,lowercase_					:			Optional[datasets.Features] = None,)->       str:





        '''simple docstring'''







        A__        =  config_kwargs.copy()
        # We need to stringify the Selectable object to make its hash deterministic

        # The process of stringifying is explained here: http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html
        A__        =  config_kwargs['sql']
        if not isinstance(lowercase_,lowercase_						):
            if datasets.config.SQLALCHEMY_AVAILABLE and "sqlalchemy" in sys.modules:
                import sqlalchemy

                if isinstance(lowercase_,sqlalchemy.sql.Selectable						):
                    A__        =  sqlalchemy.create_engine(config_kwargs['con'].split('://'						)[0] + '://'						)
                    A__        =  str(sql.compile(dialect=engine.dialect						)						)
                    A__        =  sql_str
                else:
                    raise TypeError(
                        F'Supported types for \'sql\' are string and sqlalchemy.sql.Selectable but got {type(lowercase_						)}: {sql}'						)
            else:
                raise TypeError(
                    F'Supported types for \'sql\' are string and sqlalchemy.sql.Selectable but got {type(lowercase_						)}: {sql}'						)
        A__        =  config_kwargs['con']
        if not isinstance(lowercase_,lowercase_						):
            A__        =  id(lowercase_						)
            logger.info(
                F'SQL connection \'con\' of type {type(lowercase_						)} couldn\'t be hashed properly. To enable hashing, specify \'con\' as URI string instead.'						)

        return super().create_config_id(lowercase_,custom_features=lowercase_						)


    @property
    def 		snake_case__	( self					:			Union[str, Any]						)->       Any:





        '''simple docstring'''







        A__        =  {
            'index_col': self.index_col,
            'columns': self.columns,
            'params': self.params,
            'coerce_float': self.coerce_float,
            'parse_dates': self.parse_dates,
        }
        return pd_read_sql_kwargs




class 					A		(				datasets.ArrowBasedBuilder					):







    """simple docstring"""





    lowerCamelCase						      =				SqlConfig


    def 		snake_case__	( self					:			Any						)->       Any:





        '''simple docstring'''







        return datasets.DatasetInfo(features=self.config.features						)


    def 		snake_case__	( self					:			Tuple,lowercase_					:			List[Any]						)->       Union[str, Any]:





        '''simple docstring'''







        return [datasets.SplitGenerator(name=datasets.Split.TRAIN,gen_kwargs={}						)]


    def 		snake_case__	( self					:			Any,lowercase_					:			pa.Table						)->       pa.Table:





        '''simple docstring'''







        if self.config.features is not None:
            A__        =  self.config.features.arrow_schema
            if all(not require_storage_cast(lowercase_						) for feature in self.config.features.values()						):
                # cheaper cast
                A__        =  pa.Table.from_arrays([pa_table[field.name] for field in schema],schema=lowercase_						)
            else:
                # more expensive cast; allows str <-> int/float or str to Audio for example
                A__        =  table_cast(lowercase_,lowercase_						)
        return pa_table


    def 		snake_case__	( self					:			List[str]						)->       Union[str, Any]:





        '''simple docstring'''







        A__        =  self.config.chunksize
        A__        =  pd.read_sql(
            self.config.sql,self.config.con,chunksize=lowercase_,**self.config.pd_read_sql_kwargs						)
        A__        =  [sql_reader] if chunksize is None else sql_reader
        for chunk_idx, df in enumerate(lowercase_						):
            A__        =  pa.Table.from_pandas(lowercase_						)
            yield chunk_idx, self._cast_table(lowercase_						)




import timeit


class 					A		:







    """simple docstring"""





    def __init__( self					:			Optional[int],lowercase_					:			Union[str, Any]						)->       List[str]:





        '''simple docstring'''







        if isinstance(lowercase_,lowercase_						):  # Initializes a matrix identical to the one provided.
            A__        =  arg
            A__        =  len(lowercase_						)
        else:  # Initializes a square matrix of the given size and set values to zero.
            A__        =  arg
            A__        =  [[0 for _ in range(self.n						)] for _ in range(self.n						)]


    def __mul__( self					:			Union[str, Any],lowercase_					:			List[Any]						)->       List[str]:





        '''simple docstring'''







        A__        =  Matrix(self.n						)
        for i in range(self.n						):
            for j in range(self.n						):
                for k in range(self.n						):
                    matrix.t[i][j] += self.t[i][k] * b.t[k][j]
        return matrix




def 		_snake_case(       SCREAMING_SNAKE_CASE__     :      List[Any]       ,     SCREAMING_SNAKE_CASE__     :      Optional[Any] )				-> Union[str, Any]:





    '''simple docstring'''






    A__        =  Matrix([[1, 0], [0, 1]] )
    while b > 0:
        if b & 1:
            matrix *= a
        a *= a
        b >>= 1
    return matrix
def 		_snake_case(       SCREAMING_SNAKE_CASE__     :      Optional[int]       ,     SCREAMING_SNAKE_CASE__     :      str       ,     SCREAMING_SNAKE_CASE__     :      Any )				-> List[str]:





    '''simple docstring'''






    if n == 1:
        return fa
    elif n == 2:
        return fa
    A__        =  Matrix([[1, 1], [1, 0]] )
    A__        =  modular_exponentiation(SCREAMING_SNAKE_CASE__       ,     n - 2 )
    return fa * matrix.t[0][0] + fa * matrix.t[0][1]
def 		_snake_case(       SCREAMING_SNAKE_CASE__     :      Dict       ,     SCREAMING_SNAKE_CASE__     :      Tuple       ,     SCREAMING_SNAKE_CASE__     :      Tuple )				-> Dict:





    '''simple docstring'''






    if n == 1:
        return fa
    elif n == 2:
        return fa

    A__        =  fa
    A__        =  fa
    n -= 2

    while n > 0:
        A__ ,		A__        =  fn_a + fn_a, fn_a
        n -= 1

    return fn_a
def 		_snake_case(       )				-> Optional[Any]:





    '''simple docstring'''






    A__        =  '\nfrom random import randint\nfrom __main__ import fibonacci_with_matrix_exponentiation\n'
    A__        =  'fibonacci_with_matrix_exponentiation(randint(1,70000), 1, 1)'
    A__        =  timeit.timeit(setup=SCREAMING_SNAKE_CASE__       ,     stmt=SCREAMING_SNAKE_CASE__       ,     number=100 )
    print('With matrix exponentiation the average execution time is '       ,     exec_time / 100 )
    return exec_time
def 		_snake_case(       )				-> Optional[int]:





    '''simple docstring'''






    A__        =  '\nfrom random import randint\nfrom __main__ import simple_fibonacci\n'
    A__        =  'simple_fibonacci(randint(1,70000), 1, 1)'
    A__        =  timeit.timeit(setup=SCREAMING_SNAKE_CASE__       ,     stmt=SCREAMING_SNAKE_CASE__       ,     number=100 )
    print(
        'Without matrix exponentiation the average execution time is '       ,     exec_time / 100 )
    return exec_time
def 		_snake_case(       )				-> Union[str, Any]:





    '''simple docstring'''






    matrix_exponentiation_time()
    simple_fibonacci_time()


if __name__ == "__main__":
     main()

