<commit_before>import matutils
import sputils
import lomutils
import interputils
import ModelBuilder
import meshutils
from matutils import getSubArray, mkvc, ndgrid, ind2sub, sub2ind
from sputils import spzeros, kron3, speye, sdiag, ddx, av, avExtrap
from meshutils import exampleLomGird, meshTensors
from lomutils import volTetra, faceInfo, inv2X2BlockDiagonal, inv3X3BlockDiagonal, indexCube
from interputils import interpmat
from ipythonUtils import easyAnimate as animate
import Solver
from Solver import Solver
import Save
import Geophysics

import types
import time
import numpy as np
from functools import wraps

def hook(obj, method, name=None, overwrite=False, silent=False):
    """
        This dynamically binds a method to the instance of the class.

        If name is None, the name of the method is used.
    """
    if name is None:
        name = method.__name__
        if name == '<lambda>':
            raise Exception('Must provide name to hook lambda functions.')
    if not hasattr(obj,name) or overwrite:
        setattr(obj, name, types.MethodType( method, obj ))
        if getattr(obj,'debug',False):
            print 'Method '+name+' was added to class.'
    elif not silent or getattr(obj,'debug',False):
        print 'Method '+name+' was not overwritten.'


def setKwargs(obj, **kwargs):
    """Sets key word arguments (kwargs) that are present in the object, throw an error if they don't exist."""
    for attr in kwargs:
        if hasattr(obj, attr):
            setattr(obj, attr, kwargs[attr])
        else:
            raise Exception('%s attr is not recognized' % attr)

    hook(obj,hook, silent=True)
    hook(obj,setKwargs, silent=True)

def printTitles(obj, printers, name='Print Titles', pad=''):
    titles = ''
    widths = 0
    for printer in printers:
        titles += ('{:^%i}'%printer['width']).format(printer['title']) + ''
        widths += printer['width']
    print pad + "{0} {1} {0}".format('='*((widths-1-len(name))/2), name)
    print pad + titles
    print pad + "%s" % '-'*widths

def printLine(obj, printers, pad=''):
    values = ''
    for printer in printers:
        values += ('{:^%i}'%printer['width']).format(printer['format'] % printer['value'](obj))
    print pad + values

def checkStoppers(obj, stoppers):
    # check stopping rules
    optimal = []
    critical = []
    for stopper in stoppers:
        l = stopper['left'](obj)
        r = stopper['right'](obj)
        if stopper['stopType'] == 'optimal':
            optimal.append(l <= r)
        if stopper['stopType'] == 'critical':
            critical.append(l <= r)

    if obj.debug: print 'checkStoppers.optimal: ', optimal
    if obj.debug: print 'checkStoppers.critical: ', critical

    return (len(optimal)>0 and all(optimal)) | (len(critical)>0 and any(critical))

def printStoppers(obj, stoppers, pad='', stop='STOP!', done='DONE!'):
    print pad + "%s%s%s" % ('-'*25,stop,'-'*25)
    for stopper in stoppers:
        l = stopper['left'](obj)
        r = stopper['right'](obj)
        print pad + stopper['str'] % (l<=r,l,r)
    print pad + "%s%s%s" % ('-'*25,done,'-'*25)

def callHooks(match):
    """
    Use this to wrap a funciton::

        @callHooks('doEndIteration')
        def doEndIteration(self):
            pass

    This will call everything named _doEndIteration* at the beginning of the function call.
    """
    def callHooksWrap(f):
        @wraps(f)
        def wrapper(self,*args,**kwargs):

            for method in [posible for posible in dir(self) if ('_'+match) in posible]:
                if getattr(self,'debug',False): print (match+' is calling self.'+method)
                getattr(self,method)(*args, **kwargs)

            return f(self,*args,**kwargs)

        extra = """
            If you have things that also need to run in the method %s, you can create a method::

                def _%s*(self, ... ):
                    pass

            Where the * can be any string. If present, _%s* will be called at the start of the default %s call.
            You may also completely overwrite this function.
        """ % (match, match, match, match)

        wrapper.__doc__ += extra
        return wrapper
    return callHooksWrap

def dependentProperty(name, value, children, doc):
    def fget(self): return getattr(self,name,value)
    def fset(self, val):
        for child in children:
            if hasattr(self, child):
                delattr(self, child)
        setattr(self, name, val)
    return property(fget=fget, fset=fset, doc=doc)


