idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
30,900
def make_logger ( name , stream_type , jobs ) : logger = logging . getLogger ( 'noodles' ) . getChild ( name ) @ stream_type def log_message ( message ) : if message is EndOfQueue : logger . info ( "-end-of-queue-" ) elif isinstance ( message , JobMessage ) : logger . info ( "job %10s: %s" , message . key , message ...
Create a logger component .
30,901
def run_process ( workflow , * , n_processes , registry , verbose = False , jobdirs = False , init = None , finish = None , deref = False ) : workers = { } for i in range ( n_processes ) : new_worker = process_worker ( registry , verbose , jobdirs , init , finish ) workers [ 'worker {0:2}' . format ( i ) ] = new_worker...
Run the workflow using a number of new python processes . Use this runner to test the workflow in a situation where data serial is needed .
30,902
def xenon_interactive_worker ( machine , worker_config , input_queue = None , stderr_sink = None ) : if input_queue is None : input_queue = Queue ( ) registry = worker_config . registry ( ) @ pull_map def serialise ( obj ) : if isinstance ( obj , JobMessage ) : print ( 'serializing:' , str ( obj . node ) , file = sys ....
Uses Xenon to run a single remote interactive worker .
30,903
def wait_until_running ( self , callback = None ) : status = self . machine . scheduler . wait_until_running ( self . job , self . worker_config . time_out ) if status . running : self . online = True if callback : callback ( self ) else : raise TimeoutError ( "Timeout while waiting for worker to run: " + self . worker...
Waits until the remote worker is running then calls the callback . Usually this method is passed to a different thread ; the callback is then a function patching results through to the result queue .
30,904
def add_xenon_worker ( self , worker_config ) : c = XenonInteractiveWorker ( self . machine , worker_config ) w = RemoteWorker ( worker_config . name , threading . Lock ( ) , worker_config . n_threads , [ ] , * c . setup ( ) ) with self . wlock : self . workers [ worker_config . name ] = w def populate ( job_source ) :...
Adds a worker to the pool ; sets gears in motion .
30,905
def find_first ( pred , lst ) : if lst : return s_find_first ( pred , lst [ 0 ] , [ quote ( l ) for l in lst [ 1 : ] ] ) else : return None
Find the first result of a list of promises lst that satisfies a predicate pred .
30,906
def s_find_first ( pred , first , lst ) : if pred ( first ) : return first elif lst : return s_find_first ( pred , unquote ( lst [ 0 ] ) , lst [ 1 : ] ) else : return None
Evaluate first ; if predicate pred succeeds on the result of first return the result ; otherwise recur on the first element of lst .
30,907
def run_online_mode ( args ) : print ( "\033[47;30m Netherlands\033[48;2;0;174;239;37m▌" "\033[38;2;255;255;255me\u20d2Science\u20d2\033[37m▐" "\033[47;30mcenter \033[m Noodles worker" , file = sys . stderr ) if args . n == 1 : registry = look_up ( args . registry ) ( ) finish = None input_stream = JSONObjectReader ( r...
Run jobs .
30,908
def _format_arg_list ( args , variadic = False ) : def sugar ( s ) : s = s . replace ( "{" , "{{" ) . replace ( "}" , "}}" ) if len ( s ) > 50 : return s [ : 20 ] + " ... " + s [ - 20 : ] else : return s def arg_to_str ( arg ) : if isinstance ( arg , str ) : return sugar ( repr ( arg ) ) elif arg is Parameter . empty :...
Format a list of arguments for pretty printing .
30,909
def get_workflow_graph ( promise ) : workflow = get_workflow ( promise ) dot = Digraph ( ) for i , n in workflow . nodes . items ( ) : dot . node ( str ( i ) , label = "{0} \n {1}" . format ( n . foo . __name__ , _format_arg_list ( n . bound_args . args ) ) ) for i in workflow . links : for j in workflow . links [ i ] ...
Get a graph of a promise .
30,910
def display_workflows ( prefix , ** kwargs ) : from IPython . display import display , Markdown def create_svg ( name , workflow ) : name = name . replace ( '_' , '-' ) filename = '{}-{}.svg' . format ( prefix , name ) dot = get_workflow_graph ( workflow ) dot . attr ( 'graph' , bgcolor = 'transparent' ) with open ( fi...
Display workflows in a table . This generates SVG files . Use this in a Jupyter notebook and ship the images
30,911
def snip_line ( line , max_width , split_at ) : if len ( line ) < max_width : return line return line [ : split_at ] + " … " \ + line [ - ( max_width - split_at - 3 ) : ]
Shorten a line to a maximum length .
30,912
def run_and_print_log ( workflow , highlight = None ) : from noodles . run . threading . sqlite3 import run_parallel from noodles import serial import io import logging log = io . StringIO ( ) log_handler = logging . StreamHandler ( log ) formatter = logging . Formatter ( '%(asctime)s - %(message)s' ) log_handler . set...
Run workflow on multi - threaded worker cached with Sqlite3 .
30,913
def run_single_with_display ( wf , display ) : S = Scheduler ( error_handler = display . error_handler ) W = Queue ( ) >> branch ( log_job_start . to ( sink_map ( display ) ) ) >> worker >> branch ( sink_map ( display ) ) return S . run ( W , get_workflow ( wf ) )
Adds a display to the single runner . Everything still runs in a single thread . Every time a job is pulled by the worker a message goes to the display routine ; when the job is finished the result is sent to the display routine .
30,914
def run_parallel_with_display ( wf , n_threads , display ) : LogQ = Queue ( ) S = Scheduler ( error_handler = display . error_handler ) threading . Thread ( target = patch , args = ( LogQ . source , sink_map ( display ) ) , daemon = True ) . start ( ) W = Queue ( ) >> branch ( log_job_start >> LogQ . sink ) >> thread_p...
Adds a display to the parallel runner . Because messages come in asynchronously now we start an extra thread just for the display routine .
30,915
def decorator ( f ) : @ functools . wraps ( f ) def decoratored_function ( * args , ** kwargs ) : if args and len ( args ) == 1 : return f ( * args , ** kwargs ) if args : raise TypeError ( "This decorator only accepts extra keyword arguments." ) return lambda g : f ( g , ** kwargs ) return decoratored_function
Creates a paramatric decorator from a function . The resulting decorator will optionally take keyword arguments .
30,916
def run ( self , connection : Connection , master : Workflow ) : source , sink = connection . setup ( ) self . add_workflow ( master , master , master . root , sink ) graceful_exit = False errors = [ ] for job_key , status , result , err_msg in source : wf , n = self . jobs [ job_key ] if status == 'error' : graceful_e...
Run a workflow .
30,917
def ref_argument ( bound_args , address ) : if address . kind == ArgumentKind . regular : return bound_args . arguments [ address . name ] return bound_args . arguments [ address . name ] [ address . key ]
Taking a bound_args object and an ArgumentAddress retrieves the data currently stored in bound_args for this particular address .
30,918
def set_argument ( bound_args , address , value ) : if address . kind == ArgumentKind . regular : bound_args . arguments [ address . name ] = value return if address . kind == ArgumentKind . variadic : if address . name not in bound_args . arguments : bound_args . arguments [ address . name ] = [ ] n_args = len ( bound...
Taking a bound_args object and an |ArgumentAddress| and a value sets the value pointed to by the address to value .
30,919
def format_address ( address ) : if address . kind == ArgumentKind . regular : return address . name return "{0}[{1}]" . format ( address . name , address . key )
Formats an ArgumentAddress for human reading .
30,920
def run_parallel ( workflow , n_threads ) : scheduler = Scheduler ( ) threaded_worker = Queue ( ) >> thread_pool ( * repeat ( worker , n_threads ) ) return scheduler . run ( threaded_worker , get_workflow ( workflow ) )
Run a workflow in parallel threads .
30,921
def thread_counter ( finalize ) : n_threads = 0 lock = threading . Lock ( ) def target_modifier ( target ) : @ functools . wraps ( target ) def modified_target ( * args , ** kwargs ) : nonlocal n_threads , lock with lock : n_threads += 1 return_value = target ( * args , ** kwargs ) with lock : n_threads -= 1 if n_threa...
Modifies a thread target function such that the number of active threads is counted . If the count reaches zero a finalizer is called .
30,922
def thread_pool ( * workers , results = None , end_of_queue = EndOfQueue ) : if results is None : results = Queue ( end_of_queue = end_of_queue ) count = thread_counter ( results . close ) @ pull def thread_pool_results ( source ) : for worker in workers : t = threading . Thread ( target = count ( patch ) , args = ( pu...
Returns a |pull| object call it r starting a thread for each given worker . Each thread pulls from the source that r is connected to and the returned results are pushed to a |Queue| . r yields from the other end of the same |Queue| .
30,923
def run ( wf , * , display , n_threads = 1 ) : worker = dynamic_exclusion_worker ( display , n_threads ) return noodles . Scheduler ( error_handler = display . error_handler ) . run ( worker , get_workflow ( wf ) )
Run the workflow using the dynamic - exclusion worker .
30,924
def create_object ( cls , members ) : obj = cls . __new__ ( cls ) obj . __dict__ = members return obj
Promise an object of class cls with content members .
30,925
def lift ( obj , memo = None ) : if memo is None : memo = { } if isinstance ( obj , ( PromisedObject , str , int , float , complex ) ) : return obj if id ( obj ) in memo : return memo [ id ( obj ) ] if hasattr ( obj , '__lift__' ) : rv = obj . __lift__ ( memo ) memo [ id ( obj ) ] = rv return rv actions = { list : ( la...
Make a promise out of object obj where obj may contain promises internally .
30,926
def branch ( * sinks_ ) : @ pull def junction ( source ) : sinks = [ s ( ) for s in sinks_ ] for msg in source ( ) : for s in sinks : s . send ( msg ) yield msg return junction
The |branch| decorator creates a |pull| object that pulls from a single source and then sends to all the sinks given . After all the sinks received the message it is yielded .
30,927
def broadcast ( * sinks_ ) : @ push def bc ( ) : sinks = [ s ( ) for s in sinks_ ] while True : msg = yield for s in sinks : s . send ( msg ) return bc
The |broadcast| decorator creates a |push| object that receives a message by yield and then sends this message on to all the given sinks .
30,928
def push_from ( iterable ) : def p ( sink ) : sink = sink ( ) for x in iterable : sink . send ( x ) return push ( p , dont_wrap = True )
Creates a |push| object from an iterable . The resulting function is not a coroutine but can be chained to another |push| .
30,929
def patch ( source , sink ) : sink = sink ( ) for v in source ( ) : try : sink . send ( v ) except StopIteration : return
Create a direct link between a source and a sink .
30,930
def conditional ( b : bool , branch_true : Any , branch_false : Any = None ) -> Any : return schedule_branches ( b , quote ( branch_true ) , quote ( branch_false ) )
Control statement to follow a branch in workflow . Equivalent to the if statement in standard Python .
30,931
def schedule_branches ( b : bool , quoted_true , quoted_false ) : if b : return unquote ( quoted_true ) else : return unquote ( quoted_false )
Helper function to choose which workflow to execute based on the boolean b .
30,932
def array_sha256 ( a ) : dtype = str ( a . dtype ) . encode ( ) shape = numpy . array ( a . shape ) sha = hashlib . sha256 ( ) sha . update ( dtype ) sha . update ( shape ) sha . update ( a . tobytes ( ) ) return sha . hexdigest ( )
Create a SHA256 hash from a Numpy array .
30,933
def arrays_to_file ( file_prefix = None ) : return Registry ( types = { numpy . ndarray : SerNumpyArrayToFile ( file_prefix ) } , hooks = { '<ufunc>' : SerUFunc ( ) } , hook_fn = _numpy_hook )
Returns a serialisation registry for serialising NumPy data and as well as any UFuncs that have no normal way of retrieving qualified names .
30,934
def arrays_to_string ( file_prefix = None ) : return Registry ( types = { numpy . ndarray : SerNumpyArray ( ) , numpy . floating : SerNumpyScalar ( ) } , hooks = { '<ufunc>' : SerUFunc ( ) } , hook_fn = _numpy_hook )
Returns registry for serialising arrays as a Base64 string .
30,935
def arrays_to_hdf5 ( filename = "cache.hdf5" ) : return Registry ( types = { numpy . ndarray : SerNumpyArrayToHDF5 ( filename , "cache.lock" ) } , hooks = { '<ufunc>' : SerUFunc ( ) } , hook_fn = _numpy_hook )
Returns registry for serialising arrays to a HDF5 reference .
30,936
def run_xenon_simple ( workflow , machine , worker_config ) : scheduler = Scheduler ( ) return scheduler . run ( xenon_interactive_worker ( machine , worker_config ) , get_workflow ( workflow ) )
Run a workflow using a single Xenon remote worker .
30,937
def run_xenon ( workflow , * , machine , worker_config , n_processes , deref = False , verbose = False ) : dynamic_pool = DynamicPool ( machine ) for i in range ( n_processes ) : cfg = copy ( worker_config ) cfg . name = 'xenon-{0:02}' . format ( i ) dynamic_pool . add_xenon_worker ( cfg ) job_keeper = JobKeeper ( ) S ...
Run the workflow using a number of online Xenon workers .
30,938
def pass_job ( db : JobDB , result_queue : Queue , always_cache = False ) : @ pull def pass_job_stream ( job_source ) : result_sink = result_queue . sink ( ) for message in job_source ( ) : if message is EndOfQueue : return key , job = message if always_cache or ( 'store' in job . hints ) : status , retrieved_result = ...
Create a pull stream that receives jobs and passes them on to the database . If the job already has a result that result is pushed onto the result_queue .
30,939
def pass_result ( db : JobDB , always_cache = False ) : @ pull def pass_result_stream ( worker_source ) : for result in worker_source ( ) : if result is EndOfQueue : return attached = db . store_result_in_db ( result , always_cache = always_cache ) yield result yield from ( ResultMessage ( key , 'attached' , result . v...
Creates a pull stream receiving results storing them in the database then sending them on . At this stage the database may return a list of attached jobs which also need to be sent on to the scheduler .
30,940
def run_parallel ( workflow , * , n_threads , registry , db_file , echo_log = True , always_cache = False ) : if echo_log : logging . getLogger ( 'noodles' ) . setLevel ( logging . DEBUG ) logging . debug ( "--- start log ---" ) with JobDB ( db_file , registry ) as db : job_queue = Queue ( ) result_queue = Queue ( ) jo...
Run a workflow in parallel threads storing results in a Sqlite3 database .
30,941
def is_unwrapped ( f ) : try : g = look_up ( object_name ( f ) ) return g != f and unwrap ( g ) == f except ( AttributeError , TypeError , ImportError ) : return False
If f was imported and then unwrapped this function might return True .
30,942
def inverse_deep_map ( f , root ) : if isinstance ( root , dict ) : r = { k : inverse_deep_map ( f , v ) for k , v in root . items ( ) } elif isinstance ( root , list ) : r = [ inverse_deep_map ( f , v ) for v in root ] else : r = root return f ( r )
Sibling to |deep_map| . Recursively maps objects in a nested structure of list and dict objects . Where |deep_map| starts at the top |inverse_deep_map| starts at the bottom . First if root is a list or dict its contents are |inverse_deep_map|ed . Then at the end the entire object is passed through f .
30,943
def decode ( self , rec , deref = False ) : if not isinstance ( rec , dict ) : return rec if '_noodles' not in rec : return rec if rec . get ( 'ref' , False ) and not deref : return RefObject ( rec ) typename = rec [ 'type' ] classname = rec [ 'class' ] try : cls = look_up ( classname ) if classname else None except ( ...
Decode a record to return an object that could be considered equivalent to the original .
30,944
def to_json ( self , obj , host = None , indent = None ) : if indent : return json . dumps ( deep_map ( lambda o : self . encode ( o , host ) , obj ) , indent = indent ) else : return json . dumps ( deep_map ( lambda o : self . encode ( o , host ) , obj ) )
Recursively encode obj and convert it to a JSON string .
30,945
def from_json ( self , data , deref = False ) : return self . deep_decode ( json . loads ( data ) , deref )
Decode the string from JSON to return the original object ( if deref is true . Uses the json . loads function with self . decode as object_hook .
30,946
def dereference ( self , data , host = None ) : return self . deep_decode ( self . deep_encode ( data , host ) , deref = True )
Dereferences RefObjects stuck in the hierarchy . This is a bit of an ugly hack .
30,947
def run_single ( workflow , * , registry , db_file , always_cache = True ) : with JobDB ( db_file , registry ) as db : job_logger = make_logger ( "worker" , push_map , db ) result_logger = make_logger ( "worker" , pull_map , db ) @ pull def pass_job ( source ) : for msg in source ( ) : key , job = msg status , retrieve...
Run workflow in a single thread storing results in a Sqlite3 database .
30,948
def scheduler ( self ) : if self . _scheduler is None : self . _scheduler = xenon . Scheduler . create ( ** self . scheduler_args ) return self . _scheduler
Returns the scheduler object .
30,949
def file_system ( self ) : if self . _file_system is None : self . _file_system = self . scheduler . get_file_system ( ) return self . _file_system
Gets the filesystem corresponding to the open scheduler .
30,950
def registry ( ) : return Registry ( types = { dict : SerDict ( ) , tuple : SerSequence ( tuple ) , set : SerSequence ( set ) , bytes : SerBytes ( ) , slice : SerSlice ( ) , complex : SerByMembers ( complex , [ 'real' , 'imag' ] ) , Reasonable : SerReasonableObject ( Reasonable ) , ArgumentKind : SerEnum ( ArgumentKind...
Returns the Noodles base serialisation registry .
30,951
def scheduled_function ( f , hints = None ) : if hints is None : hints = { } if 'version' not in hints : try : source_bytes = inspect . getsource ( f ) . encode ( ) except Exception : pass else : m = hashlib . md5 ( ) m . update ( source_bytes ) hints [ 'version' ] = m . hexdigest ( ) @ wraps ( f ) def wrapped ( * args...
The Noodles schedule function decorator .
30,952
def worker ( job ) : if job is EndOfQueue : return if not isinstance ( job , JobMessage ) : print ( "Warning: Job should be communicated using `JobMessage`." , file = sys . stderr ) key , node = job return run_job ( key , node )
Primary |worker| coroutine . This is a |pull| object that pulls jobs from a source and yield evaluated results .
30,953
def run_job ( key , node ) : try : result = node . apply ( ) return ResultMessage ( key , 'done' , result , None ) except Exception as exc : return ResultMessage ( key , 'error' , None , exc )
Run a job . This applies the function node and returns a |ResultMessage| when complete . If an exception is raised in the job the |ResultMessage| will have error status .
30,954
def hybrid_coroutine_worker ( selector , workers ) : jobs = Queue ( ) worker_source = { } worker_sink = { } for k , w in workers . items ( ) : worker_source [ k ] , worker_sink [ k ] = w . setup ( ) def get_result ( ) : source = jobs . source ( ) for msg in source : key , job = msg worker = selector ( job ) if worker i...
Runs a set of workers all of them in the main thread . This runner is here for testing purposes .
30,955
def hybrid_threaded_worker ( selector , workers ) : result_queue = Queue ( ) job_sink = { k : w . sink ( ) for k , w in workers . items ( ) } @ push def dispatch_job ( ) : default_sink = result_queue . sink ( ) while True : msg = yield if msg is EndOfQueue : for k in workers . keys ( ) : try : job_sink [ k ] . send ( E...
Runs a set of workers each in a separate thread .
30,956
def run_hybrid ( wf , selector , workers ) : worker = hybrid_threaded_worker ( selector , workers ) return Scheduler ( ) . run ( worker , get_workflow ( wf ) )
Returns the result of evaluating the workflow ; runs through several supplied workers in as many threads .
30,957
def prov_key ( job_msg , extra = None ) : m = hashlib . md5 ( ) update_object_hash ( m , job_msg [ 'data' ] [ 'function' ] ) update_object_hash ( m , job_msg [ 'data' ] [ 'arguments' ] ) if 'version' in job_msg [ 'data' ] [ 'hints' ] : update_object_hash ( m , job_msg [ 'data' ] [ 'hints' ] [ 'version' ] ) if extra is ...
Retrieves a MD5 sum from a function call . This takes into account the name of the function the arguments and possibly a version number of the function if that is given in the hints . This version can also be auto - generated by generating an MD5 hash from the function source . However the source - code may not always ...
30,958
def JSONObjectReader ( registry , fi , deref = False ) : for line in fi : yield registry . from_json ( line , deref = deref )
Stream objects from a JSON file .
30,959
def JSONObjectWriter ( registry , fo , host = None ) : while True : obj = yield try : print ( registry . to_json ( obj , host = host ) , file = fo , flush = True ) except BrokenPipeError : return
Sink ; writes object as JSON to a file .
30,960
def matrix ( mat ) : import ROOT if isinstance ( mat , ( ROOT . TMatrixD , ROOT . TMatrixDSym ) ) : return _librootnumpy . matrix_d ( ROOT . AsCObject ( mat ) ) elif isinstance ( mat , ( ROOT . TMatrixF , ROOT . TMatrixFSym ) ) : return _librootnumpy . matrix_f ( ROOT . AsCObject ( mat ) ) raise TypeError ( "unable to ...
Convert a ROOT TMatrix into a NumPy matrix .
30,961
def fill_graph ( graph , array ) : import ROOT array = np . asarray ( array , dtype = np . double ) if isinstance ( graph , ROOT . TGraph ) : if array . ndim != 2 : raise ValueError ( "array must be 2-dimensional" ) if array . shape [ 1 ] != 2 : raise ValueError ( "length of the second dimension must equal " "the dimen...
Fill a ROOT graph with a NumPy array .
30,962
def random_sample ( obj , n_samples , seed = None ) : import ROOT if n_samples <= 0 : raise ValueError ( "n_samples must be greater than 0" ) if seed is not None : if seed < 0 : raise ValueError ( "seed must be positive or 0" ) ROOT . gRandom . SetSeed ( seed ) if isinstance ( obj , ROOT . TF1 ) : if isinstance ( obj ,...
Create a random array by sampling a ROOT function or histogram .
30,963
def _glob ( filenames ) : if isinstance ( filenames , string_types ) : filenames = [ filenames ] matches = [ ] for name in filenames : matched_names = glob ( name ) if not matched_names : matches . append ( name ) else : matches . extend ( matched_names ) return matches
Glob a filename or list of filenames but always return the original string if the glob didn t match anything so URLs for remote file access are not clobbered .
30,964
def list_structures ( filename , treename = None ) : warnings . warn ( "list_structures is deprecated and will be " "removed in 5.0.0." , DeprecationWarning ) return _librootnumpy . list_structures ( filename , treename )
Get a dictionary mapping branch names to leaf structures .
30,965
def root2array ( filenames , treename = None , branches = None , selection = None , object_selection = None , start = None , stop = None , step = None , include_weight = False , weight_name = 'weight' , cache_size = - 1 , warn_missing_tree = False ) : filenames = _glob ( filenames ) if not filenames : raise ValueError ...
Convert trees in ROOT files into a numpy structured array .
30,966
def tree2array ( tree , branches = None , selection = None , object_selection = None , start = None , stop = None , step = None , include_weight = False , weight_name = 'weight' , cache_size = - 1 ) : import ROOT if not isinstance ( tree , ROOT . TTree ) : raise TypeError ( "tree must be a ROOT.TTree" ) cobj = ROOT . A...
Convert a tree into a numpy structured array .
30,967
def array2tree ( arr , name = 'tree' , tree = None ) : import ROOT if tree is not None : if not isinstance ( tree , ROOT . TTree ) : raise TypeError ( "tree must be a ROOT.TTree" ) incobj = ROOT . AsCObject ( tree ) else : incobj = None cobj = _librootnumpy . array2tree_toCObj ( arr , name = name , tree = incobj ) retu...
Convert a numpy structured array into a ROOT TTree .
30,968
def array2root ( arr , filename , treename = 'tree' , mode = 'update' ) : _librootnumpy . array2root ( arr , filename , treename , mode )
Convert a numpy array into a ROOT TTree and save it in a ROOT TFile .
30,969
def fill_hist ( hist , array , weights = None , return_indices = False ) : import ROOT array = np . asarray ( array , dtype = np . double ) if weights is not None : weights = np . asarray ( weights , dtype = np . double ) if weights . shape [ 0 ] != array . shape [ 0 ] : raise ValueError ( "array and weights must have ...
Fill a ROOT histogram with a NumPy array .
30,970
def fill_profile ( profile , array , weights = None , return_indices = False ) : import ROOT array = np . asarray ( array , dtype = np . double ) if array . ndim != 2 : raise ValueError ( "array must be 2-dimensional" ) if array . shape [ 1 ] != profile . GetDimension ( ) + 1 : raise ValueError ( "there must be one mor...
Fill a ROOT profile with a NumPy array .
30,971
def array2hist ( array , hist , errors = None ) : import ROOT if isinstance ( hist , ROOT . TH3 ) : shape = ( hist . GetNbinsX ( ) + 2 , hist . GetNbinsY ( ) + 2 , hist . GetNbinsZ ( ) + 2 ) elif isinstance ( hist , ROOT . TH2 ) : shape = ( hist . GetNbinsX ( ) + 2 , hist . GetNbinsY ( ) + 2 ) elif isinstance ( hist , ...
Convert a NumPy array into a ROOT histogram
30,972
def extract_docstring ( filename ) : lines = file ( filename ) . readlines ( ) start_row = 0 if lines [ 0 ] . startswith ( '#!' ) : lines . pop ( 0 ) start_row = 1 docstring = '' first_par = '' tokens = tokenize . generate_tokens ( iter ( lines ) . next ) for tok_type , tok_content , _ , ( erow , _ ) , _ in tokens : to...
Extract a module - level docstring if any
30,973
def generate_example_rst ( app ) : root_dir = os . path . join ( app . builder . srcdir , 'auto_examples' ) example_dir = os . path . abspath ( app . builder . srcdir + '/../' + 'examples' ) try : plot_gallery = eval ( app . builder . config . plot_gallery ) except TypeError : plot_gallery = bool ( app . builder . conf...
Generate the list of examples as well as the contents of examples .
30,974
def array ( arr , copy = True ) : import ROOT if isinstance ( arr , ROOT . TArrayD ) : arr = _librootnumpy . array_d ( ROOT . AsCObject ( arr ) ) elif isinstance ( arr , ROOT . TArrayF ) : arr = _librootnumpy . array_f ( ROOT . AsCObject ( arr ) ) elif isinstance ( arr , ROOT . TArrayL ) : arr = _librootnumpy . array_l...
Convert a ROOT TArray into a NumPy array .
30,975
def stretch ( arr , fields = None , return_indices = False ) : dtype = [ ] len_array = None flatten = False if fields is None : fields = arr . dtype . names elif isinstance ( fields , string_types ) : fields = [ fields ] flatten = True for field in fields : dt = arr . dtype [ field ] if dt == 'O' or len ( dt . shape ) ...
Stretch an array .
30,976
def dup_idx ( arr ) : _ , b = np . unique ( arr , return_inverse = True ) return np . nonzero ( np . logical_or . reduce ( b [ : , np . newaxis ] == np . nonzero ( np . bincount ( b ) > 1 ) , axis = 1 ) ) [ 0 ]
Return the indices of all duplicated array elements .
30,977
def blockwise_inner_join ( data , left , foreign_key , right , force_repeat = None , foreign_key_name = None ) : if isinstance ( foreign_key , string_types ) : foreign_key = data [ foreign_key ] return _blockwise_inner_join ( data , left , foreign_key , right , force_repeat , foreign_key_name )
Perform a blockwise inner join .
30,978
def executemany ( self , query , args ) : if not args : return m = RE_INSERT_VALUES . match ( query ) if m : q_prefix = m . group ( 1 ) q_values = m . group ( 2 ) . rstrip ( ) q_postfix = m . group ( 3 ) or '' assert q_values [ 0 ] == '(' and q_values [ - 1 ] == ')' yield self . _do_execute_many ( q_prefix , q_values ,...
Run several data against one query
30,979
def Binary ( x ) : if isinstance ( x , text_type ) and not ( JYTHON or IRONPYTHON ) : return x . encode ( ) return bytes ( x )
Return x as a binary type .
30,980
def convert_mysql_timestamp ( timestamp ) : if timestamp [ 4 ] == '-' : return convert_datetime ( timestamp ) timestamp += "0" * ( 14 - len ( timestamp ) ) year , month , day , hour , minute , second = int ( timestamp [ : 4 ] ) , int ( timestamp [ 4 : 6 ] ) , int ( timestamp [ 6 : 8 ] ) , int ( timestamp [ 8 : 10 ] ) ,...
Convert a MySQL TIMESTAMP to a Timestamp object .
30,981
def close ( self ) : stream = self . _stream if stream is None : return self . _stream = None stream . close ( )
Close the socket without sending quit message .
30,982
def close_async ( self ) : if self . _stream is None or self . _stream . closed ( ) : self . _stream = None return send_data = struct . pack ( '<i' , 1 ) + int2byte ( COMMAND . COM_QUIT ) yield self . _stream . write ( send_data ) self . close ( )
Send the quit message and close the socket
30,983
def select_db ( self , db ) : yield self . _execute_command ( COMMAND . COM_INIT_DB , db ) yield self . _read_ok_packet ( )
Set current db
30,984
def execute ( self , query , params = None , cursor = None ) : conn = yield self . _get_conn ( ) try : cur = conn . cursor ( cursor ) yield cur . execute ( query , params ) yield cur . close ( ) except : self . _close_conn ( conn ) raise else : self . _put_conn ( conn ) raise Return ( cur )
Execute query in pool .
30,985
def get_queryset ( self ) : self . z , self . x , self . y = self . _parse_args ( ) nw = self . tile_coord ( self . x , self . y , self . z ) se = self . tile_coord ( self . x + 1 , self . y + 1 , self . z ) bbox = Polygon ( ( nw , ( se [ 0 ] , nw [ 1 ] ) , se , ( nw [ 0 ] , se [ 1 ] ) , nw ) ) qs = super ( TiledGeoJSO...
Inspired by Glen Roberton s django - geojson - tiles view
30,986
def json_encoder_with_precision ( precision , JSONEncoderClass ) : needs_class_hack = not hasattr ( json . encoder , 'FLOAT_REPR' ) try : if precision is not None : def float_repr ( o ) : return format ( o , '.%sf' % precision ) if not needs_class_hack : original_float_repr = json . encoder . FLOAT_REPR json . encoder ...
Context manager to set float precision during json encoding
30,987
def datetime_to_utc ( ts ) : if not isinstance ( ts , datetime . datetime ) : msg = '<%s> object' % type ( ts ) raise InvalidDateError ( date = msg ) if not ts . tzinfo : ts = ts . replace ( tzinfo = dateutil . tz . tzutc ( ) ) try : ts = ts . astimezone ( dateutil . tz . tzutc ( ) ) except ValueError : logger . warnin...
Convert a timestamp to UTC + 0 timezone .
30,988
def unixtime_to_datetime ( ut ) : try : dt = datetime . datetime . utcfromtimestamp ( ut ) dt = dt . replace ( tzinfo = dateutil . tz . tzutc ( ) ) return dt except Exception : raise InvalidDateError ( date = str ( ut ) )
Convert a unixtime timestamp to a datetime object .
30,989
def inspect_signature_parameters ( callable_ , excluded = None ) : if not excluded : excluded = ( ) signature = inspect . signature ( callable_ ) params = [ v for p , v in signature . parameters . items ( ) if p not in excluded ] return params
Get the parameters of a callable .
30,990
def find_signature_parameters ( callable_ , candidates , excluded = ( 'self' , 'cls' ) ) : signature_params = inspect_signature_parameters ( callable_ , excluded = excluded ) exec_params = { } add_all = False for param in signature_params : name = param . name if str ( param ) . startswith ( '*' ) : add_all = True elif...
Find on a set of candidates the parameters needed to execute a callable .
30,991
def find_class_properties ( cls ) : candidates = inspect . getmembers ( cls , inspect . isdatadescriptor ) result = [ ( name , value ) for name , value in candidates if isinstance ( value , property ) ] return result
Find property members in a class .
30,992
def coroutine ( func ) : def __start ( * args , ** kwargs ) : __cr = func ( * args , ** kwargs ) next ( __cr ) return __cr return __start
Basic decorator to implement the coroutine pattern .
30,993
def _endCodeIfNeeded ( line , inCodeBlock ) : assert isinstance ( line , str ) if inCodeBlock : line = '# @endcode{0}{1}' . format ( linesep , line . rstrip ( ) ) inCodeBlock = False return line , inCodeBlock
Simple routine to append end code marker if needed .
30,994
def _checkIfCode ( self , inCodeBlockObj ) : while True : line , lines , lineNum = ( yield ) testLineNum = 1 currentLineNum = 0 testLine = line . strip ( ) lineOfCode = None while lineOfCode is None : match = AstWalker . __errorLineRE . match ( testLine ) if not testLine or testLine == '...' or match : line , lines , l...
Checks whether or not a given line appears to be Python code .
30,995
def __writeDocstring ( self ) : while True : firstLineNum , lastLineNum , lines = ( yield ) newDocstringLen = lastLineNum - firstLineNum + 1 while len ( lines ) < newDocstringLen : lines . append ( '' ) self . docLines [ firstLineNum : lastLineNum + 1 ] = lines
Runs eternally dumping out docstring line batches as they get fed in .
30,996
def _checkMemberName ( name ) : assert isinstance ( name , str ) restrictionLevel = None if not name . endswith ( '__' ) : if name . startswith ( '__' ) : restrictionLevel = 'private' elif name . startswith ( '_' ) : restrictionLevel = 'protected' return restrictionLevel
See if a member name indicates that it should be private .
30,997
def _processMembers ( self , node , contextTag ) : restrictionLevel = self . _checkMemberName ( node . name ) if restrictionLevel : workTag = '{0}{1}# @{2}' . format ( contextTag , linesep , restrictionLevel ) else : workTag = contextTag return workTag
Mark up members if they should be private .
30,998
def visit ( self , node , ** kwargs ) : containingNodes = kwargs . get ( 'containingNodes' , [ ] ) method = 'visit_' + node . __class__ . __name__ visitor = getattr ( self , method , self . generic_visit ) return visitor ( node , containingNodes = containingNodes )
Visit a node and extract useful information from it .
30,999
def _getFullPathName ( self , containingNodes ) : assert isinstance ( containingNodes , list ) return [ ( self . options . fullPathNamespace , 'module' ) ] + containingNodes
Returns the full node hierarchy rooted at module name .