idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
239,600 | def setBottomRight ( self , loc ) : offset = self . getBottomRight ( ) . getOffset ( loc ) return self . setLocation ( self . getTopLeft ( ) . offset ( offset ) ) | Move this region so its bottom right corner is on loc |
239,601 | def setSize ( self , w , h ) : self . setW ( w ) self . setH ( h ) return self | Sets the new size of the region |
239,602 | def saveScreenCapture ( self , path = None , name = None ) : bitmap = self . getBitmap ( ) target_file = None if path is None and name is None : _ , target_file = tempfile . mkstemp ( ".png" ) elif name is None : _ , tpath = tempfile . mkstemp ( ".png" ) target_file = os . path . join ( path , tfile ) else : target_fil... | Saves the region s bitmap |
239,603 | def saveLastScreenImage ( self ) : bitmap = self . getLastScreenImage ( ) _ , target_file = tempfile . mkstemp ( ".png" ) cv2 . imwrite ( target_file , bitmap ) | Saves the last image taken on this region s screen to a temporary file |
239,604 | def onChange ( self , min_changed_pixels = None , handler = None ) : if isinstance ( min_changed_pixels , int ) and ( callable ( handler ) or handler is None ) : return self . _observer . register_event ( "CHANGE" , pattern = ( min_changed_pixels , self . getBitmap ( ) ) , handler = handler ) elif ( callable ( min_chan... | Registers an event to call handler when at least min_changed_pixels change in this region . |
239,605 | def isChanged ( self , min_changed_pixels , screen_state ) : r = self . clipRegionToScreen ( ) current_state = r . getBitmap ( ) diff = numpy . subtract ( current_state , screen_state ) return ( numpy . count_nonzero ( diff ) >= min_changed_pixels ) | Returns true if at least min_changed_pixels are different between screen_state and the current state . |
239,606 | def stopObserver ( self ) : self . _observer . isStopped = True self . _observer . isRunning = False | Stops this region s observer loop . |
239,607 | def getEvents ( self ) : caught_events = self . _observer . caught_events self . _observer . caught_events = [ ] for event in caught_events : self . _observer . activate_event ( event [ "name" ] ) return caught_events | Returns a list of all events that have occurred . |
239,608 | def getEvent ( self , name ) : to_return = None for event in self . _observer . caught_events : if event [ "name" ] == name : to_return = event break if to_return : self . _observer . caught_events . remove ( to_return ) self . _observer . activate_event ( to_return [ "name" ] ) return to_return | Returns the named event . |
239,609 | def setFindFailedResponse ( self , response ) : valid_responses = ( "ABORT" , "SKIP" , "PROMPT" , "RETRY" ) if response not in valid_responses : raise ValueError ( "Invalid response - expected one of ({})" . format ( ", " . join ( valid_responses ) ) ) self . _findFailedResponse = response | Set the response to a FindFailed exception in this region . Can be ABORT SKIP PROMPT or RETRY . |
239,610 | def setThrowException ( self , setting ) : if setting : self . _throwException = True self . _findFailedResponse = "ABORT" else : self . _throwException = False self . _findFailedResponse = "SKIP" | Defines whether an exception should be thrown for FindFailed operations . |
239,611 | def register_event ( self , event_type , pattern , handler ) : if event_type not in self . _supported_events : raise ValueError ( "Unsupported event type {}" . format ( event_type ) ) if event_type != "CHANGE" and not isinstance ( pattern , Pattern ) and not isinstance ( pattern , basestring ) : raise ValueError ( "Exp... | When event_type is observed for pattern triggers handler . |
239,612 | def capture ( self , * args ) : if len ( args ) == 0 : region = self elif isinstance ( args [ 0 ] , Region ) : region = args [ 0 ] elif isinstance ( args [ 0 ] , tuple ) : region = Region ( * args [ 0 ] ) elif isinstance ( args [ 0 ] , basestring ) : raise NotImplementedError ( "Interactive capture mode not defined" ) ... | Captures the region as an image |
239,613 | def showMonitors ( cls ) : Debug . info ( "*** monitor configuration [ {} Screen(s)] ***" . format ( cls . getNumberScreens ( ) ) ) Debug . info ( "*** Primary is Screen {}" . format ( cls . primaryScreen ) ) for index , screen in enumerate ( PlatformManager . getScreenDetails ( ) ) : Debug . info ( "Screen {}: ({}, {}... | Prints debug information about currently detected screens |
239,614 | def resetMonitors ( self ) : Debug . error ( "*** BE AWARE: experimental - might not work ***" ) Debug . error ( "Re-evaluation of the monitor setup has been requested" ) Debug . error ( "... Current Region/Screen objects might not be valid any longer" ) Debug . error ( "... Use existing Region/Screen objects only if y... | Recalculates screen based on changed monitor setup |
239,615 | def newRegion ( self , loc , width , height ) : return Region . create ( self . getTopLeft ( ) . offset ( loc ) , width , height ) | Creates a new region on the current screen at the specified offset with the specified width and height . |
239,616 | def history ( self , message ) : if Settings . ActionLogs : self . _write_log ( "action" , Settings . LogTime , message ) | Records an Action - level log message |
239,617 | def error ( self , message ) : if Settings . ErrorLogs : self . _write_log ( "error" , Settings . LogTime , message ) | Records an Error - level log message |
239,618 | def info ( self , message ) : if Settings . InfoLogs : self . _write_log ( "info" , Settings . LogTime , message ) | Records an Info - level log message |
239,619 | def on ( self , level ) : if isinstance ( level , int ) and level >= 0 and level <= 3 : self . _debug_level = level | Turns on all debugging messages up to the specified level |
239,620 | def setLogFile ( self , filepath ) : if filepath is None : self . _log_file = None return parsed_path = os . path . abspath ( filepath ) if os . path . isdir ( os . path . dirname ( parsed_path ) ) and not os . path . isdir ( parsed_path ) : self . _log_file = parsed_path else : raise IOError ( "File not found: " + fil... | Defines the file to which output log messages should be sent . |
239,621 | def _write_log ( self , log_type , log_time , message ) : timestamp = datetime . datetime . now ( ) . strftime ( " %Y-%m-%d %H:%M:%S" ) log_entry = "[{}{}] {}" . format ( log_type , timestamp if log_time else "" , message ) if self . _logger and callable ( getattr ( self . _logger , self . _logger_methods [ log_type ] ... | Private method to abstract log writing for different types of logs |
239,622 | def addImagePath ( new_path ) : if os . path . exists ( new_path ) : Settings . ImagePaths . append ( new_path ) elif "http://" in new_path or "https://" in new_path : request = requests . get ( new_path ) if request . status_code < 400 : Settings . ImagePaths . append ( new_path ) else : raise OSError ( "Unable to con... | Convenience function . Adds a path to the list of paths to search for images . |
239,623 | def unzip ( from_file , to_folder ) : with ZipFile ( os . path . abspath ( from_file ) , 'r' ) as to_unzip : to_unzip . extractall ( os . path . abspath ( to_folder ) ) | Convenience function . |
239,624 | def popup ( text , title = "Lackey Info" ) : root = tk . Tk ( ) root . withdraw ( ) tkMessageBox . showinfo ( title , text ) | Creates an info dialog with the specified text . |
239,625 | def popError ( text , title = "Lackey Error" ) : root = tk . Tk ( ) root . withdraw ( ) tkMessageBox . showerror ( title , text ) | Creates an error dialog with the specified text . |
239,626 | def popAsk ( text , title = "Lackey Decision" ) : root = tk . Tk ( ) root . withdraw ( ) return tkMessageBox . askyesno ( title , text ) | Creates a yes - no dialog with the specified text . |
239,627 | def input ( msg = "" , default = "" , title = "Lackey Input" , hidden = False ) : root = tk . Tk ( ) input_text = tk . StringVar ( ) input_text . set ( default ) PopupInput ( root , msg , title , hidden , input_text ) root . focus_force ( ) root . mainloop ( ) return str ( input_text . get ( ) ) | Creates an input dialog with the specified message and default text . |
239,628 | def inputText ( message = "" , title = "Lackey Input" , lines = 9 , width = 20 , text = "" ) : root = tk . Tk ( ) input_text = tk . StringVar ( ) input_text . set ( text ) PopupTextarea ( root , message , title , lines , width , input_text ) root . focus_force ( ) root . mainloop ( ) return str ( input_text . get ( ) ) | Creates a textarea dialog with the specified message and default text . |
239,629 | def select ( message = "" , title = "Lackey Input" , options = None , default = None ) : if options is None or len ( options ) == 0 : return "" if default is None : default = options [ 0 ] if default not in options : raise ValueError ( "<<default>> not in options[]" ) root = tk . Tk ( ) input_text = tk . StringVar ( ) ... | Creates a dropdown selection dialog with the specified message and options |
239,630 | def popFile ( title = "Lackey Open File" ) : root = tk . Tk ( ) root . withdraw ( ) return str ( tkFileDialog . askopenfilename ( title = title ) ) | Creates a file selection dialog with the specified message and options . |
239,631 | def setLocation ( self , x , y ) : self . x = int ( x ) self . y = int ( y ) return self | Set the location of this object to the specified coordinates . |
239,632 | def offset ( self , dx , dy ) : return Location ( self . x + dx , self . y + dy ) | Get a new location which is dx and dy pixels away horizontally and vertically from the current location . |
239,633 | def getOffset ( self , loc ) : return Location ( loc . x - self . x , loc . y - self . y ) | Returns the offset between the given point and this point |
239,634 | def copyTo ( self , screen ) : from . RegionMatching import Screen if not isinstance ( screen , Screen ) : screen = RegionMatching . Screen ( screen ) return screen . getTopLeft ( ) . offset ( self . getScreen ( ) . getTopLeft ( ) . getOffset ( self ) ) | Creates a new point with the same offset on the target screen as this point has on the current screen |
239,635 | def focusedWindow ( cls ) : x , y , w , h = PlatformManager . getWindowRect ( PlatformManager . getForegroundWindow ( ) ) return Region ( x , y , w , h ) | Returns a Region corresponding to whatever window is in the foreground |
239,636 | def getWindow ( self ) : if self . getPID ( ) != - 1 : return PlatformManager . getWindowTitle ( PlatformManager . getWindowByPID ( self . getPID ( ) ) ) else : return "" | Returns the title of the main window of the currently open app . |
239,637 | def window ( self , windowNum = 0 ) : if self . _pid == - 1 : return None x , y , w , h = PlatformManager . getWindowRect ( PlatformManager . getWindowByPID ( self . _pid , windowNum ) ) return Region ( x , y , w , h ) . clipRegionToScreen ( ) | Returns the region corresponding to the specified window of the app . |
239,638 | def isRunning ( self , waitTime = 0 ) : waitUntil = time . time ( ) + waitTime while True : if self . getPID ( ) > 0 : return True else : self . _pid = PlatformManager . getWindowPID ( PlatformManager . getWindowByTitle ( re . escape ( self . _title ) ) ) if time . time ( ) > waitUntil : break else : time . sleep ( sel... | If PID isn t set yet checks if there is a window with the specified title . |
239,639 | def _getVirtualScreenBitmap ( self ) : filenames = [ ] screen_details = self . getScreenDetails ( ) for screen in screen_details : fh , filepath = tempfile . mkstemp ( '.png' ) filenames . append ( filepath ) os . close ( fh ) subprocess . call ( [ 'screencapture' , '-x' ] + filenames ) min_x , min_y , screen_w , scree... | Returns a bitmap of all attached screens |
239,640 | def osCopy ( self ) : k = Keyboard ( ) k . keyDown ( "{CTRL}" ) k . type ( "c" ) k . keyUp ( "{CTRL}" ) | Triggers the OS copy keyboard shortcut |
239,641 | def getForegroundWindow ( self ) : active_app = NSWorkspace . sharedWorkspace ( ) . frontmostApplication ( ) . localizedName ( ) for w in self . _get_window_list ( ) : if "kCGWindowOwnerName" in w and w [ "kCGWindowOwnerName" ] == active_app : return w [ "kCGWindowNumber" ] | Returns a handle to the window in the foreground |
239,642 | def _get_window_list ( self ) : window_list = Quartz . CGWindowListCopyWindowInfo ( Quartz . kCGWindowListExcludeDesktopElements , Quartz . kCGNullWindowID ) return window_list | Returns a dictionary of details about open windows |
239,643 | def getProcessName ( self , pid ) : ps = subprocess . check_output ( [ "ps" , "aux" ] ) . decode ( "ascii" ) processes = ps . split ( "\n" ) cols = len ( processes [ 0 ] . split ( ) ) - 1 for row in processes [ 1 : ] : if row != "" : proc = row . split ( None , cols ) if proc [ 1 ] . strip ( ) == str ( pid ) : return p... | Searches all processes for the given PID then returns the originating command |
239,644 | def moveSpeed ( self , location , seconds = 0.3 ) : self . _lock . acquire ( ) original_location = mouse . get_position ( ) mouse . move ( location . x , location . y , duration = seconds ) if mouse . get_position ( ) == original_location and original_location != location . getTuple ( ) : raise IOError ( ) self . _lock... | Moves cursor to specified Location over seconds . |
239,645 | def click ( self , loc = None , button = mouse . LEFT ) : if loc is not None : self . moveSpeed ( loc ) self . _lock . acquire ( ) mouse . click ( button ) self . _lock . release ( ) | Clicks the specified mouse button . |
239,646 | def buttonDown ( self , button = mouse . LEFT ) : self . _lock . acquire ( ) mouse . press ( button ) self . _lock . release ( ) | Holds down the specified mouse button . |
239,647 | def buttonUp ( self , button = mouse . LEFT ) : self . _lock . acquire ( ) mouse . release ( button ) self . _lock . release ( ) | Releases the specified mouse button . |
239,648 | def wheel ( self , direction , steps ) : self . _lock . acquire ( ) if direction == 1 : wheel_moved = steps elif direction == 0 : wheel_moved = - 1 * steps else : raise ValueError ( "Expected direction to be 1 or 0" ) self . _lock . release ( ) return mouse . wheel ( wheel_moved ) | Clicks the wheel the specified number of steps in the given direction . |
239,649 | def type ( self , text , delay = 0.1 ) : in_special_code = False special_code = "" modifier_held = False modifier_stuck = False modifier_codes = [ ] for i in range ( 0 , len ( text ) ) : if text [ i ] == "{" : in_special_code = True elif in_special_code and ( text [ i ] == "}" or text [ i ] == " " or i == len ( text ) ... | Translates a string into a series of keystrokes . |
239,650 | def findBestMatch ( self , needle , similarity ) : method = cv2 . TM_CCOEFF_NORMED position = None match = cv2 . matchTemplate ( self . haystack , needle , method ) min_val , max_val , min_loc , max_loc = cv2 . minMaxLoc ( match ) if method == cv2 . TM_SQDIFF_NORMED or method == cv2 . TM_SQDIFF : confidence = min_val i... | Find the best match for needle that has a similarity better than or equal to similarity . |
239,651 | def findAllMatches ( self , needle , similarity ) : positions = [ ] method = cv2 . TM_CCOEFF_NORMED match = cv2 . matchTemplate ( self . haystack , self . needle , method ) indices = ( - match ) . argpartition ( 100 , axis = None ) [ : 100 ] unraveled_indices = numpy . array ( numpy . unravel_index ( indices , match . ... | Find all matches for needle with confidence better than or equal to similarity . |
239,652 | def findAllMatches ( self , needle , similarity ) : positions = [ ] while True : best_match = self . findBestMatch ( needle , similarity ) if best_match is None : break positions . append ( best_match ) x , y = best_match [ 0 ] w = needle . shape [ 1 ] h = needle . shape [ 0 ] roi = ( x , y , w , h ) roi_slice = ( slic... | Finds all matches above similarity using a search pyramid to improve efficiency |
239,653 | def _build_pyramid ( self , image , levels ) : pyramid = [ image ] for l in range ( levels - 1 ) : if any ( x < 20 for x in pyramid [ - 1 ] . shape [ : 2 ] ) : break pyramid . append ( cv2 . pyrDown ( pyramid [ - 1 ] ) ) return list ( reversed ( pyramid ) ) | Returns a list of reduced - size images from smallest to original size |
239,654 | def count_weights ( scope = None , exclude = None , graph = None ) : if scope : scope = scope if scope . endswith ( '/' ) else scope + '/' graph = graph or tf . get_default_graph ( ) vars_ = graph . get_collection ( tf . GraphKeys . TRAINABLE_VARIABLES ) if scope : vars_ = [ var for var in vars_ if var . name . startsw... | Count learnable parameters . |
239,655 | def _custom_diag_normal_kl ( lhs , rhs , name = None ) : with tf . name_scope ( name or 'kl_divergence' ) : mean0 = lhs . mean ( ) mean1 = rhs . mean ( ) logstd0 = tf . log ( lhs . stddev ( ) ) logstd1 = tf . log ( rhs . stddev ( ) ) logstd0_2 , logstd1_2 = 2 * logstd0 , 2 * logstd1 return 0.5 * ( tf . reduce_sum ( tf ... | Empirical KL divergence of two normals with diagonal covariance . |
239,656 | def define_simulation_graph ( batch_env , algo_cls , config ) : step = tf . Variable ( 0 , False , dtype = tf . int32 , name = 'global_step' ) is_training = tf . placeholder ( tf . bool , name = 'is_training' ) should_log = tf . placeholder ( tf . bool , name = 'should_log' ) do_report = tf . placeholder ( tf . bool , ... | Define the algorithm and environment interaction . |
239,657 | def define_batch_env ( constructor , num_agents , env_processes ) : with tf . variable_scope ( 'environments' ) : if env_processes : envs = [ tools . wrappers . ExternalProcess ( constructor ) for _ in range ( num_agents ) ] else : envs = [ constructor ( ) for _ in range ( num_agents ) ] batch_env = tools . BatchEnv ( ... | Create environments and apply all desired wrappers . |
239,658 | def define_saver ( exclude = None ) : variables = [ ] exclude = exclude or [ ] exclude = [ re . compile ( regex ) for regex in exclude ] for variable in tf . global_variables ( ) : if any ( regex . match ( variable . name ) for regex in exclude ) : continue variables . append ( variable ) saver = tf . train . Saver ( v... | Create a saver for the variables we want to checkpoint . |
239,659 | def initialize_variables ( sess , saver , logdir , checkpoint = None , resume = None ) : sess . run ( tf . group ( tf . local_variables_initializer ( ) , tf . global_variables_initializer ( ) ) ) if resume and not ( logdir or checkpoint ) : raise ValueError ( 'Need to specify logdir to resume a checkpoint.' ) if logdir... | Initialize or restore variables from a checkpoint if available . |
239,660 | def save_config ( config , logdir = None ) : if logdir : with config . unlocked : config . logdir = logdir message = 'Start a new run and write summaries and checkpoints to {}.' tf . logging . info ( message . format ( config . logdir ) ) tf . gfile . MakeDirs ( config . logdir ) config_path = os . path . join ( config... | Save a new configuration by name . |
239,661 | def load_config ( logdir ) : config_path = logdir and os . path . join ( logdir , 'config.yaml' ) if not config_path or not tf . gfile . Exists ( config_path ) : message = ( 'Cannot resume an existing run since the logging directory does not ' 'contain a configuration file.' ) raise IOError ( message ) with tf . gfile ... | Load a configuration from the log directory . |
239,662 | def set_up_logging ( ) : tf . logging . set_verbosity ( tf . logging . INFO ) logging . getLogger ( 'tensorflow' ) . propagate = False | Configure the TensorFlow logger . |
239,663 | def _define_loop ( graph , eval_steps ) : loop = tools . Loop ( None , graph . step , graph . should_log , graph . do_report , graph . force_reset ) loop . add_phase ( 'eval' , graph . done , graph . score , graph . summary , eval_steps , report_every = eval_steps , log_every = None , checkpoint_every = None , feed = {... | Create and configure an evaluation loop . |
239,664 | def visualize ( logdir , outdir , num_agents , num_episodes , checkpoint = None , env_processes = True ) : config = utility . load_config ( logdir ) with tf . device ( '/cpu:0' ) : batch_env = utility . define_batch_env ( lambda : _create_environment ( config , outdir ) , num_agents , env_processes ) graph = utility . ... | Recover checkpoint and render videos from it . |
239,665 | def main ( _ ) : utility . set_up_logging ( ) if not FLAGS . logdir or not FLAGS . outdir : raise KeyError ( 'You must specify logging and outdirs directories.' ) FLAGS . logdir = os . path . expanduser ( FLAGS . logdir ) FLAGS . outdir = os . path . expanduser ( FLAGS . outdir ) visualize ( FLAGS . logdir , FLAGS . ou... | Load a trained algorithm and render videos . |
239,666 | def reinit_nested_vars ( variables , indices = None ) : if isinstance ( variables , ( tuple , list ) ) : return tf . group ( * [ reinit_nested_vars ( variable , indices ) for variable in variables ] ) if indices is None : return variables . assign ( tf . zeros_like ( variables ) ) else : zeros = tf . zeros ( [ tf . sha... | Reset all variables in a nested tuple to zeros . |
239,667 | def assign_nested_vars ( variables , tensors , indices = None ) : if isinstance ( variables , ( tuple , list ) ) : return tf . group ( * [ assign_nested_vars ( variable , tensor ) for variable , tensor in zip ( variables , tensors ) ] ) if indices is None : return variables . assign ( tensors ) else : return tf . scatt... | Assign tensors to matching nested tuple of variables . |
239,668 | def discounted_return ( reward , length , discount ) : timestep = tf . range ( reward . shape [ 1 ] . value ) mask = tf . cast ( timestep [ None , : ] < length [ : , None ] , tf . float32 ) return_ = tf . reverse ( tf . transpose ( tf . scan ( lambda agg , cur : cur + discount * agg , tf . transpose ( tf . reverse ( ma... | Discounted Monte - Carlo returns . |
239,669 | def fixed_step_return ( reward , value , length , discount , window ) : timestep = tf . range ( reward . shape [ 1 ] . value ) mask = tf . cast ( timestep [ None , : ] < length [ : , None ] , tf . float32 ) return_ = tf . zeros_like ( reward ) for _ in range ( window ) : return_ += reward reward = discount * tf . conca... | N - step discounted return . |
239,670 | def lambda_return ( reward , value , length , discount , lambda_ ) : timestep = tf . range ( reward . shape [ 1 ] . value ) mask = tf . cast ( timestep [ None , : ] < length [ : , None ] , tf . float32 ) sequence = mask * reward + discount * value * ( 1 - lambda_ ) discount = mask * discount * lambda_ sequence = tf . s... | TD - lambda returns . |
239,671 | def lambda_advantage ( reward , value , length , discount , gae_lambda ) : timestep = tf . range ( reward . shape [ 1 ] . value ) mask = tf . cast ( timestep [ None , : ] < length [ : , None ] , tf . float32 ) next_value = tf . concat ( [ value [ : , 1 : ] , tf . zeros_like ( value [ : , - 1 : ] ) ] , 1 ) delta = rewar... | Generalized Advantage Estimation . |
239,672 | def available_gpus ( ) : local_device_protos = device_lib . list_local_devices ( ) return [ x . name for x in local_device_protos if x . device_type == 'GPU' ] | List of GPU device names detected by TensorFlow . |
239,673 | def gradient_summaries ( grad_vars , groups = None , scope = 'gradients' ) : groups = groups or { r'all' : r'.*' } grouped = collections . defaultdict ( list ) for grad , var in grad_vars : if grad is None : continue for name , pattern in groups . items ( ) : if re . match ( pattern , var . name ) : name = re . sub ( p... | Create histogram summaries of the gradient . |
239,674 | def variable_summaries ( vars_ , groups = None , scope = 'weights' ) : groups = groups or { r'all' : r'.*' } grouped = collections . defaultdict ( list ) for var in vars_ : for name , pattern in groups . items ( ) : if re . match ( pattern , var . name ) : name = re . sub ( pattern , name , var . name ) grouped [ name ... | Create histogram summaries for the provided variables . |
239,675 | def set_dimension ( tensor , axis , value ) : shape = tensor . shape . as_list ( ) if shape [ axis ] not in ( value , None ) : message = 'Cannot set dimension {} of tensor {} to {}; is already {}.' raise ValueError ( message . format ( axis , tensor . name , value , shape [ axis ] ) ) shape [ axis ] = value tensor . se... | Set the length of a tensor along the specified dimension . |
239,676 | def default ( ) : algorithm = algorithms . PPO num_agents = 30 eval_episodes = 30 use_gpu = False normalize_ranges = True network = networks . feed_forward_gaussian weight_summaries = dict ( all = r'.*' , policy = r'.*/policy/.*' , value = r'.*/value/.*' ) policy_layers = 200 , 100 value_layers = 200 , 100 init_output_... | Default configuration for PPO . |
239,677 | def pendulum ( ) : locals ( ) . update ( default ( ) ) env = 'Pendulum-v0' max_length = 200 steps = 1e6 batch_size = 20 chunk_length = 50 return locals ( ) | Configuration for the pendulum classic control task . |
239,678 | def cartpole ( ) : locals ( ) . update ( default ( ) ) env = 'CartPole-v1' max_length = 500 steps = 2e5 normalize_ranges = False network = networks . feed_forward_categorical return locals ( ) | Configuration for the cart pole classic control task . |
239,679 | def reacher ( ) : locals ( ) . update ( default ( ) ) env = 'Reacher-v2' max_length = 1000 steps = 5e6 discount = 0.985 update_every = 60 return locals ( ) | Configuration for MuJoCo s reacher task . |
239,680 | def bullet_ant ( ) : locals ( ) . update ( default ( ) ) import pybullet_envs env = 'AntBulletEnv-v0' max_length = 1000 steps = 3e7 update_every = 60 return locals ( ) | Configuration for PyBullet s ant task . |
239,681 | def step ( self , actions ) : for index , ( env , action ) in enumerate ( zip ( self . _envs , actions ) ) : if not env . action_space . contains ( action ) : message = 'Invalid action at index {}: {}' raise ValueError ( message . format ( index , action ) ) if self . _blocking : transitions = [ env . step ( action ) f... | Forward a batch of actions to the wrapped environments . |
239,682 | def call ( self , name , * args , ** kwargs ) : payload = name , args , kwargs self . _conn . send ( ( self . _CALL , payload ) ) return self . _receive | Asynchronously call a method of the external environment . |
239,683 | def close ( self ) : try : self . _conn . send ( ( self . _CLOSE , None ) ) self . _conn . close ( ) except IOError : pass self . _process . join ( ) | Send a close message to the external process and join it . |
239,684 | def step ( self , action , blocking = True ) : promise = self . call ( 'step' , action ) if blocking : return promise ( ) else : return promise | Step the environment . |
239,685 | def _receive ( self ) : message , payload = self . _conn . recv ( ) if message == self . _EXCEPTION : stacktrace = payload raise Exception ( stacktrace ) if message == self . _RESULT : return payload raise KeyError ( 'Received message of unexpected type {}' . format ( message ) ) | Wait for a message from the worker process and return its payload . |
239,686 | def _worker ( self , constructor , conn ) : try : env = constructor ( ) while True : try : if not conn . poll ( 0.1 ) : continue message , payload = conn . recv ( ) except ( EOFError , KeyboardInterrupt ) : break if message == self . _ACCESS : name = payload result = getattr ( env , name ) conn . send ( ( self . _RESUL... | The process waits for actions and sends back environment results . |
239,687 | def step ( self , action ) : observ , reward , done , info = self . _env . step ( action ) observ = self . _convert_observ ( observ ) reward = self . _convert_reward ( reward ) return observ , reward , done , info | Forward action to the wrapped environment . |
239,688 | def _convert_observ ( self , observ ) : if not np . isfinite ( observ ) . all ( ) : raise ValueError ( 'Infinite observation encountered.' ) if observ . dtype == np . float64 : return observ . astype ( np . float32 ) if observ . dtype == np . int64 : return observ . astype ( np . int32 ) return observ | Convert the observation to 32 bits . |
239,689 | def _convert_reward ( self , reward ) : if not np . isfinite ( reward ) . all ( ) : raise ValueError ( 'Infinite reward encountered.' ) return np . array ( reward , dtype = np . float32 ) | Convert the reward to 32 bits . |
239,690 | def value ( self ) : return self . _sum / tf . cast ( self . _count , self . _dtype ) | The current value of the mean . |
239,691 | def submit ( self , value ) : if value . shape . ndims == self . _sum . shape . ndims : value = value [ None , ... ] return tf . group ( self . _sum . assign_add ( tf . reduce_sum ( value , 0 ) ) , self . _count . assign_add ( tf . shape ( value ) [ 0 ] ) ) | Submit a single or batch tensor to refine the streaming mean . |
239,692 | def clear ( self ) : value = self . _sum / tf . cast ( self . _count , self . _dtype ) with tf . control_dependencies ( [ value ] ) : reset_value = self . _sum . assign ( tf . zeros_like ( self . _sum ) ) reset_count = self . _count . assign ( 0 ) with tf . control_dependencies ( [ reset_value , reset_count ] ) : retur... | Return the mean estimate and reset the streaming statistics . |
239,693 | def zip_ ( * structures , ** kwargs ) : flatten = kwargs . pop ( 'flatten' , False ) assert not kwargs , 'zip() got unexpected keyword arguments.' return map ( lambda * x : x if len ( x ) > 1 else x [ 0 ] , * structures , flatten = flatten ) | Combine corresponding elements in multiple nested structure to tuples . |
239,694 | def map_ ( function , * structures , ** kwargs ) : flatten = kwargs . pop ( 'flatten' , False ) assert not kwargs , 'map() got unexpected keyword arguments.' def impl ( function , * structures ) : if len ( structures ) == 0 : return structures if all ( isinstance ( s , ( tuple , list ) ) for s in structures ) : if len ... | Apply a function to every element in a nested structure . |
239,695 | def flatten_ ( structure ) : if isinstance ( structure , dict ) : if structure : structure = zip ( * sorted ( structure . items ( ) , key = lambda x : x [ 0 ] ) ) [ 1 ] else : structure = ( ) if isinstance ( structure , ( tuple , list ) ) : result = [ ] for element in structure : result += flatten_ ( element ) return t... | Combine all leaves of a nested structure into a tuple . |
239,696 | def filter_ ( predicate , * structures , ** kwargs ) : flatten = kwargs . pop ( 'flatten' , False ) assert not kwargs , 'filter() got unexpected keyword arguments.' def impl ( predicate , * structures ) : if len ( structures ) == 0 : return structures if all ( isinstance ( s , ( tuple , list ) ) for s in structures ) :... | Select elements of a nested structure based on a predicate function . |
239,697 | def add_phase ( self , name , done , score , summary , steps , report_every = None , log_every = None , checkpoint_every = None , feed = None ) : done = tf . convert_to_tensor ( done , tf . bool ) score = tf . convert_to_tensor ( score , tf . float32 ) summary = tf . convert_to_tensor ( summary , tf . string ) feed = f... | Add a phase to the loop protocol . |
239,698 | def run ( self , sess , saver , max_step = None ) : global_step = sess . run ( self . _step ) steps_made = 1 while True : if max_step and global_step >= max_step : break phase , epoch , steps_in = self . _find_current_phase ( global_step ) phase_step = epoch * phase . steps + steps_in if steps_in % phase . steps < step... | Run the loop schedule for a specified number of steps . |
239,699 | def _is_every_steps ( self , phase_step , batch , every ) : if not every : return False covered_steps = range ( phase_step , phase_step + batch ) return any ( ( step + 1 ) % every == 0 for step in covered_steps ) | Determine whether a periodic event should happen at this step . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.