class Counter(object):
    """
        Counter allows anything that calls it to record iterations and
        timings in a simple way.

        Also has plotting functions that allow quick recalls of data.

        If you want to use this, import *count* or *timeIt* and use them as decorators on class methods.<commit_msg>Modified callHooks to work when wrapping methods with no docstrings.<commit_after>import matutils
import sputils
import lomutils
import interputils
import ModelBuilder
import meshutils
from matutils import getSubArray, mkvc, ndgrid, ind2sub, sub2ind
from sputils import spzeros, kron3, speye, sdiag, ddx, av, avExtrap
from meshutils import exampleLomGird, meshTensors
from lomutils import volTetra, faceInfo, inv2X2BlockDiagonal, inv3X3BlockDiagonal, indexCube
from interputils import interpmat
from ipythonUtils import easyAnimate as animate
import Solver
from Solver import Solver
import Save
import Geophysics

import types
import time
import numpy as np
from functools import wraps

def hook(obj, method, name=None, overwrite=False, silent=False):
    """
        This dynamically binds a method to the instance of the class.

        If name is None, the name of the method is used.
    """
    if name is None:
        name = method.__name__
        if name == '<lambda>':
            raise Exception('Must provide name to hook lambda functions.')
    if not hasattr(obj,name) or overwrite:
        setattr(obj, name, types.MethodType( method, obj ))
        if getattr(obj,'debug',False):
            print 'Method '+name+' was added to class.'
    elif not silent or getattr(obj,'debug',False):
        print 'Method '+name+' was not overwritten.'


def setKwargs(obj, **kwargs):
    """Sets key word arguments (kwargs) that are present in the object, throw an error if they don't exist."""
    for attr in kwargs:
        if hasattr(obj, attr):
            setattr(obj, attr, kwargs[attr])
        else:
            raise Exception('%s attr is not recognized' % attr)

    hook(obj,hook, silent=True)
    hook(obj,setKwargs, silent=True)

def printTitles(obj, printers, name='Print Titles', pad=''):
    titles = ''
    widths = 0
    for printer in printers:
        titles += ('{:^%i}'%printer['width']).format(printer['title']) + ''
        widths += printer['width']
    print pad + "{0} {1} {0}".format('='*((widths-1-len(name))/2), name)
    print pad + titles
    print pad + "%s" % '-'*widths

def printLine(obj, printers, pad=''):
    values = ''
    for printer in printers:
        values += ('{:^%i}'%printer['width']).format(printer['format'] % printer['value'](obj))
    print pad + values

def checkStoppers(obj, stoppers):
    # check stopping rules
    optimal = []
    critical = []
    for stopper in stoppers:
        l = stopper['left'](obj)
        r = stopper['right'](obj)
        if stopper['stopType'] == 'optimal':
            optimal.append(l <= r)
        if stopper['stopType'] == 'critical':
            critical.append(l <= r)

    if obj.debug: print 'checkStoppers.optimal: ', optimal
    if obj.debug: print 'checkStoppers.critical: ', critical

    return (len(optimal)>0 and all(optimal)) | (len(critical)>0 and any(critical))

def printStoppers(obj, stoppers, pad='', stop='STOP!', done='DONE!'):
    print pad + "%s%s%s" % ('-'*25,stop,'-'*25)
    for stopper in stoppers:
        l = stopper['left'](obj)
        r = stopper['right'](obj)
        print pad + stopper['str'] % (l<=r,l,r)
    print pad + "%s%s%s" % ('-'*25,done,'-'*25)

def callHooks(match):
    """
    Use this to wrap a funciton::

        @callHooks('doEndIteration')
        def doEndIteration(self):
            pass

    This will call everything named _doEndIteration* at the beginning of the function call.
    """
    def callHooksWrap(f):
        @wraps(f)
        def wrapper(self,*args,**kwargs):

            for method in [posible for posible in dir(self) if ('_'+match) in posible]:
                if getattr(self,'debug',False): print (match+' is calling self.'+method)
                getattr(self,method)(*args, **kwargs)

            return f(self,*args,**kwargs)

        extra = """
            If you have things that also need to run in the method %s, you can create a method::

                def _%s*(self, ... ):
                    pass

            Where the * can be any string. If present, _%s* will be called at the start of the default %s call.
            You may also completely overwrite this function.
        """ % (match, match, match, match)
        try:
            wrapper.__doc__ += extra
        except Exception, e:
            pass
        return wrapper
    return callHooksWrap

def dependentProperty(name, value, children, doc):
    def fget(self): return getattr(self,name,value)
    def fset(self, val):
        for child in children:
            if hasattr(self, child):
                delattr(self, child)
        setattr(self, name, val)
    return property(fget=fget, fset=fset, doc=doc)


class Counter(object):
    """
        Counter allows anything that calls it to record iterations and
        timings in a simple way.

        Also has plotting functions that allow quick recalls of data.

        If you want to use this, import *count* or *timeIt* and use them as decorators on class methods.
{'fraction_non_alphanumeric': 0.12104567185433832, 'fraction_numerical': 0.004679076391008036, 'mean_word_length': 2.815289095847885, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7023761', 'n_tokens_mistral': 3000, 'n_tokens_neox': 2897, 'n_words': 997}