idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
60,600
def define ( self , * args : Any , ** kwargs : Any ) -> None : if isinstance ( args [ 0 ] , str ) : self . _define_orig ( * args , ** kwargs ) elif isinstance ( args [ 0 ] , type ) : self . _define_class ( * args , ** kwargs ) else : raise TypeError ( 'Invalid argument for define: {}, {}' . format ( args , kwargs ) )
Add new custom element .
60,601
def event_handler ( msg : EventMsgDict ) -> Event : e = create_event_from_msg ( msg ) if e . currentTarget is None : if e . type not in [ 'mount' , 'unmount' ] : id = msg [ 'currentTarget' ] [ 'id' ] logger . warning ( 'No such element: wdom_id={}' . format ( id ) ) return e e . currentTarget . on_event_pre ( e ) e . currentTarget . dispatchEvent ( e ) return e
Handle events emitted on browser .
60,602
def response_handler ( msg : Dict [ str , str ] ) -> None : from wdom . document import getElementByWdomId id = msg [ 'id' ] elm = getElementByWdomId ( id ) if elm : elm . on_response ( msg ) else : logger . warning ( 'No such element: wdom_id={}' . format ( id ) )
Handle response sent by browser .
60,603
def on_websocket_message ( message : str ) -> None : msgs = json . loads ( message ) for msg in msgs : if not isinstance ( msg , dict ) : logger . error ( 'Invalid WS message format: {}' . format ( message ) ) continue _type = msg . get ( 'type' ) if _type == 'log' : log_handler ( msg [ 'level' ] , msg [ 'message' ] ) elif _type == 'event' : event_handler ( msg [ 'event' ] ) elif _type == 'response' : response_handler ( msg ) else : raise ValueError ( 'Unkown message type: {}' . format ( message ) )
Handle messages from browser .
60,604
def parse_html ( html : str , parser : FragmentParser = None ) -> Node : parser = parser or FragmentParser ( ) parser . feed ( html ) return parser . root
Parse HTML fragment and return DocumentFragment object .
60,605
def getElementsBy ( start_node : ParentNode , cond : Callable [ [ 'Element' ] , bool ] ) -> NodeList : elements = [ ] for child in start_node . children : if cond ( child ) : elements . append ( child ) elements . extend ( child . getElementsBy ( cond ) ) return NodeList ( elements )
Return list of child elements of start_node which matches cond .
60,606
def getElementsByTagName ( start_node : ParentNode , tag : str ) -> NodeList : _tag = tag . upper ( ) return getElementsBy ( start_node , lambda node : node . tagName == _tag )
Get child nodes which tag name is tag .
60,607
def getElementsByClassName ( start_node : ParentNode , class_name : str ) -> NodeList : classes = set ( class_name . split ( ' ' ) ) return getElementsBy ( start_node , lambda node : classes . issubset ( set ( node . classList ) ) )
Get child nodes which has class_name class attribute .
60,608
def add ( self , * tokens : str ) -> None : from wdom . web_node import WdomElement _new_tokens = [ ] for token in tokens : self . _validate_token ( token ) if token and token not in self : self . _list . append ( token ) _new_tokens . append ( token ) if isinstance ( self . _owner , WdomElement ) and _new_tokens : self . _owner . js_exec ( 'addClass' , _new_tokens )
Add new tokens to list .
60,609
def remove ( self , * tokens : str ) -> None : from wdom . web_node import WdomElement _removed_tokens = [ ] for token in tokens : self . _validate_token ( token ) if token in self : self . _list . remove ( token ) _removed_tokens . append ( token ) if isinstance ( self . _owner , WdomElement ) and _removed_tokens : self . _owner . js_exec ( 'removeClass' , _removed_tokens )
Remove tokens from list .
60,610
def contains ( self , token : str ) -> bool : self . _validate_token ( token ) return token in self
Return if the token is in the list or not .
60,611
def html ( self ) -> str : if self . _owner and self . name in self . _owner . _special_attr_boolean : return self . name else : value = self . value if isinstance ( value , str ) : value = html_ . escape ( value ) return '{name}="{value}"' . format ( name = self . name , value = value )
Return string representation of this .
60,612
def html ( self ) -> str : if isinstance ( self . value , bool ) : val = 'true' if self . value else 'false' else : val = str ( self . value ) return 'draggable="{}"' . format ( val )
Return html representation .
60,613
def getNamedItem ( self , name : str ) -> Optional [ Attr ] : return self . _dict . get ( name , None )
Get Attr object which has name .
60,614
def setNamedItem ( self , item : Attr ) -> None : from wdom . web_node import WdomElement if not isinstance ( item , Attr ) : raise TypeError ( 'item must be an instance of Attr' ) if isinstance ( self . _owner , WdomElement ) : self . _owner . js_exec ( 'setAttribute' , item . name , item . value ) self . _dict [ item . name ] = item item . _owner = self . _owner
Set Attr object in this collection .
60,615
def item ( self , index : int ) -> Optional [ Attr ] : if 0 <= index < len ( self ) : return self . _dict [ tuple ( self . _dict . keys ( ) ) [ index ] ] return None
Return index - th attr node .
60,616
def toString ( self ) -> str : return ' ' . join ( attr . html for attr in self . _dict . values ( ) )
Return string representation of collections .
60,617
def start_tag ( self ) -> str : tag = '<' + self . tag attrs = self . _get_attrs_by_string ( ) if attrs : tag = ' ' . join ( ( tag , attrs ) ) return tag + '>'
Return HTML start tag .
60,618
def insertAdjacentHTML ( self , position : str , html : str ) -> None : df = self . _parse_html ( html ) pos = position . lower ( ) if pos == 'beforebegin' : self . before ( df ) elif pos == 'afterbegin' : self . prepend ( df ) elif pos == 'beforeend' : self . append ( df ) elif pos == 'afterend' : self . after ( df ) else : raise ValueError ( 'The value provided ({}) is not one of "beforeBegin", ' '"afterBegin", "beforeEnd", or "afterEnd".' . format ( position ) )
Parse html to DOM and insert to position .
60,619
def getAttribute ( self , attr : str ) -> _AttrValueType : if attr == 'class' : if self . classList : return self . classList . toString ( ) return None attr_node = self . getAttributeNode ( attr ) if attr_node is None : return None return attr_node . value
Get attribute of this node as string format .
60,620
def getAttributeNode ( self , attr : str ) -> Optional [ Attr ] : return self . attributes . getNamedItem ( attr )
Get attribute of this node as Attr format .
60,621
def hasAttribute ( self , attr : str ) -> bool : if attr == 'class' : return bool ( self . classList ) return attr in self . attributes
Return True if this node has attr .
60,622
def setAttribute ( self , attr : str , value : _AttrValueType ) -> None : self . _set_attribute ( attr , value )
Set attr and value in this node .
60,623
def removeAttributeNode ( self , attr : Attr ) -> Optional [ Attr ] : return self . attributes . removeNamedItem ( attr )
Remove Attr node from this node .
60,624
def style ( self , style : _AttrValueType ) -> None : if isinstance ( style , str ) : self . __style . _parse_str ( style ) elif style is None : self . __style . _parse_str ( '' ) elif isinstance ( style , CSSStyleDeclaration ) : self . __style . _owner = None if style . _owner is not None : new_style = CSSStyleDeclaration ( owner = self ) new_style . update ( style ) self . __style = new_style else : style . _owner = self self . __style = style else : raise TypeError ( 'Invalid type for style: {}' . format ( type ( style ) ) )
Set style attribute of this node .
60,625
def draggable ( self ) -> Union [ bool , str ] : if not self . hasAttribute ( 'draggable' ) : return False return self . getAttribute ( 'draggable' )
Get draggable property .
60,626
def draggable ( self , value : Union [ bool , str ] ) -> None : if value is False : self . removeAttribute ( 'draggable' ) else : self . setAttribute ( 'draggable' , value )
Set draggable property .
60,627
def form ( self ) -> Optional [ 'HTMLFormElement' ] : if self . __form : return self . __form parent = self . parentNode while parent : if isinstance ( parent , HTMLFormElement ) : return parent else : parent = parent . parentNode return None
Get HTMLFormElement object related to this node .
60,628
def control ( self ) -> Optional [ HTMLElement ] : id = self . getAttribute ( 'for' ) if id : if self . ownerDocument : return self . ownerDocument . getElementById ( id ) elif isinstance ( id , str ) : from wdom . document import getElementById return getElementById ( id ) else : raise TypeError ( '"for" attribute must be string' ) return None
Return related HTMLElement object .
60,629
def selectedOptions ( self ) -> NodeList : return NodeList ( list ( opt for opt in self . options if opt . selected ) )
Return all selected option nodes .
60,630
def NewTagClass ( class_name : str , tag : str = None , bases : Union [ type , Iterable ] = ( Tag , ) , ** kwargs : Any ) -> type : if tag is None : tag = class_name . lower ( ) if not isinstance ( type , tuple ) : if isinstance ( bases , Iterable ) : bases = tuple ( bases ) elif isinstance ( bases , type ) : bases = ( bases , ) else : TypeError ( 'Invalid base class: {}' . format ( str ( bases ) ) ) kwargs [ 'tag' ] = tag cls = new_class ( class_name , bases , { } , lambda ns : ns . update ( kwargs ) ) return cls
Generate and return new Tag class .
60,631
def _clone_node ( self ) -> 'Tag' : clone = type ( self ) ( ) for attr in self . attributes : clone . setAttribute ( attr , self . getAttribute ( attr ) ) for c in self . classList : clone . addClass ( c ) clone . style . update ( self . style ) return clone
Need to copy class not tag .
60,632
def textContent ( self , text : str ) -> None : if self . _inner_element : self . _inner_element . textContent = text else : super ( ) . textContent = text
Set text content to inner node .
60,633
def html ( self ) -> str : if self . _inner_element : return self . start_tag + self . _inner_element . html + self . end_tag return super ( ) . html
Get whole html representation of this node .
60,634
def innerHTML ( self ) -> str : if self . _inner_element : return self . _inner_element . innerHTML return super ( ) . innerHTML
Get innerHTML of the inner node .
60,635
def get ( self ) -> None : from wdom . document import get_document logger . info ( 'connected' ) self . write ( get_document ( ) . build ( ) )
Return whole html representation of the root document .
60,636
async def terminate ( self ) -> None : await asyncio . sleep ( config . shutdown_wait ) if not is_connected ( ) : stop_server ( self . application . server ) self . application . loop . stop ( )
Terminate server if no more connection exists .
60,637
def on_close ( self ) -> None : logger . info ( 'WebSocket CLOSED' ) if self in connections : connections . remove ( self ) if config . auto_shutdown and not is_connected ( ) : asyncio . ensure_future ( self . terminate ( ) )
Execute when connection closed .
60,638
def log_request ( self , handler : web . RequestHandler ) -> None : if 'log_function' in self . settings : self . settings [ 'log_function' ] ( handler ) return status = handler . get_status ( ) if status < 400 : log_method = logger . info elif status < 500 : log_method = logger . warning else : log_method = logger . error request_time = 1000.0 * handler . request . request_time ( ) if request_time > 10 : logger . warning ( '%d %s %.2fms' , status , handler . _request_summary ( ) , request_time ) else : log_method ( '%d %s' , status , handler . _request_summary ( ) )
Handle access log .
60,639
def add_static_path ( self , prefix : str , path : str ) -> None : pattern = prefix if not pattern . startswith ( '/' ) : pattern = '/' + pattern if not pattern . endswith ( '/(.*)' ) : pattern = pattern + '/(.*)' self . add_handlers ( r'.*' , [ ( pattern , StaticFileHandler , dict ( path = path ) ) ] )
Add path to serve static files .
60,640
def add_favicon_path ( self , path : str ) -> None : spec = web . URLSpec ( '/(favicon.ico)' , StaticFileHandler , dict ( path = path ) ) handlers = self . handlers [ 0 ] [ 1 ] handlers . append ( spec )
Add path to serve favicon file .
60,641
def _exec_action ( self , method , type , chaincodeID , function , args , id , secure_context = None , confidentiality_level = CHAINCODE_CONFIDENTIAL_PUB , metadata = None ) : if method not in DEFAULT_CHAINCODE_METHODS : self . logger . error ( 'Non-supported chaincode method: ' + method ) data = { "jsonrpc" : "2.0" , "method" : method , "params" : { "type" : type , "chaincodeID" : chaincodeID , "ctorMsg" : { "function" : function , "args" : args } } , "id" : id } if secure_context : data [ "params" ] [ "secureContext" ] = secure_context u = self . _url ( "/chaincode" ) response = self . _post ( u , data = json . dumps ( data ) ) return self . _result ( response , True )
Private method to implement the deploy invoke and query actions
60,642
def watch_dir ( path : str ) -> None : _compile_exclude_patterns ( ) if config . autoreload or config . debug : p = pathlib . Path ( path ) p . resolve ( ) _add_watch_path ( p )
Add path to watch for autoreload .
60,643
def open_browser ( url : str , browser : str = None ) -> None : if '--open-browser' in sys . argv : sys . argv . remove ( '--open-browser' ) if browser is None : browser = config . browser if browser in _browsers : webbrowser . get ( browser ) . open ( url ) else : webbrowser . open ( url )
Open web browser .
60,644
def parse_style_decl ( style : str , owner : AbstractNode = None ) -> CSSStyleDeclaration : _style = CSSStyleDeclaration ( style , owner = owner ) return _style
Make CSSStyleDeclaration from style string .
60,645
def parse_style_rules ( styles : str ) -> CSSRuleList : rules = CSSRuleList ( ) for m in _style_rule_re . finditer ( styles ) : rules . append ( CSSStyleRule ( m . group ( 1 ) , parse_style_decl ( m . group ( 2 ) ) ) ) return rules
Make CSSRuleList object from style string .
60,646
def cssText ( self ) -> str : text = '; ' . join ( '{0}: {1}' . format ( k , v ) for k , v in self . items ( ) ) if text : text += ';' return text
String - representation .
60,647
def removeProperty ( self , prop : str ) -> str : removed_prop = self . get ( prop ) if removed_prop is not None : del self [ prop ] return removed_prop
Remove the css property .
60,648
def setProperty ( self , prop : str , value : str , priority : str = None ) -> None : self [ prop ] = value
Set property as the value .
60,649
def cssText ( self ) -> str : _style = self . style . cssText if _style : return '{0} {{{1}}}' . format ( self . selectorText , _style ) return ''
Return string representation of this rule .
60,650
def set_loglevel ( level : Union [ int , str , None ] = None ) -> None : if level is not None : lv = level_to_int ( level ) elif config . logging : lv = level_to_int ( config . logging ) elif config . debug : lv = logging . DEBUG else : lv = logging . INFO root_logger . setLevel ( lv ) _log_handler . setLevel ( lv )
Set proper log - level .
60,651
def parse_command_line ( ) -> Namespace : import tornado . options parser . parse_known_args ( namespace = config ) set_loglevel ( ) for k , v in vars ( config ) . items ( ) : if k . startswith ( 'log' ) : tornado . options . options . __setattr__ ( k , v ) return config
Parse command line options and set them to config .
60,652
def suppress_logging ( ) -> None : from wdom import options options . root_logger . removeHandler ( options . _log_handler ) options . root_logger . addHandler ( logging . NullHandler ( ) )
Suppress log output to stdout .
60,653
def reset ( ) -> None : from wdom . document import get_new_document , set_document from wdom . element import Element from wdom . server import _tornado from wdom . window import customElements set_document ( get_new_document ( ) ) _tornado . connections . clear ( ) _tornado . set_application ( _tornado . Application ( ) ) Element . _elements_with_id . clear ( ) Element . _element_buffer . clear ( ) customElements . reset ( )
Reset all wdom objects .
60,654
def _dnsname_match ( dn , hostname , max_wildcards = 1 ) : pats = [ ] if not dn : return False split_dn = dn . split ( r'.' ) leftmost , remainder = split_dn [ 0 ] , split_dn [ 1 : ] wildcards = leftmost . count ( '*' ) if wildcards > max_wildcards : raise CertificateError ( "too many wildcards in certificate DNS name: " + repr ( dn ) ) if not wildcards : return dn . lower ( ) == hostname . lower ( ) if leftmost == '*' : pats . append ( '[^.]+' ) elif leftmost . startswith ( 'xn--' ) or hostname . startswith ( 'xn--' ) : pats . append ( re . escape ( leftmost ) ) else : pats . append ( re . escape ( leftmost ) . replace ( r'\*' , '[^.]*' ) ) for frag in remainder : pats . append ( re . escape ( frag ) ) pat = re . compile ( r'\A' + r'\.' . join ( pats ) + r'\Z' , re . IGNORECASE ) return pat . match ( hostname )
Matching according to RFC 6125 section 6 . 4 . 3
60,655
def _ensure_node ( node : Union [ str , AbstractNode ] ) -> AbstractNode : if isinstance ( node , str ) : return Text ( node ) elif isinstance ( node , Node ) : return node else : raise TypeError ( 'Invalid type to append: {}' . format ( node ) )
Ensure to be node .
60,656
def previousSibling ( self ) -> Optional [ AbstractNode ] : parent = self . parentNode if parent is None : return None return parent . childNodes . item ( parent . childNodes . index ( self ) - 1 )
Return the previous sibling of this node .
60,657
def ownerDocument ( self ) -> Optional [ AbstractNode ] : if self . nodeType == Node . DOCUMENT_NODE : return self elif self . parentNode : return self . parentNode . ownerDocument return None
Return the owner document of this node .
60,658
def index ( self , node : AbstractNode ) -> int : if node in self . childNodes : return self . childNodes . index ( node ) elif isinstance ( node , Text ) : for i , n in enumerate ( self . childNodes ) : if isinstance ( n , Text ) and n . data == node : return i raise ValueError ( 'node is not in this node' )
Return index of the node .
60,659
def insertBefore ( self , node : AbstractNode , ref_node : AbstractNode ) -> AbstractNode : return self . _insert_before ( node , ref_node )
Insert a node just before the reference node .
60,660
def replaceChild ( self , new_child : AbstractNode , old_child : AbstractNode ) -> AbstractNode : return self . _replace_child ( new_child , old_child )
Replace an old child with new child .
60,661
def cloneNode ( self , deep : bool = False ) -> AbstractNode : if deep : return self . _clone_node_deep ( ) return self . _clone_node ( )
Return new copy of this node .
60,662
def item ( self , index : int ) -> Optional [ Node ] : if not isinstance ( index , int ) : raise TypeError ( 'Indeces must be integer, not {}' . format ( type ( index ) ) ) return self . __nodes [ index ] if 0 <= index < self . length else None
Return item with the index .
60,663
def children ( self ) -> NodeList : return NodeList ( [ e for e in self . childNodes if e . nodeType == Node . ELEMENT_NODE ] )
Return list of child nodes .
60,664
def firstElementChild ( self ) -> Optional [ AbstractNode ] : for child in self . childNodes : if child . nodeType == Node . ELEMENT_NODE : return child return None
First Element child node .
60,665
def lastElementChild ( self ) -> Optional [ AbstractNode ] : for child in reversed ( self . childNodes ) : if child . nodeType == Node . ELEMENT_NODE : return child return None
Last Element child node .
60,666
def prepend ( self , * nodes : Union [ str , AbstractNode ] ) -> None : node = _to_node_list ( nodes ) if self . firstChild : self . insertBefore ( node , self . firstChild ) else : self . appendChild ( node )
Insert new nodes before first child node .
60,667
def append ( self , * nodes : Union [ AbstractNode , str ] ) -> None : node = _to_node_list ( nodes ) self . appendChild ( node )
Append new nodes after last child node .
60,668
def nextElementSibling ( self ) -> Optional [ AbstractNode ] : if self . parentNode is None : return None siblings = self . parentNode . childNodes for i in range ( siblings . index ( self ) + 1 , len ( siblings ) ) : n = siblings [ i ] if n . nodeType == Node . ELEMENT_NODE : return n return None
Next Element Node .
60,669
def before ( self , * nodes : Union [ AbstractNode , str ] ) -> None : if self . parentNode : node = _to_node_list ( nodes ) self . parentNode . insertBefore ( node , self )
Insert nodes before this node .
60,670
def after ( self , * nodes : Union [ AbstractNode , str ] ) -> None : if self . parentNode : node = _to_node_list ( nodes ) _next_node = self . nextSibling if _next_node is None : self . parentNode . appendChild ( node ) else : self . parentNode . insertBefore ( node , _next_node )
Append nodes after this node .
60,671
def replaceWith ( self , * nodes : Union [ AbstractNode , str ] ) -> None : if self . parentNode : node = _to_node_list ( nodes ) self . parentNode . replaceChild ( node , self )
Replace this node with nodes .
60,672
def insertData ( self , offset : int , string : str ) -> None : self . _insert_data ( offset , string )
Insert string at offset on this node .
60,673
def deleteData ( self , offset : int , count : int ) -> None : self . _delete_data ( offset , count )
Delete data by offset to count letters .
60,674
def replaceData ( self , offset : int , count : int , string : str ) -> None : self . _replace_data ( offset , count , string )
Replace data from offset to count by string .
60,675
def html ( self ) -> str : if self . parentNode and self . parentNode . _should_escape_text : return html . escape ( self . data ) return self . data
Return html - escaped string representation of this node .
60,676
def create_event ( msg : EventMsgDict ) -> Event : proto = msg . get ( 'proto' , '' ) cls = proto_dict . get ( proto , Event ) e = cls ( msg [ 'type' ] , msg ) return e
Create Event from JSOM msg and set target nodes .
60,677
def getData ( self , type : str ) -> str : return self . __data . get ( normalize_type ( type ) , '' )
Get data of type format .
60,678
def setData ( self , type : str , data : str ) -> None : type = normalize_type ( type ) if type in self . __data : del self . __data [ type ] self . __data [ type ] = data
Set data of type format .
60,679
def clearData ( self , type : str = '' ) -> None : type = normalize_type ( type ) if not type : self . __data . clear ( ) elif type in self . __data : del self . __data [ type ]
Remove data of type foramt .
60,680
def addEventListener ( self , event : str , listener : _EventListenerType ) -> None : self . _add_event_listener ( event , listener )
Add event listener to this node .
60,681
def removeEventListener ( self , event : str , listener : _EventListenerType ) -> None : self . _remove_event_listener ( event , listener )
Remove an event listener of this node .
60,682
def on_response ( self , msg : Dict [ str , str ] ) -> None : response = msg . get ( 'data' , False ) if response : task = self . __tasks . pop ( msg . get ( 'reqid' ) , False ) if task and not task . cancelled ( ) and not task . done ( ) : task . set_result ( msg . get ( 'data' ) )
Run when get response from browser .
60,683
def js_exec ( self , method : str , * args : Union [ int , str , bool ] ) -> None : if self . connected : self . ws_send ( dict ( method = method , params = args ) )
Execute method in the related node on browser .
60,684
def js_query ( self , query : str ) -> Awaitable : if self . connected : self . js_exec ( query , self . __reqid ) fut = Future ( ) self . __tasks [ self . __reqid ] = fut self . __reqid += 1 return fut f = Future ( ) f . set_result ( None ) return f
Send query to related DOM on browser .
60,685
def ws_send ( self , obj : Dict [ str , Union [ Iterable [ _T_MsgItem ] , _T_MsgItem ] ] ) -> None : from wdom import server if self . ownerDocument is not None : obj [ 'target' ] = 'node' obj [ 'id' ] = self . wdom_id server . push_message ( obj )
Send obj as message to the related nodes on browser .
60,686
def get_ts_stats_significance ( self , x , ts , stat_ts_func , null_ts_func , B = 1000 , permute_fast = False , label_ts = '' ) : stats_ts , pvals , nums = ts_stats_significance ( ts , stat_ts_func , null_ts_func , B = B , permute_fast = permute_fast ) return stats_ts , pvals , nums
Returns the statistics pvalues and the actual number of bootstrap samples .
60,687
def generate_null_timeseries ( self , ts , mu , sigma ) : l = len ( ts ) return np . random . normal ( mu , sigma , l )
Generate a time series with a given mu and sigma . This serves as the NULL distribution .
60,688
def compute_balance_mean ( self , ts , t ) : return np . mean ( ts [ t + 1 : ] ) - np . mean ( ts [ : t + 1 ] )
Compute the balance . The right end - the left end .
60,689
def compute_balance_median ( self , ts , t ) : return np . median ( ts [ t + 1 : ] ) - np . median ( ts [ : t + 1 ] )
Compute the balance at either end .
60,690
def compute_cusum_ts ( self , ts ) : mean = np . mean ( ts ) cusums = np . zeros ( len ( ts ) ) cusum [ 0 ] = ( ts [ 0 ] - mean ) for i in np . arange ( 1 , len ( ts ) ) : cusums [ i ] = cusums [ i - 1 ] + ( ts [ i ] - mean ) assert ( np . isclose ( cumsum [ - 1 ] , 0.0 ) ) return cusums
Compute the Cumulative Sum at each point t of the time series .
60,691
def detect_mean_shift ( self , ts , B = 1000 ) : x = np . arange ( 0 , len ( ts ) ) stat_ts_func = self . compute_balance_mean_ts null_ts_func = self . shuffle_timeseries stats_ts , pvals , nums = self . get_ts_stats_significance ( x , ts , stat_ts_func , null_ts_func , B = B , permute_fast = True ) return stats_ts , pvals , nums
Detect mean shift in a time series . B is number of bootstrapped samples to draw .
60,692
def parallelize_func ( iterable , func , chunksz = 1 , n_jobs = 16 , * args , ** kwargs ) : chunker = func chunks = more_itertools . chunked ( iterable , chunksz ) chunks_results = Parallel ( n_jobs = n_jobs , verbose = 50 ) ( delayed ( chunker ) ( chunk , * args , ** kwargs ) for chunk in chunks ) results = more_itertools . flatten ( chunks_results ) return list ( results )
Parallelize a function over each element of an iterable .
60,693
def ts_stats_significance ( ts , ts_stat_func , null_ts_func , B = 1000 , permute_fast = False ) : stats_ts = ts_stat_func ( ts ) if permute_fast : null_ts = map ( np . random . permutation , np . array ( [ ts , ] * B ) ) else : null_ts = np . vstack ( [ null_ts_func ( ts ) for i in np . arange ( 0 , B ) ] ) stats_null_ts = np . vstack ( [ ts_stat_func ( nts ) for nts in null_ts ] ) pvals = [ ] nums = [ ] for i in np . arange ( 0 , len ( stats_ts ) ) : num_samples = np . sum ( ( stats_null_ts [ : , i ] >= stats_ts [ i ] ) ) nums . append ( num_samples ) pval = num_samples / float ( B ) pvals . append ( pval ) return stats_ts , pvals , nums
Compute the statistical significance of a test statistic at each point of the time series .
60,694
def get_ci ( theta_star , blockratio = 1.0 ) : b_star = np . sort ( theta_star [ ~ np . isnan ( theta_star ) ] ) se = np . std ( b_star ) * np . sqrt ( blockratio ) ci = [ b_star [ int ( len ( b_star ) * .025 ) ] , b_star [ int ( len ( b_star ) * .975 ) ] ] return ci
Get the confidence interval .
60,695
def get_pvalue ( value , ci ) : from scipy . stats import norm se = ( ci [ 1 ] - ci [ 0 ] ) / ( 2.0 * 1.96 ) z = value / se pvalue = - 2 * norm . cdf ( - np . abs ( z ) ) return pvalue
Get the p - value from the confidence interval .
60,696
def ts_stats_significance_bootstrap ( ts , stats_ts , stats_func , B = 1000 , b = 3 ) : pvals = [ ] for tp in np . arange ( 0 , len ( stats_ts ) ) : pf = partial ( stats_func , t = tp ) bs = bootstrap_ts ( ts , pf , B = B , b = b ) ci = get_ci ( bs , blockratio = b / len ( stats_ts ) ) pval = abs ( get_pvalue ( stats_ts [ tp ] , ci ) ) pvals . append ( pval ) return pvals
Compute the statistical significance of a test statistic at each point of the time series by using timeseries boootstrap .
60,697
def format_traceback ( extracted_tb , exc_type , exc_value , cwd = '' , term = None , function_color = 12 , dim_color = 8 , editor = 'vi' , template = DEFAULT_EDITOR_SHORTCUT_TEMPLATE ) : def format_shortcut ( editor , path , line_number , function = None ) : return template . format ( editor = editor , line_number = line_number or 0 , path = path , function = function or u'' , hash_if_function = u' # ' if function else u'' , function_format = term . color ( function_color ) , normal = term . normal , dim_format = term . color ( dim_color ) + term . bold , line_number_max_width = line_number_max_width , term = term ) template += '\n' extracted_tb = _unicode_decode_extracted_tb ( extracted_tb ) if not term : term = Terminal ( ) if extracted_tb : for i , ( file , line_number , function , text ) in enumerate ( extracted_tb ) : extracted_tb [ i ] = human_path ( src ( file ) , cwd ) , line_number , function , text line_number_max_width = len ( unicode ( max ( the_line for _ , the_line , _ , _ in extracted_tb ) ) ) for i , ( path , line_number , function , text ) in enumerate ( extracted_tb ) : text = ( text and text . strip ( ) ) or u'' yield ( format_shortcut ( editor , path , line_number , function ) + ( u' %s\n' % text ) ) if exc_type is SyntaxError : if hasattr ( exc_value , 'filename' ) and hasattr ( exc_value , 'lineno' ) : exc_lines = [ format_shortcut ( editor , exc_value . filename , exc_value . lineno ) ] formatted_exception = format_exception_only ( SyntaxError , exc_value ) [ 1 : ] else : exc_lines = [ ] formatted_exception = format_exception_only ( SyntaxError , exc_value ) formatted_exception . append ( u'(Try --nologcapture for a more detailed traceback)\n' ) else : exc_lines = [ ] formatted_exception = format_exception_only ( exc_type , exc_value ) exc_lines . extend ( [ _decode ( f ) for f in formatted_exception ] ) yield u'' . join ( exc_lines )
Return an iterable of formatted Unicode traceback frames .
60,698
def extract_relevant_tb ( tb , exctype , is_test_failure ) : while tb and _is_unittest_frame ( tb ) : tb = tb . tb_next if is_test_failure : length = _count_relevant_tb_levels ( tb ) return extract_tb ( tb , length ) return extract_tb ( tb )
Return extracted traceback frame 4 - tuples that aren t unittest ones .
60,699
def _unicode_decode_extracted_tb ( extracted_tb ) : return [ ( _decode ( file ) , line_number , _decode ( function ) , _decode ( text ) ) for file , line_number , function , text in extracted_tb ]
Return a traceback with the string elements translated into Unicode .