repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
glitchassassin/lackey
lackey/RegionMatching.py
Region.setBottomRight
def setBottomRight(self, loc): """ Move this region so its bottom right corner is on ``loc`` """ offset = self.getBottomRight().getOffset(loc) # Calculate offset from current bottom right return self.setLocation(self.getTopLeft().offset(offset)) # Move top left corner by the same offset
python
def setBottomRight(self, loc): """ Move this region so its bottom right corner is on ``loc`` """ offset = self.getBottomRight().getOffset(loc) # Calculate offset from current bottom right return self.setLocation(self.getTopLeft().offset(offset)) # Move top left corner by the same offset
[ "def", "setBottomRight", "(", "self", ",", "loc", ")", ":", "offset", "=", "self", ".", "getBottomRight", "(", ")", ".", "getOffset", "(", "loc", ")", "return", "self", ".", "setLocation", "(", "self", ".", "getTopLeft", "(", ")", ".", "offset", "(", ...
Move this region so its bottom right corner is on ``loc``
[ "Move", "this", "region", "so", "its", "bottom", "right", "corner", "is", "on", "loc" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1241-L1244
train
glitchassassin/lackey
lackey/RegionMatching.py
Region.setSize
def setSize(self, w, h): """ Sets the new size of the region """ self.setW(w) self.setH(h) return self
python
def setSize(self, w, h): """ Sets the new size of the region """ self.setW(w) self.setH(h) return self
[ "def", "setSize", "(", "self", ",", "w", ",", "h", ")", ":", "self", ".", "setW", "(", "w", ")", "self", ".", "setH", "(", "h", ")", "return", "self" ]
Sets the new size of the region
[ "Sets", "the", "new", "size", "of", "the", "region" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1245-L1249
train
glitchassassin/lackey
lackey/RegionMatching.py
Region.saveScreenCapture
def saveScreenCapture(self, path=None, name=None): """ Saves the region's bitmap """ 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(".p...
python
def saveScreenCapture(self, path=None, name=None): """ Saves the region's bitmap """ 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(".p...
[ "def", "saveScreenCapture", "(", "self", ",", "path", "=", "None", ",", "name", "=", "None", ")", ":", "bitmap", "=", "self", ".", "getBitmap", "(", ")", "target_file", "=", "None", "if", "path", "is", "None", "and", "name", "is", "None", ":", "_", ...
Saves the region's bitmap
[ "Saves", "the", "region", "s", "bitmap" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1277-L1289
train
glitchassassin/lackey
lackey/RegionMatching.py
Region.saveLastScreenImage
def saveLastScreenImage(self): """ Saves the last image taken on this region's screen to a temporary file """ bitmap = self.getLastScreenImage() _, target_file = tempfile.mkstemp(".png") cv2.imwrite(target_file, bitmap)
python
def saveLastScreenImage(self): """ Saves the last image taken on this region's screen to a temporary file """ bitmap = self.getLastScreenImage() _, target_file = tempfile.mkstemp(".png") cv2.imwrite(target_file, bitmap)
[ "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
[ "Saves", "the", "last", "image", "taken", "on", "this", "region", "s", "screen", "to", "a", "temporary", "file" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1293-L1297
train
glitchassassin/lackey
lackey/RegionMatching.py
Region.onChange
def onChange(self, min_changed_pixels=None, handler=None): """ Registers an event to call ``handler`` when at least ``min_changed_pixels`` change in this region. (Default for min_changed_pixels is set in Settings.ObserveMinChangedPixels) The ``handler`` function should take one paramet...
python
def onChange(self, min_changed_pixels=None, handler=None): """ Registers an event to call ``handler`` when at least ``min_changed_pixels`` change in this region. (Default for min_changed_pixels is set in Settings.ObserveMinChangedPixels) The ``handler`` function should take one paramet...
[ "def", "onChange", "(", "self", ",", "min_changed_pixels", "=", "None", ",", "handler", "=", "None", ")", ":", "if", "isinstance", "(", "min_changed_pixels", ",", "int", ")", "and", "(", "callable", "(", "handler", ")", "or", "handler", "is", "None", ")"...
Registers an event to call ``handler`` when at least ``min_changed_pixels`` change in this region. (Default for min_changed_pixels is set in Settings.ObserveMinChangedPixels) The ``handler`` function should take one parameter, an ObserveEvent object (see below). This event is ignored i...
[ "Registers", "an", "event", "to", "call", "handler", "when", "at", "least", "min_changed_pixels", "change", "in", "this", "region", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1400-L1424
train
glitchassassin/lackey
lackey/RegionMatching.py
Region.isChanged
def isChanged(self, min_changed_pixels, screen_state): """ Returns true if at least ``min_changed_pixels`` are different between ``screen_state`` and the current state. """ r = self.clipRegionToScreen() current_state = r.getBitmap() diff = numpy.subtract(current_state, sc...
python
def isChanged(self, min_changed_pixels, screen_state): """ Returns true if at least ``min_changed_pixels`` are different between ``screen_state`` and the current state. """ r = self.clipRegionToScreen() current_state = r.getBitmap() diff = numpy.subtract(current_state, sc...
[ "def", "isChanged", "(", "self", ",", "min_changed_pixels", ",", "screen_state", ")", ":", "r", "=", "self", ".", "clipRegionToScreen", "(", ")", "current_state", "=", "r", ".", "getBitmap", "(", ")", "diff", "=", "numpy", ".", "subtract", "(", "current_st...
Returns true if at least ``min_changed_pixels`` are different between ``screen_state`` and the current state.
[ "Returns", "true", "if", "at", "least", "min_changed_pixels", "are", "different", "between", "screen_state", "and", "the", "current", "state", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1425-L1432
train
glitchassassin/lackey
lackey/RegionMatching.py
Region.stopObserver
def stopObserver(self): """ Stops this region's observer loop. If this is running in a subprocess, the subprocess will end automatically. """ self._observer.isStopped = True self._observer.isRunning = False
python
def stopObserver(self): """ Stops this region's observer loop. If this is running in a subprocess, the subprocess will end automatically. """ self._observer.isStopped = True self._observer.isRunning = False
[ "def", "stopObserver", "(", "self", ")", ":", "self", ".", "_observer", ".", "isStopped", "=", "True", "self", ".", "_observer", ".", "isRunning", "=", "False" ]
Stops this region's observer loop. If this is running in a subprocess, the subprocess will end automatically.
[ "Stops", "this", "region", "s", "observer", "loop", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1486-L1492
train
glitchassassin/lackey
lackey/RegionMatching.py
Region.getEvents
def getEvents(self): """ Returns a list of all events that have occurred. Empties the internal queue. """ caught_events = self._observer.caught_events self._observer.caught_events = [] for event in caught_events: self._observer.activate_event(event["name"]) ...
python
def getEvents(self): """ Returns a list of all events that have occurred. Empties the internal queue. """ caught_events = self._observer.caught_events self._observer.caught_events = [] for event in caught_events: self._observer.activate_event(event["name"]) ...
[ "def", "getEvents", "(", "self", ")", ":", "caught_events", "=", "self", ".", "_observer", ".", "caught_events", "self", ".", "_observer", ".", "caught_events", "=", "[", "]", "for", "event", "in", "caught_events", ":", "self", ".", "_observer", ".", "acti...
Returns a list of all events that have occurred. Empties the internal queue.
[ "Returns", "a", "list", "of", "all", "events", "that", "have", "occurred", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1506-L1515
train
glitchassassin/lackey
lackey/RegionMatching.py
Region.getEvent
def getEvent(self, name): """ Returns the named event. Removes it from the internal queue. """ to_return = None for event in self._observer.caught_events: if event["name"] == name: to_return = event break if to_return: ...
python
def getEvent(self, name): """ Returns the named event. Removes it from the internal queue. """ to_return = None for event in self._observer.caught_events: if event["name"] == name: to_return = event break if to_return: ...
[ "def", "getEvent", "(", "self", ",", "name", ")", ":", "to_return", "=", "None", "for", "event", "in", "self", ".", "_observer", ".", "caught_events", ":", "if", "event", "[", "\"name\"", "]", "==", "name", ":", "to_return", "=", "event", "break", "if"...
Returns the named event. Removes it from the internal queue.
[ "Returns", "the", "named", "event", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1516-L1529
train
glitchassassin/lackey
lackey/RegionMatching.py
Region.setFindFailedResponse
def setFindFailedResponse(self, response): """ Set the response to a FindFailed exception in this region. Can be ABORT, SKIP, PROMPT, or RETRY. """ valid_responses = ("ABORT", "SKIP", "PROMPT", "RETRY") if response not in valid_responses: raise ValueError("Invalid re...
python
def setFindFailedResponse(self, response): """ Set the response to a FindFailed exception in this region. Can be ABORT, SKIP, PROMPT, or RETRY. """ valid_responses = ("ABORT", "SKIP", "PROMPT", "RETRY") if response not in valid_responses: raise ValueError("Invalid re...
[ "def", "setFindFailedResponse", "(", "self", ",", "response", ")", ":", "valid_responses", "=", "(", "\"ABORT\"", ",", "\"SKIP\"", ",", "\"PROMPT\"", ",", "\"RETRY\"", ")", "if", "response", "not", "in", "valid_responses", ":", "raise", "ValueError", "(", "\"I...
Set the response to a FindFailed exception in this region. Can be ABORT, SKIP, PROMPT, or RETRY.
[ "Set", "the", "response", "to", "a", "FindFailed", "exception", "in", "this", "region", ".", "Can", "be", "ABORT", "SKIP", "PROMPT", "or", "RETRY", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1569-L1576
train
glitchassassin/lackey
lackey/RegionMatching.py
Region.setThrowException
def setThrowException(self, setting): """ Defines whether an exception should be thrown for FindFailed operations. ``setting`` should be True or False. """ if setting: self._throwException = True self._findFailedResponse = "ABORT" else: self._throwExc...
python
def setThrowException(self, setting): """ Defines whether an exception should be thrown for FindFailed operations. ``setting`` should be True or False. """ if setting: self._throwException = True self._findFailedResponse = "ABORT" else: self._throwExc...
[ "def", "setThrowException", "(", "self", ",", "setting", ")", ":", "if", "setting", ":", "self", ".", "_throwException", "=", "True", "self", ".", "_findFailedResponse", "=", "\"ABORT\"", "else", ":", "self", ".", "_throwException", "=", "False", "self", "."...
Defines whether an exception should be thrown for FindFailed operations. ``setting`` should be True or False.
[ "Defines", "whether", "an", "exception", "should", "be", "thrown", "for", "FindFailed", "operations", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1586-L1595
train
glitchassassin/lackey
lackey/RegionMatching.py
Observer.register_event
def register_event(self, event_type, pattern, handler): """ When ``event_type`` is observed for ``pattern``, triggers ``handler``. For "CHANGE" events, ``pattern`` should be a tuple of ``min_changed_pixels`` and the base screen state. """ if event_type not in self._supported_eve...
python
def register_event(self, event_type, pattern, handler): """ When ``event_type`` is observed for ``pattern``, triggers ``handler``. For "CHANGE" events, ``pattern`` should be a tuple of ``min_changed_pixels`` and the base screen state. """ if event_type not in self._supported_eve...
[ "def", "register_event", "(", "self", ",", "event_type", ",", "pattern", ",", "handler", ")", ":", "if", "event_type", "not", "in", "self", ".", "_supported_events", ":", "raise", "ValueError", "(", "\"Unsupported event type {}\"", ".", "format", "(", "event_typ...
When ``event_type`` is observed for ``pattern``, triggers ``handler``. For "CHANGE" events, ``pattern`` should be a tuple of ``min_changed_pixels`` and the base screen state.
[ "When", "event_type", "is", "observed", "for", "pattern", "triggers", "handler", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1650-L1673
train
glitchassassin/lackey
lackey/RegionMatching.py
Screen.capture
def capture(self, *args): #x=None, y=None, w=None, h=None): """ Captures the region as an image """ if len(args) == 0: # Capture screen region region = self elif isinstance(args[0], Region): # Capture specified region region = args[0] elif ...
python
def capture(self, *args): #x=None, y=None, w=None, h=None): """ Captures the region as an image """ if len(args) == 0: # Capture screen region region = self elif isinstance(args[0], Region): # Capture specified region region = args[0] elif ...
[ "def", "capture", "(", "self", ",", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "0", ":", "region", "=", "self", "elif", "isinstance", "(", "args", "[", "0", "]", ",", "Region", ")", ":", "region", "=", "args", "[", "0", "]", ...
Captures the region as an image
[ "Captures", "the", "region", "as", "an", "image" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1854-L1872
train
glitchassassin/lackey
lackey/RegionMatching.py
Screen.showMonitors
def showMonitors(cls): """ Prints debug information about currently detected screens """ Debug.info("*** monitor configuration [ {} Screen(s)] ***".format(cls.getNumberScreens())) Debug.info("*** Primary is Screen {}".format(cls.primaryScreen)) for index, screen in enumerate(PlatformMana...
python
def showMonitors(cls): """ Prints debug information about currently detected screens """ Debug.info("*** monitor configuration [ {} Screen(s)] ***".format(cls.getNumberScreens())) Debug.info("*** Primary is Screen {}".format(cls.primaryScreen)) for index, screen in enumerate(PlatformMana...
[ "def", "showMonitors", "(", "cls", ")", ":", "Debug", ".", "info", "(", "\"*** monitor configuration [ {} Screen(s)] ***\"", ".", "format", "(", "cls", ".", "getNumberScreens", "(", ")", ")", ")", "Debug", ".", "info", "(", "\"*** Primary is Screen {}\"", ".", "...
Prints debug information about currently detected screens
[ "Prints", "debug", "information", "about", "currently", "detected", "screens" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1908-L1914
train
glitchassassin/lackey
lackey/RegionMatching.py
Screen.resetMonitors
def resetMonitors(self): """ Recalculates screen based on changed monitor setup """ 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 lo...
python
def resetMonitors(self): """ Recalculates screen based on changed monitor setup """ 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 lo...
[ "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 ...
Recalculates screen based on changed monitor setup
[ "Recalculates", "screen", "based", "on", "changed", "monitor", "setup" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1915-L1922
train
glitchassassin/lackey
lackey/RegionMatching.py
Screen.newRegion
def newRegion(self, loc, width, height): """ Creates a new region on the current screen at the specified offset with the specified width and height. """ return Region.create(self.getTopLeft().offset(loc), width, height)
python
def newRegion(self, loc, width, height): """ Creates a new region on the current screen at the specified offset with the specified width and height. """ return Region.create(self.getTopLeft().offset(loc), width, height)
[ "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.
[ "Creates", "a", "new", "region", "on", "the", "current", "screen", "at", "the", "specified", "offset", "with", "the", "specified", "width", "and", "height", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L1923-L1926
train
glitchassassin/lackey
lackey/SettingsDebug.py
DebugMaster.history
def history(self, message): """ Records an Action-level log message Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is defined, sends to STDOUT """ if Settings.ActionLogs: self._write_log("action", Settings.LogTime, message)
python
def history(self, message): """ Records an Action-level log message Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is defined, sends to STDOUT """ if Settings.ActionLogs: self._write_log("action", Settings.LogTime, message)
[ "def", "history", "(", "self", ",", "message", ")", ":", "if", "Settings", ".", "ActionLogs", ":", "self", ".", "_write_log", "(", "\"action\"", ",", "Settings", ".", "LogTime", ",", "message", ")" ]
Records an Action-level log message Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is defined, sends to STDOUT
[ "Records", "an", "Action", "-", "level", "log", "message" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/SettingsDebug.py#L34-L41
train
glitchassassin/lackey
lackey/SettingsDebug.py
DebugMaster.error
def error(self, message): """ Records an Error-level log message Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is defined, sends to STDOUT """ if Settings.ErrorLogs: self._write_log("error", Settings.LogTime, message)
python
def error(self, message): """ Records an Error-level log message Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is defined, sends to STDOUT """ if Settings.ErrorLogs: self._write_log("error", Settings.LogTime, message)
[ "def", "error", "(", "self", ",", "message", ")", ":", "if", "Settings", ".", "ErrorLogs", ":", "self", ".", "_write_log", "(", "\"error\"", ",", "Settings", ".", "LogTime", ",", "message", ")" ]
Records an Error-level log message Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is defined, sends to STDOUT
[ "Records", "an", "Error", "-", "level", "log", "message" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/SettingsDebug.py#L42-L49
train
glitchassassin/lackey
lackey/SettingsDebug.py
DebugMaster.info
def info(self, message): """ Records an Info-level log message Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is defined, sends to STDOUT """ if Settings.InfoLogs: self._write_log("info", Settings.LogTime, message)
python
def info(self, message): """ Records an Info-level log message Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is defined, sends to STDOUT """ if Settings.InfoLogs: self._write_log("info", Settings.LogTime, message)
[ "def", "info", "(", "self", ",", "message", ")", ":", "if", "Settings", ".", "InfoLogs", ":", "self", ".", "_write_log", "(", "\"info\"", ",", "Settings", ".", "LogTime", ",", "message", ")" ]
Records an Info-level log message Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is defined, sends to STDOUT
[ "Records", "an", "Info", "-", "level", "log", "message" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/SettingsDebug.py#L50-L57
train
glitchassassin/lackey
lackey/SettingsDebug.py
DebugMaster.on
def on(self, level): """ Turns on all debugging messages up to the specified level 0 = None; 1 = User; """ if isinstance(level, int) and level >= 0 and level <= 3: self._debug_level = level
python
def on(self, level): """ Turns on all debugging messages up to the specified level 0 = None; 1 = User; """ if isinstance(level, int) and level >= 0 and level <= 3: self._debug_level = level
[ "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 0 = None; 1 = User;
[ "Turns", "on", "all", "debugging", "messages", "up", "to", "the", "specified", "level" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/SettingsDebug.py#L58-L64
train
glitchassassin/lackey
lackey/SettingsDebug.py
DebugMaster.setLogFile
def setLogFile(self, filepath): """ Defines the file to which output log messages should be sent. Set to `None` to print to STDOUT instead. """ if filepath is None: self._log_file = None return parsed_path = os.path.abspath(filepath) # Checks if t...
python
def setLogFile(self, filepath): """ Defines the file to which output log messages should be sent. Set to `None` to print to STDOUT instead. """ if filepath is None: self._log_file = None return parsed_path = os.path.abspath(filepath) # Checks if t...
[ "def", "setLogFile", "(", "self", ",", "filepath", ")", ":", "if", "filepath", "is", "None", ":", "self", ".", "_log_file", "=", "None", "return", "parsed_path", "=", "os", ".", "path", ".", "abspath", "(", "filepath", ")", "if", "os", ".", "path", "...
Defines the file to which output log messages should be sent. Set to `None` to print to STDOUT instead.
[ "Defines", "the", "file", "to", "which", "output", "log", "messages", "should", "be", "sent", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/SettingsDebug.py#L102-L116
train
glitchassassin/lackey
lackey/SettingsDebug.py
DebugMaster._write_log
def _write_log(self, log_type, log_time, message): """ Private method to abstract log writing for different types of logs """ timestamp = datetime.datetime.now().strftime(" %Y-%m-%d %H:%M:%S") log_entry = "[{}{}] {}".format(log_type, timestamp if log_time else "", message) if self._logge...
python
def _write_log(self, log_type, log_time, message): """ Private method to abstract log writing for different types of logs """ timestamp = datetime.datetime.now().strftime(" %Y-%m-%d %H:%M:%S") log_entry = "[{}{}] {}".format(log_type, timestamp if log_time else "", message) if self._logge...
[ "def", "_write_log", "(", "self", ",", "log_type", ",", "log_time", ",", "message", ")", ":", "timestamp", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "\" %Y-%m-%d %H:%M:%S\"", ")", "log_entry", "=", "\"[{}{}] {}\"", ".", ...
Private method to abstract log writing for different types of logs
[ "Private", "method", "to", "abstract", "log", "writing", "for", "different", "types", "of", "logs" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/SettingsDebug.py#L117-L137
train
glitchassassin/lackey
lackey/__init__.py
addImagePath
def addImagePath(new_path): """ Convenience function. Adds a path to the list of paths to search for images. Can be a URL (but must be accessible). """ if os.path.exists(new_path): Settings.ImagePaths.append(new_path) elif "http://" in new_path or "https://" in new_path: request = reque...
python
def addImagePath(new_path): """ Convenience function. Adds a path to the list of paths to search for images. Can be a URL (but must be accessible). """ if os.path.exists(new_path): Settings.ImagePaths.append(new_path) elif "http://" in new_path or "https://" in new_path: request = reque...
[ "def", "addImagePath", "(", "new_path", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "new_path", ")", ":", "Settings", ".", "ImagePaths", ".", "append", "(", "new_path", ")", "elif", "\"http://\"", "in", "new_path", "or", "\"https://\"", "in", ...
Convenience function. Adds a path to the list of paths to search for images. Can be a URL (but must be accessible).
[ "Convenience", "function", ".", "Adds", "a", "path", "to", "the", "list", "of", "paths", "to", "search", "for", "images", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L107-L121
train
glitchassassin/lackey
lackey/__init__.py
unzip
def unzip(from_file, to_folder): """ Convenience function. Extracts files from the zip file `fromFile` into the folder `toFolder`. """ with ZipFile(os.path.abspath(from_file), 'r') as to_unzip: to_unzip.extractall(os.path.abspath(to_folder))
python
def unzip(from_file, to_folder): """ Convenience function. Extracts files from the zip file `fromFile` into the folder `toFolder`. """ with ZipFile(os.path.abspath(from_file), 'r') as to_unzip: to_unzip.extractall(os.path.abspath(to_folder))
[ "def", "unzip", "(", "from_file", ",", "to_folder", ")", ":", "with", "ZipFile", "(", "os", ".", "path", ".", "abspath", "(", "from_file", ")", ",", "'r'", ")", "as", "to_unzip", ":", "to_unzip", ".", "extractall", "(", "os", ".", "path", ".", "abspa...
Convenience function. Extracts files from the zip file `fromFile` into the folder `toFolder`.
[ "Convenience", "function", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L146-L151
train
glitchassassin/lackey
lackey/__init__.py
popup
def popup(text, title="Lackey Info"): """ Creates an info dialog with the specified text. """ root = tk.Tk() root.withdraw() tkMessageBox.showinfo(title, text)
python
def popup(text, title="Lackey Info"): """ Creates an info dialog with the specified text. """ root = tk.Tk() root.withdraw() tkMessageBox.showinfo(title, text)
[ "def", "popup", "(", "text", ",", "title", "=", "\"Lackey Info\"", ")", ":", "root", "=", "tk", ".", "Tk", "(", ")", "root", ".", "withdraw", "(", ")", "tkMessageBox", ".", "showinfo", "(", "title", ",", "text", ")" ]
Creates an info dialog with the specified text.
[ "Creates", "an", "info", "dialog", "with", "the", "specified", "text", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L176-L180
train
glitchassassin/lackey
lackey/__init__.py
popError
def popError(text, title="Lackey Error"): """ Creates an error dialog with the specified text. """ root = tk.Tk() root.withdraw() tkMessageBox.showerror(title, text)
python
def popError(text, title="Lackey Error"): """ Creates an error dialog with the specified text. """ root = tk.Tk() root.withdraw() tkMessageBox.showerror(title, text)
[ "def", "popError", "(", "text", ",", "title", "=", "\"Lackey Error\"", ")", ":", "root", "=", "tk", ".", "Tk", "(", ")", "root", ".", "withdraw", "(", ")", "tkMessageBox", ".", "showerror", "(", "title", ",", "text", ")" ]
Creates an error dialog with the specified text.
[ "Creates", "an", "error", "dialog", "with", "the", "specified", "text", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L181-L185
train
glitchassassin/lackey
lackey/__init__.py
popAsk
def popAsk(text, title="Lackey Decision"): """ Creates a yes-no dialog with the specified text. """ root = tk.Tk() root.withdraw() return tkMessageBox.askyesno(title, text)
python
def popAsk(text, title="Lackey Decision"): """ Creates a yes-no dialog with the specified text. """ root = tk.Tk() root.withdraw() return tkMessageBox.askyesno(title, text)
[ "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.
[ "Creates", "a", "yes", "-", "no", "dialog", "with", "the", "specified", "text", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L186-L190
train
glitchassassin/lackey
lackey/__init__.py
input
def input(msg="", default="", title="Lackey Input", hidden=False): """ Creates an input dialog with the specified message and default text. If `hidden`, creates a password dialog instead. Returns the entered value. """ root = tk.Tk() input_text = tk.StringVar() input_text.set(default) PopupInpu...
python
def input(msg="", default="", title="Lackey Input", hidden=False): """ Creates an input dialog with the specified message and default text. If `hidden`, creates a password dialog instead. Returns the entered value. """ root = tk.Tk() input_text = tk.StringVar() input_text.set(default) PopupInpu...
[ "def", "input", "(", "msg", "=", "\"\"", ",", "default", "=", "\"\"", ",", "title", "=", "\"Lackey Input\"", ",", "hidden", "=", "False", ")", ":", "root", "=", "tk", ".", "Tk", "(", ")", "input_text", "=", "tk", ".", "StringVar", "(", ")", "input_...
Creates an input dialog with the specified message and default text. If `hidden`, creates a password dialog instead. Returns the entered value.
[ "Creates", "an", "input", "dialog", "with", "the", "specified", "message", "and", "default", "text", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L193-L203
train
glitchassassin/lackey
lackey/__init__.py
inputText
def inputText(message="", title="Lackey Input", lines=9, width=20, text=""): """ Creates a textarea dialog with the specified message and default text. Returns the entered value. """ root = tk.Tk() input_text = tk.StringVar() input_text.set(text) PopupTextarea(root, message, title, lines, width...
python
def inputText(message="", title="Lackey Input", lines=9, width=20, text=""): """ Creates a textarea dialog with the specified message and default text. Returns the entered value. """ root = tk.Tk() input_text = tk.StringVar() input_text.set(text) PopupTextarea(root, message, title, lines, width...
[ "def", "inputText", "(", "message", "=", "\"\"", ",", "title", "=", "\"Lackey Input\"", ",", "lines", "=", "9", ",", "width", "=", "20", ",", "text", "=", "\"\"", ")", ":", "root", "=", "tk", ".", "Tk", "(", ")", "input_text", "=", "tk", ".", "St...
Creates a textarea dialog with the specified message and default text. Returns the entered value.
[ "Creates", "a", "textarea", "dialog", "with", "the", "specified", "message", "and", "default", "text", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L204-L214
train
glitchassassin/lackey
lackey/__init__.py
select
def select(message="", title="Lackey Input", options=None, default=None): """ Creates a dropdown selection dialog with the specified message and options `default` must be one of the options. Returns the selected value. """ if options is None or len(options) == 0: return "" if default is ...
python
def select(message="", title="Lackey Input", options=None, default=None): """ Creates a dropdown selection dialog with the specified message and options `default` must be one of the options. Returns the selected value. """ if options is None or len(options) == 0: return "" if default is ...
[ "def", "select", "(", "message", "=", "\"\"", ",", "title", "=", "\"Lackey Input\"", ",", "options", "=", "None", ",", "default", "=", "None", ")", ":", "if", "options", "is", "None", "or", "len", "(", "options", ")", "==", "0", ":", "return", "\"\""...
Creates a dropdown selection dialog with the specified message and options `default` must be one of the options. Returns the selected value.
[ "Creates", "a", "dropdown", "selection", "dialog", "with", "the", "specified", "message", "and", "options" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L215-L233
train
glitchassassin/lackey
lackey/__init__.py
popFile
def popFile(title="Lackey Open File"): """ Creates a file selection dialog with the specified message and options. Returns the selected file. """ root = tk.Tk() root.withdraw() return str(tkFileDialog.askopenfilename(title=title))
python
def popFile(title="Lackey Open File"): """ Creates a file selection dialog with the specified message and options. Returns the selected file. """ root = tk.Tk() root.withdraw() return str(tkFileDialog.askopenfilename(title=title))
[ "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. Returns the selected file.
[ "Creates", "a", "file", "selection", "dialog", "with", "the", "specified", "message", "and", "options", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L234-L240
train
glitchassassin/lackey
lackey/Geometry.py
Location.setLocation
def setLocation(self, x, y): """Set the location of this object to the specified coordinates.""" self.x = int(x) self.y = int(y) return self
python
def setLocation(self, x, y): """Set the location of this object to the specified coordinates.""" self.x = int(x) self.y = int(y) return self
[ "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.
[ "Set", "the", "location", "of", "this", "object", "to", "the", "specified", "coordinates", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/Geometry.py#L15-L19
train
glitchassassin/lackey
lackey/Geometry.py
Location.offset
def offset(self, dx, dy): """Get a new location which is dx and dy pixels away horizontally and vertically from the current location. """ return Location(self.x+dx, self.y+dy)
python
def offset(self, dx, dy): """Get a new location which is dx and dy pixels away horizontally and vertically from the current location. """ return Location(self.x+dx, self.y+dy)
[ "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.
[ "Get", "a", "new", "location", "which", "is", "dx", "and", "dy", "pixels", "away", "horizontally", "and", "vertically", "from", "the", "current", "location", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/Geometry.py#L22-L26
train
glitchassassin/lackey
lackey/Geometry.py
Location.getOffset
def getOffset(self, loc): """ Returns the offset between the given point and this point """ return Location(loc.x - self.x, loc.y - self.y)
python
def getOffset(self, loc): """ Returns the offset between the given point and this point """ return Location(loc.x - self.x, loc.y - self.y)
[ "def", "getOffset", "(", "self", ",", "loc", ")", ":", "return", "Location", "(", "loc", ".", "x", "-", "self", ".", "x", ",", "loc", ".", "y", "-", "self", ".", "y", ")" ]
Returns the offset between the given point and this point
[ "Returns", "the", "offset", "between", "the", "given", "point", "and", "this", "point" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/Geometry.py#L71-L73
train
glitchassassin/lackey
lackey/Geometry.py
Location.copyTo
def copyTo(self, screen): """ Creates a new point with the same offset on the target screen as this point has on the current screen """ from .RegionMatching import Screen if not isinstance(screen, Screen): screen = RegionMatching.Screen(screen) return screen.getTopLef...
python
def copyTo(self, screen): """ Creates a new point with the same offset on the target screen as this point has on the current screen """ from .RegionMatching import Screen if not isinstance(screen, Screen): screen = RegionMatching.Screen(screen) return screen.getTopLef...
[ "def", "copyTo", "(", "self", ",", "screen", ")", ":", "from", ".", "RegionMatching", "import", "Screen", "if", "not", "isinstance", "(", "screen", ",", "Screen", ")", ":", "screen", "=", "RegionMatching", ".", "Screen", "(", "screen", ")", "return", "sc...
Creates a new point with the same offset on the target screen as this point has on the current screen
[ "Creates", "a", "new", "point", "with", "the", "same", "offset", "on", "the", "target", "screen", "as", "this", "point", "has", "on", "the", "current", "screen" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/Geometry.py#L96-L102
train
glitchassassin/lackey
lackey/App.py
App.focusedWindow
def focusedWindow(cls): """ Returns a Region corresponding to whatever window is in the foreground """ x, y, w, h = PlatformManager.getWindowRect(PlatformManager.getForegroundWindow()) return Region(x, y, w, h)
python
def focusedWindow(cls): """ Returns a Region corresponding to whatever window is in the foreground """ x, y, w, h = PlatformManager.getWindowRect(PlatformManager.getForegroundWindow()) return Region(x, y, w, h)
[ "def", "focusedWindow", "(", "cls", ")", ":", "x", ",", "y", ",", "w", ",", "h", "=", "PlatformManager", ".", "getWindowRect", "(", "PlatformManager", ".", "getForegroundWindow", "(", ")", ")", "return", "Region", "(", "x", ",", "y", ",", "w", ",", "...
Returns a Region corresponding to whatever window is in the foreground
[ "Returns", "a", "Region", "corresponding", "to", "whatever", "window", "is", "in", "the", "foreground" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/App.py#L182-L185
train
glitchassassin/lackey
lackey/App.py
App.getWindow
def getWindow(self): """ Returns the title of the main window of the currently open app. Returns an empty string if no match could be found. """ if self.getPID() != -1: return PlatformManager.getWindowTitle(PlatformManager.getWindowByPID(self.getPID())) else: ...
python
def getWindow(self): """ Returns the title of the main window of the currently open app. Returns an empty string if no match could be found. """ if self.getPID() != -1: return PlatformManager.getWindowTitle(PlatformManager.getWindowByPID(self.getPID())) else: ...
[ "def", "getWindow", "(", "self", ")", ":", "if", "self", ".", "getPID", "(", ")", "!=", "-", "1", ":", "return", "PlatformManager", ".", "getWindowTitle", "(", "PlatformManager", ".", "getWindowByPID", "(", "self", ".", "getPID", "(", ")", ")", ")", "e...
Returns the title of the main window of the currently open app. Returns an empty string if no match could be found.
[ "Returns", "the", "title", "of", "the", "main", "window", "of", "the", "currently", "open", "app", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/App.py#L187-L195
train
glitchassassin/lackey
lackey/App.py
App.window
def window(self, windowNum=0): """ Returns the region corresponding to the specified window of the app. Defaults to the first window found for the corresponding PID. """ if self._pid == -1: return None x,y,w,h = PlatformManager.getWindowRect(PlatformManager.getWindow...
python
def window(self, windowNum=0): """ Returns the region corresponding to the specified window of the app. Defaults to the first window found for the corresponding PID. """ if self._pid == -1: return None x,y,w,h = PlatformManager.getWindowRect(PlatformManager.getWindow...
[ "def", "window", "(", "self", ",", "windowNum", "=", "0", ")", ":", "if", "self", ".", "_pid", "==", "-", "1", ":", "return", "None", "x", ",", "y", ",", "w", ",", "h", "=", "PlatformManager", ".", "getWindowRect", "(", "PlatformManager", ".", "get...
Returns the region corresponding to the specified window of the app. Defaults to the first window found for the corresponding PID.
[ "Returns", "the", "region", "corresponding", "to", "the", "specified", "window", "of", "the", "app", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/App.py#L220-L228
train
glitchassassin/lackey
lackey/App.py
App.isRunning
def isRunning(self, waitTime=0): """ If PID isn't set yet, checks if there is a window with the specified title. """ waitUntil = time.time() + waitTime while True: if self.getPID() > 0: return True else: self._pid = PlatformManager.getWindo...
python
def isRunning(self, waitTime=0): """ If PID isn't set yet, checks if there is a window with the specified title. """ waitUntil = time.time() + waitTime while True: if self.getPID() > 0: return True else: self._pid = PlatformManager.getWindo...
[ "def", "isRunning", "(", "self", ",", "waitTime", "=", "0", ")", ":", "waitUntil", "=", "time", ".", "time", "(", ")", "+", "waitTime", "while", "True", ":", "if", "self", ".", "getPID", "(", ")", ">", "0", ":", "return", "True", "else", ":", "se...
If PID isn't set yet, checks if there is a window with the specified title.
[ "If", "PID", "isn", "t", "set", "yet", "checks", "if", "there", "is", "a", "window", "with", "the", "specified", "title", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/App.py#L237-L251
train
glitchassassin/lackey
lackey/PlatformManagerDarwin.py
PlatformManagerDarwin._getVirtualScreenBitmap
def _getVirtualScreenBitmap(self): """ Returns a bitmap of all attached screens """ filenames = [] screen_details = self.getScreenDetails() for screen in screen_details: fh, filepath = tempfile.mkstemp('.png') filenames.append(filepath) os.close(fh) ...
python
def _getVirtualScreenBitmap(self): """ Returns a bitmap of all attached screens """ filenames = [] screen_details = self.getScreenDetails() for screen in screen_details: fh, filepath = tempfile.mkstemp('.png') filenames.append(filepath) os.close(fh) ...
[ "def", "_getVirtualScreenBitmap", "(", "self", ")", ":", "filenames", "=", "[", "]", "screen_details", "=", "self", ".", "getScreenDetails", "(", ")", "for", "screen", "in", "screen_details", ":", "fh", ",", "filepath", "=", "tempfile", ".", "mkstemp", "(", ...
Returns a bitmap of all attached screens
[ "Returns", "a", "bitmap", "of", "all", "attached", "screens" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/PlatformManagerDarwin.py#L228-L254
train
glitchassassin/lackey
lackey/PlatformManagerDarwin.py
PlatformManagerDarwin.osCopy
def osCopy(self): """ Triggers the OS "copy" keyboard shortcut """ k = Keyboard() k.keyDown("{CTRL}") k.type("c") k.keyUp("{CTRL}")
python
def osCopy(self): """ Triggers the OS "copy" keyboard shortcut """ k = Keyboard() k.keyDown("{CTRL}") k.type("c") k.keyUp("{CTRL}")
[ "def", "osCopy", "(", "self", ")", ":", "k", "=", "Keyboard", "(", ")", "k", ".", "keyDown", "(", "\"{CTRL}\"", ")", "k", ".", "type", "(", "\"c\"", ")", "k", ".", "keyUp", "(", "\"{CTRL}\"", ")" ]
Triggers the OS "copy" keyboard shortcut
[ "Triggers", "the", "OS", "copy", "keyboard", "shortcut" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/PlatformManagerDarwin.py#L287-L292
train
glitchassassin/lackey
lackey/PlatformManagerDarwin.py
PlatformManagerDarwin.getForegroundWindow
def getForegroundWindow(self): """ Returns a handle to the window in the foreground """ active_app = NSWorkspace.sharedWorkspace().frontmostApplication().localizedName() for w in self._get_window_list(): if "kCGWindowOwnerName" in w and w["kCGWindowOwnerName"] == active_app: ...
python
def getForegroundWindow(self): """ Returns a handle to the window in the foreground """ active_app = NSWorkspace.sharedWorkspace().frontmostApplication().localizedName() for w in self._get_window_list(): if "kCGWindowOwnerName" in w and w["kCGWindowOwnerName"] == active_app: ...
[ "def", "getForegroundWindow", "(", "self", ")", ":", "active_app", "=", "NSWorkspace", ".", "sharedWorkspace", "(", ")", ".", "frontmostApplication", "(", ")", ".", "localizedName", "(", ")", "for", "w", "in", "self", ".", "_get_window_list", "(", ")", ":", ...
Returns a handle to the window in the foreground
[ "Returns", "a", "handle", "to", "the", "window", "in", "the", "foreground" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/PlatformManagerDarwin.py#L347-L352
train
glitchassassin/lackey
lackey/PlatformManagerDarwin.py
PlatformManagerDarwin._get_window_list
def _get_window_list(self): """ Returns a dictionary of details about open windows """ window_list = Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListExcludeDesktopElements, Quartz.kCGNullWindowID) return window_list
python
def _get_window_list(self): """ Returns a dictionary of details about open windows """ window_list = Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListExcludeDesktopElements, Quartz.kCGNullWindowID) return window_list
[ "def", "_get_window_list", "(", "self", ")", ":", "window_list", "=", "Quartz", ".", "CGWindowListCopyWindowInfo", "(", "Quartz", ".", "kCGWindowListExcludeDesktopElements", ",", "Quartz", ".", "kCGNullWindowID", ")", "return", "window_list" ]
Returns a dictionary of details about open windows
[ "Returns", "a", "dictionary", "of", "details", "about", "open", "windows" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/PlatformManagerDarwin.py#L354-L357
train
glitchassassin/lackey
lackey/PlatformManagerDarwin.py
PlatformManagerDarwin.getProcessName
def getProcessName(self, pid): """ Searches all processes for the given PID, then returns the originating command """ ps = subprocess.check_output(["ps", "aux"]).decode("ascii") processes = ps.split("\n") cols = len(processes[0].split()) - 1 for row in processes[1:]: ...
python
def getProcessName(self, pid): """ Searches all processes for the given PID, then returns the originating command """ ps = subprocess.check_output(["ps", "aux"]).decode("ascii") processes = ps.split("\n") cols = len(processes[0].split()) - 1 for row in processes[1:]: ...
[ "def", "getProcessName", "(", "self", ",", "pid", ")", ":", "ps", "=", "subprocess", ".", "check_output", "(", "[", "\"ps\"", ",", "\"aux\"", "]", ")", ".", "decode", "(", "\"ascii\"", ")", "processes", "=", "ps", ".", "split", "(", "\"\\n\"", ")", "...
Searches all processes for the given PID, then returns the originating command
[ "Searches", "all", "processes", "for", "the", "given", "PID", "then", "returns", "the", "originating", "command" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/PlatformManagerDarwin.py#L407-L416
train
glitchassassin/lackey
lackey/InputEmulation.py
Mouse.moveSpeed
def moveSpeed(self, location, seconds=0.3): """ Moves cursor to specified ``Location`` over ``seconds``. If ``seconds`` is 0, moves the cursor immediately. Used for smooth somewhat-human-like motion. """ self._lock.acquire() original_location = mouse.get_position() ...
python
def moveSpeed(self, location, seconds=0.3): """ Moves cursor to specified ``Location`` over ``seconds``. If ``seconds`` is 0, moves the cursor immediately. Used for smooth somewhat-human-like motion. """ self._lock.acquire() original_location = mouse.get_position() ...
[ "def", "moveSpeed", "(", "self", ",", "location", ",", "seconds", "=", "0.3", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "original_location", "=", "mouse", ".", "get_position", "(", ")", "mouse", ".", "move", "(", "location", ".", "x", ...
Moves cursor to specified ``Location`` over ``seconds``. If ``seconds`` is 0, moves the cursor immediately. Used for smooth somewhat-human-like motion.
[ "Moves", "cursor", "to", "specified", "Location", "over", "seconds", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/InputEmulation.py#L59-L73
train
glitchassassin/lackey
lackey/InputEmulation.py
Mouse.click
def click(self, loc=None, button=mouse.LEFT): """ Clicks the specified mouse button. If ``loc`` is set, move the mouse to that Location first. Use button constants Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT """ if loc is not None: self.moveSpeed(loc) self._lock.a...
python
def click(self, loc=None, button=mouse.LEFT): """ Clicks the specified mouse button. If ``loc`` is set, move the mouse to that Location first. Use button constants Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT """ if loc is not None: self.moveSpeed(loc) self._lock.a...
[ "def", "click", "(", "self", ",", "loc", "=", "None", ",", "button", "=", "mouse", ".", "LEFT", ")", ":", "if", "loc", "is", "not", "None", ":", "self", ".", "moveSpeed", "(", "loc", ")", "self", ".", "_lock", ".", "acquire", "(", ")", "mouse", ...
Clicks the specified mouse button. If ``loc`` is set, move the mouse to that Location first. Use button constants Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT
[ "Clicks", "the", "specified", "mouse", "button", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/InputEmulation.py#L75-L86
train
glitchassassin/lackey
lackey/InputEmulation.py
Mouse.buttonDown
def buttonDown(self, button=mouse.LEFT): """ Holds down the specified mouse button. Use Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT """ self._lock.acquire() mouse.press(button) self._lock.release()
python
def buttonDown(self, button=mouse.LEFT): """ Holds down the specified mouse button. Use Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT """ self._lock.acquire() mouse.press(button) self._lock.release()
[ "def", "buttonDown", "(", "self", ",", "button", "=", "mouse", ".", "LEFT", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "mouse", ".", "press", "(", "button", ")", "self", ".", "_lock", ".", "release", "(", ")" ]
Holds down the specified mouse button. Use Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT
[ "Holds", "down", "the", "specified", "mouse", "button", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/InputEmulation.py#L87-L94
train
glitchassassin/lackey
lackey/InputEmulation.py
Mouse.buttonUp
def buttonUp(self, button=mouse.LEFT): """ Releases the specified mouse button. Use Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT """ self._lock.acquire() mouse.release(button) self._lock.release()
python
def buttonUp(self, button=mouse.LEFT): """ Releases the specified mouse button. Use Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT """ self._lock.acquire() mouse.release(button) self._lock.release()
[ "def", "buttonUp", "(", "self", ",", "button", "=", "mouse", ".", "LEFT", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "mouse", ".", "release", "(", "button", ")", "self", ".", "_lock", ".", "release", "(", ")" ]
Releases the specified mouse button. Use Mouse.LEFT, Mouse.MIDDLE, Mouse.RIGHT
[ "Releases", "the", "specified", "mouse", "button", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/InputEmulation.py#L96-L103
train
glitchassassin/lackey
lackey/InputEmulation.py
Mouse.wheel
def wheel(self, direction, steps): """ Clicks the wheel the specified number of steps in the given direction. Use Mouse.WHEEL_DOWN, Mouse.WHEEL_UP """ self._lock.acquire() if direction == 1: wheel_moved = steps elif direction == 0: wheel_moved = -...
python
def wheel(self, direction, steps): """ Clicks the wheel the specified number of steps in the given direction. Use Mouse.WHEEL_DOWN, Mouse.WHEEL_UP """ self._lock.acquire() if direction == 1: wheel_moved = steps elif direction == 0: wheel_moved = -...
[ "def", "wheel", "(", "self", ",", "direction", ",", "steps", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "if", "direction", "==", "1", ":", "wheel_moved", "=", "steps", "elif", "direction", "==", "0", ":", "wheel_moved", "=", "-", "1", ...
Clicks the wheel the specified number of steps in the given direction. Use Mouse.WHEEL_DOWN, Mouse.WHEEL_UP
[ "Clicks", "the", "wheel", "the", "specified", "number", "of", "steps", "in", "the", "given", "direction", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/InputEmulation.py#L105-L118
train
glitchassassin/lackey
lackey/InputEmulation.py
Keyboard.type
def type(self, text, delay=0.1): """ Translates a string into a series of keystrokes. Respects Sikuli special codes, like "{ENTER}". """ in_special_code = False special_code = "" modifier_held = False modifier_stuck = False modifier_codes = [] fo...
python
def type(self, text, delay=0.1): """ Translates a string into a series of keystrokes. Respects Sikuli special codes, like "{ENTER}". """ in_special_code = False special_code = "" modifier_held = False modifier_stuck = False modifier_codes = [] fo...
[ "def", "type", "(", "self", ",", "text", ",", "delay", "=", "0.1", ")", ":", "in_special_code", "=", "False", "special_code", "=", "\"\"", "modifier_held", "=", "False", "modifier_stuck", "=", "False", "modifier_codes", "=", "[", "]", "for", "i", "in", "...
Translates a string into a series of keystrokes. Respects Sikuli special codes, like "{ENTER}".
[ "Translates", "a", "string", "into", "a", "series", "of", "keystrokes", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/InputEmulation.py#L347-L385
train
glitchassassin/lackey
lackey/TemplateMatchers.py
NaiveTemplateMatcher.findBestMatch
def findBestMatch(self, needle, similarity): """ Find the best match for ``needle`` that has a similarity better than or equal to ``similarity``. Returns a tuple of ``(position, confidence)`` if a match is found, or ``None`` otherwise. *Developer's Note - Despite the name, this method actually...
python
def findBestMatch(self, needle, similarity): """ Find the best match for ``needle`` that has a similarity better than or equal to ``similarity``. Returns a tuple of ``(position, confidence)`` if a match is found, or ``None`` otherwise. *Developer's Note - Despite the name, this method actually...
[ "def", "findBestMatch", "(", "self", ",", "needle", ",", "similarity", ")", ":", "method", "=", "cv2", ".", "TM_CCOEFF_NORMED", "position", "=", "None", "match", "=", "cv2", ".", "matchTemplate", "(", "self", ".", "haystack", ",", "needle", ",", "method", ...
Find the best match for ``needle`` that has a similarity better than or equal to ``similarity``. Returns a tuple of ``(position, confidence)`` if a match is found, or ``None`` otherwise. *Developer's Note - Despite the name, this method actually returns the **first** result with enough similar...
[ "Find", "the", "best", "match", "for", "needle", "that", "has", "a", "similarity", "better", "than", "or", "equal", "to", "similarity", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/TemplateMatchers.py#L16-L43
train
glitchassassin/lackey
lackey/TemplateMatchers.py
NaiveTemplateMatcher.findAllMatches
def findAllMatches(self, needle, similarity): """ Find all matches for ``needle`` with confidence better than or equal to ``similarity``. Returns an array of tuples ``(position, confidence)`` if match(es) is/are found, or an empty array otherwise. """ positions = [] meth...
python
def findAllMatches(self, needle, similarity): """ Find all matches for ``needle`` with confidence better than or equal to ``similarity``. Returns an array of tuples ``(position, confidence)`` if match(es) is/are found, or an empty array otherwise. """ positions = [] meth...
[ "def", "findAllMatches", "(", "self", ",", "needle", ",", "similarity", ")", ":", "positions", "=", "[", "]", "method", "=", "cv2", ".", "TM_CCOEFF_NORMED", "match", "=", "cv2", ".", "matchTemplate", "(", "self", ".", "haystack", ",", "self", ".", "needl...
Find all matches for ``needle`` with confidence better than or equal to ``similarity``. Returns an array of tuples ``(position, confidence)`` if match(es) is/are found, or an empty array otherwise.
[ "Find", "all", "matches", "for", "needle", "with", "confidence", "better", "than", "or", "equal", "to", "similarity", "." ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/TemplateMatchers.py#L45-L69
train
glitchassassin/lackey
lackey/TemplateMatchers.py
PyramidTemplateMatcher.findAllMatches
def findAllMatches(self, needle, similarity): """ Finds all matches above ``similarity`` using a search pyramid to improve efficiency Pyramid implementation unashamedly stolen from https://github.com/stb-tester/stb-tester """ positions = [] # Use findBestMatch to get the best ma...
python
def findAllMatches(self, needle, similarity): """ Finds all matches above ``similarity`` using a search pyramid to improve efficiency Pyramid implementation unashamedly stolen from https://github.com/stb-tester/stb-tester """ positions = [] # Use findBestMatch to get the best ma...
[ "def", "findAllMatches", "(", "self", ",", "needle", ",", "similarity", ")", ":", "positions", "=", "[", "]", "while", "True", ":", "best_match", "=", "self", ".", "findBestMatch", "(", "needle", ",", "similarity", ")", "if", "best_match", "is", "None", ...
Finds all matches above ``similarity`` using a search pyramid to improve efficiency Pyramid implementation unashamedly stolen from https://github.com/stb-tester/stb-tester
[ "Finds", "all", "matches", "above", "similarity", "using", "a", "search", "pyramid", "to", "improve", "efficiency" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/TemplateMatchers.py#L218-L244
train
glitchassassin/lackey
lackey/TemplateMatchers.py
PyramidTemplateMatcher._build_pyramid
def _build_pyramid(self, image, levels): """ Returns a list of reduced-size images, from smallest to original size """ 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]))...
python
def _build_pyramid(self, image, levels): """ Returns a list of reduced-size images, from smallest to original size """ 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]))...
[ "def", "_build_pyramid", "(", "self", ",", "image", ",", "levels", ")", ":", "pyramid", "=", "[", "image", "]", "for", "l", "in", "range", "(", "levels", "-", "1", ")", ":", "if", "any", "(", "x", "<", "20", "for", "x", "in", "pyramid", "[", "-...
Returns a list of reduced-size images, from smallest to original size
[ "Returns", "a", "list", "of", "reduced", "-", "size", "images", "from", "smallest", "to", "original", "size" ]
7adadfacd7f45d81186710be992f5668b15399fe
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/TemplateMatchers.py#L246-L253
train
google-research/batch-ppo
agents/tools/count_weights.py
count_weights
def count_weights(scope=None, exclude=None, graph=None): """Count learnable parameters. Args: scope: Restrict the count to a variable scope. exclude: Regex to match variable names to exclude. graph: Operate on a graph other than the current default graph. Returns: Number of learnable parameters ...
python
def count_weights(scope=None, exclude=None, graph=None): """Count learnable parameters. Args: scope: Restrict the count to a variable scope. exclude: Regex to match variable names to exclude. graph: Operate on a graph other than the current default graph. Returns: Number of learnable parameters ...
[ "def", "count_weights", "(", "scope", "=", "None", ",", "exclude", "=", "None", ",", "graph", "=", "None", ")", ":", "if", "scope", ":", "scope", "=", "scope", "if", "scope", ".", "endswith", "(", "'/'", ")", "else", "scope", "+", "'/'", "graph", "...
Count learnable parameters. Args: scope: Restrict the count to a variable scope. exclude: Regex to match variable names to exclude. graph: Operate on a graph other than the current default graph. Returns: Number of learnable parameters as integer.
[ "Count", "learnable", "parameters", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/count_weights.py#L27-L48
train
google-research/batch-ppo
agents/scripts/networks.py
_custom_diag_normal_kl
def _custom_diag_normal_kl(lhs, rhs, name=None): # pylint: disable=unused-argument """Empirical KL divergence of two normals with diagonal covariance. Args: lhs: Diagonal Normal distribution. rhs: Diagonal Normal distribution. name: Name scope for the op. Returns: KL divergence from lhs to rhs....
python
def _custom_diag_normal_kl(lhs, rhs, name=None): # pylint: disable=unused-argument """Empirical KL divergence of two normals with diagonal covariance. Args: lhs: Diagonal Normal distribution. rhs: Diagonal Normal distribution. name: Name scope for the op. Returns: KL divergence from lhs to rhs....
[ "def", "_custom_diag_normal_kl", "(", "lhs", ",", "rhs", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", "or", "'kl_divergence'", ")", ":", "mean0", "=", "lhs", ".", "mean", "(", ")", "mean1", "=", "rhs", ".", "mean"...
Empirical KL divergence of two normals with diagonal covariance. Args: lhs: Diagonal Normal distribution. rhs: Diagonal Normal distribution. name: Name scope for the op. Returns: KL divergence from lhs to rhs.
[ "Empirical", "KL", "divergence", "of", "two", "normals", "with", "diagonal", "covariance", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/networks.py#L43-L64
train
google-research/batch-ppo
agents/scripts/utility.py
define_simulation_graph
def define_simulation_graph(batch_env, algo_cls, config): """Define the algorithm and environment interaction. Args: batch_env: In-graph environments object. algo_cls: Constructor of a batch algorithm. config: Configuration object for the algorithm. Returns: Object providing graph elements via a...
python
def define_simulation_graph(batch_env, algo_cls, config): """Define the algorithm and environment interaction. Args: batch_env: In-graph environments object. algo_cls: Constructor of a batch algorithm. config: Configuration object for the algorithm. Returns: Object providing graph elements via a...
[ "def", "define_simulation_graph", "(", "batch_env", ",", "algo_cls", ",", "config", ")", ":", "step", "=", "tf", ".", "Variable", "(", "0", ",", "False", ",", "dtype", "=", "tf", ".", "int32", ",", "name", "=", "'global_step'", ")", "is_training", "=", ...
Define the algorithm and environment interaction. Args: batch_env: In-graph environments object. algo_cls: Constructor of a batch algorithm. config: Configuration object for the algorithm. Returns: Object providing graph elements via attributes.
[ "Define", "the", "algorithm", "and", "environment", "interaction", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/utility.py#L31-L54
train
google-research/batch-ppo
agents/scripts/utility.py
define_batch_env
def define_batch_env(constructor, num_agents, env_processes): """Create environments and apply all desired wrappers. Args: constructor: Constructor of an OpenAI gym environment. num_agents: Number of environments to combine in the batch. env_processes: Whether to step environment in external processes....
python
def define_batch_env(constructor, num_agents, env_processes): """Create environments and apply all desired wrappers. Args: constructor: Constructor of an OpenAI gym environment. num_agents: Number of environments to combine in the batch. env_processes: Whether to step environment in external processes....
[ "def", "define_batch_env", "(", "constructor", ",", "num_agents", ",", "env_processes", ")", ":", "with", "tf", ".", "variable_scope", "(", "'environments'", ")", ":", "if", "env_processes", ":", "envs", "=", "[", "tools", ".", "wrappers", ".", "ExternalProces...
Create environments and apply all desired wrappers. Args: constructor: Constructor of an OpenAI gym environment. num_agents: Number of environments to combine in the batch. env_processes: Whether to step environment in external processes. Returns: In-graph environments object.
[ "Create", "environments", "and", "apply", "all", "desired", "wrappers", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/utility.py#L57-L77
train
google-research/batch-ppo
agents/scripts/utility.py
define_saver
def define_saver(exclude=None): """Create a saver for the variables we want to checkpoint. Args: exclude: List of regexes to match variable names to exclude. Returns: Saver object. """ variables = [] exclude = exclude or [] exclude = [re.compile(regex) for regex in exclude] for variable in tf....
python
def define_saver(exclude=None): """Create a saver for the variables we want to checkpoint. Args: exclude: List of regexes to match variable names to exclude. Returns: Saver object. """ variables = [] exclude = exclude or [] exclude = [re.compile(regex) for regex in exclude] for variable in tf....
[ "def", "define_saver", "(", "exclude", "=", "None", ")", ":", "variables", "=", "[", "]", "exclude", "=", "exclude", "or", "[", "]", "exclude", "=", "[", "re", ".", "compile", "(", "regex", ")", "for", "regex", "in", "exclude", "]", "for", "variable"...
Create a saver for the variables we want to checkpoint. Args: exclude: List of regexes to match variable names to exclude. Returns: Saver object.
[ "Create", "a", "saver", "for", "the", "variables", "we", "want", "to", "checkpoint", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/utility.py#L80-L97
train
google-research/batch-ppo
agents/scripts/utility.py
initialize_variables
def initialize_variables(sess, saver, logdir, checkpoint=None, resume=None): """Initialize or restore variables from a checkpoint if available. Args: sess: Session to initialize variables in. saver: Saver to restore variables. logdir: Directory to search for checkpoints. checkpoint: Specify what ch...
python
def initialize_variables(sess, saver, logdir, checkpoint=None, resume=None): """Initialize or restore variables from a checkpoint if available. Args: sess: Session to initialize variables in. saver: Saver to restore variables. logdir: Directory to search for checkpoints. checkpoint: Specify what ch...
[ "def", "initialize_variables", "(", "sess", ",", "saver", ",", "logdir", ",", "checkpoint", "=", "None", ",", "resume", "=", "None", ")", ":", "sess", ".", "run", "(", "tf", ".", "group", "(", "tf", ".", "local_variables_initializer", "(", ")", ",", "t...
Initialize or restore variables from a checkpoint if available. Args: sess: Session to initialize variables in. saver: Saver to restore variables. logdir: Directory to search for checkpoints. checkpoint: Specify what checkpoint name to use; defaults to most recent. resume: Whether to expect recov...
[ "Initialize", "or", "restore", "variables", "from", "a", "checkpoint", "if", "available", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/utility.py#L100-L129
train
google-research/batch-ppo
agents/scripts/utility.py
save_config
def save_config(config, logdir=None): """Save a new configuration by name. If a logging directory is specified, is will be created and the configuration will be stored there. Otherwise, a log message will be printed. Args: config: Configuration object. logdir: Location for writing summaries and checkp...
python
def save_config(config, logdir=None): """Save a new configuration by name. If a logging directory is specified, is will be created and the configuration will be stored there. Otherwise, a log message will be printed. Args: config: Configuration object. logdir: Location for writing summaries and checkp...
[ "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", ...
Save a new configuration by name. If a logging directory is specified, is will be created and the configuration will be stored there. Otherwise, a log message will be printed. Args: config: Configuration object. logdir: Location for writing summaries and checkpoints if specified. Returns: Configu...
[ "Save", "a", "new", "configuration", "by", "name", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/utility.py#L132-L159
train
google-research/batch-ppo
agents/scripts/utility.py
load_config
def load_config(logdir): # pylint: disable=missing-raises-doc """Load a configuration from the log directory. Args: logdir: The logging directory containing the configuration file. Raises: IOError: The logging directory does not contain a configuration file. Returns: Configuration object. """...
python
def load_config(logdir): # pylint: disable=missing-raises-doc """Load a configuration from the log directory. Args: logdir: The logging directory containing the configuration file. Raises: IOError: The logging directory does not contain a configuration file. Returns: Configuration object. """...
[ "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", ...
Load a configuration from the log directory. Args: logdir: The logging directory containing the configuration file. Raises: IOError: The logging directory does not contain a configuration file. Returns: Configuration object.
[ "Load", "a", "configuration", "from", "the", "log", "directory", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/utility.py#L162-L185
train
google-research/batch-ppo
agents/scripts/utility.py
set_up_logging
def set_up_logging(): """Configure the TensorFlow logger.""" tf.logging.set_verbosity(tf.logging.INFO) logging.getLogger('tensorflow').propagate = False
python
def set_up_logging(): """Configure the TensorFlow logger.""" tf.logging.set_verbosity(tf.logging.INFO) logging.getLogger('tensorflow').propagate = False
[ "def", "set_up_logging", "(", ")", ":", "tf", ".", "logging", ".", "set_verbosity", "(", "tf", ".", "logging", ".", "INFO", ")", "logging", ".", "getLogger", "(", "'tensorflow'", ")", ".", "propagate", "=", "False" ]
Configure the TensorFlow logger.
[ "Configure", "the", "TensorFlow", "logger", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/utility.py#L188-L191
train
google-research/batch-ppo
agents/scripts/visualize.py
_define_loop
def _define_loop(graph, eval_steps): """Create and configure an evaluation loop. Args: graph: Object providing graph elements via attributes. eval_steps: Number of evaluation steps per epoch. Returns: Loop object. """ loop = tools.Loop( None, graph.step, graph.should_log, graph.do_report, ...
python
def _define_loop(graph, eval_steps): """Create and configure an evaluation loop. Args: graph: Object providing graph elements via attributes. eval_steps: Number of evaluation steps per epoch. Returns: Loop object. """ loop = tools.Loop( None, graph.step, graph.should_log, graph.do_report, ...
[ "def", "_define_loop", "(", "graph", ",", "eval_steps", ")", ":", "loop", "=", "tools", ".", "Loop", "(", "None", ",", "graph", ".", "step", ",", "graph", ".", "should_log", ",", "graph", ".", "do_report", ",", "graph", ".", "force_reset", ")", "loop",...
Create and configure an evaluation loop. Args: graph: Object providing graph elements via attributes. eval_steps: Number of evaluation steps per epoch. Returns: Loop object.
[ "Create", "and", "configure", "an", "evaluation", "loop", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/visualize.py#L74-L92
train
google-research/batch-ppo
agents/scripts/visualize.py
visualize
def visualize( logdir, outdir, num_agents, num_episodes, checkpoint=None, env_processes=True): """Recover checkpoint and render videos from it. Args: logdir: Logging directory of the trained algorithm. outdir: Directory to store rendered videos in. num_agents: Number of environments to simulate...
python
def visualize( logdir, outdir, num_agents, num_episodes, checkpoint=None, env_processes=True): """Recover checkpoint and render videos from it. Args: logdir: Logging directory of the trained algorithm. outdir: Directory to store rendered videos in. num_agents: Number of environments to simulate...
[ "def", "visualize", "(", "logdir", ",", "outdir", ",", "num_agents", ",", "num_episodes", ",", "checkpoint", "=", "None", ",", "env_processes", "=", "True", ")", ":", "config", "=", "utility", ".", "load_config", "(", "logdir", ")", "with", "tf", ".", "d...
Recover checkpoint and render videos from it. Args: logdir: Logging directory of the trained algorithm. outdir: Directory to store rendered videos in. num_agents: Number of environments to simulate in parallel. num_episodes: Total number of episodes to simulate. checkpoint: Checkpoint name to loa...
[ "Recover", "checkpoint", "and", "render", "videos", "from", "it", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/visualize.py#L95-L126
train
google-research/batch-ppo
agents/scripts/visualize.py
main
def main(_): """Load a trained algorithm and render videos.""" 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( ...
python
def main(_): """Load a trained algorithm and render videos.""" 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( ...
[ "def", "main", "(", "_", ")", ":", "utility", ".", "set_up_logging", "(", ")", "if", "not", "FLAGS", ".", "logdir", "or", "not", "FLAGS", ".", "outdir", ":", "raise", "KeyError", "(", "'You must specify logging and outdirs directories.'", ")", "FLAGS", ".", ...
Load a trained algorithm and render videos.
[ "Load", "a", "trained", "algorithm", "and", "render", "videos", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/visualize.py#L129-L138
train
google-research/batch-ppo
agents/algorithms/ppo/utility.py
reinit_nested_vars
def reinit_nested_vars(variables, indices=None): """Reset all variables in a nested tuple to zeros. Args: variables: Nested tuple or list of variables. indices: Batch indices to reset, defaults to all. Returns: Operation. """ if isinstance(variables, (tuple, list)): return tf.group(*[ ...
python
def reinit_nested_vars(variables, indices=None): """Reset all variables in a nested tuple to zeros. Args: variables: Nested tuple or list of variables. indices: Batch indices to reset, defaults to all. Returns: Operation. """ if isinstance(variables, (tuple, list)): return tf.group(*[ ...
[ "def", "reinit_nested_vars", "(", "variables", ",", "indices", "=", "None", ")", ":", "if", "isinstance", "(", "variables", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "tf", ".", "group", "(", "*", "[", "reinit_nested_vars", "(", "variable",...
Reset all variables in a nested tuple to zeros. Args: variables: Nested tuple or list of variables. indices: Batch indices to reset, defaults to all. Returns: Operation.
[ "Reset", "all", "variables", "in", "a", "nested", "tuple", "to", "zeros", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/algorithms/ppo/utility.py#L28-L45
train
google-research/batch-ppo
agents/algorithms/ppo/utility.py
assign_nested_vars
def assign_nested_vars(variables, tensors, indices=None): """Assign tensors to matching nested tuple of variables. Args: variables: Nested tuple or list of variables to update. tensors: Nested tuple or list of tensors to assign. indices: Batch indices to assign to; default to all. Returns: Opera...
python
def assign_nested_vars(variables, tensors, indices=None): """Assign tensors to matching nested tuple of variables. Args: variables: Nested tuple or list of variables to update. tensors: Nested tuple or list of tensors to assign. indices: Batch indices to assign to; default to all. Returns: Opera...
[ "def", "assign_nested_vars", "(", "variables", ",", "tensors", ",", "indices", "=", "None", ")", ":", "if", "isinstance", "(", "variables", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "tf", ".", "group", "(", "*", "[", "assign_nested_vars", ...
Assign tensors to matching nested tuple of variables. Args: variables: Nested tuple or list of variables to update. tensors: Nested tuple or list of tensors to assign. indices: Batch indices to assign to; default to all. Returns: Operation.
[ "Assign", "tensors", "to", "matching", "nested", "tuple", "of", "variables", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/algorithms/ppo/utility.py#L48-L66
train
google-research/batch-ppo
agents/algorithms/ppo/utility.py
discounted_return
def discounted_return(reward, length, discount): """Discounted Monte-Carlo returns.""" 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(...
python
def discounted_return(reward, length, discount): """Discounted Monte-Carlo returns.""" 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(...
[ "def", "discounted_return", "(", "reward", ",", "length", ",", "discount", ")", ":", "timestep", "=", "tf", ".", "range", "(", "reward", ".", "shape", "[", "1", "]", ".", "value", ")", "mask", "=", "tf", ".", "cast", "(", "timestep", "[", "None", "...
Discounted Monte-Carlo returns.
[ "Discounted", "Monte", "-", "Carlo", "returns", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/algorithms/ppo/utility.py#L69-L77
train
google-research/batch-ppo
agents/algorithms/ppo/utility.py
fixed_step_return
def fixed_step_return(reward, value, length, discount, window): """N-step discounted return.""" 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.co...
python
def fixed_step_return(reward, value, length, discount, window): """N-step discounted return.""" 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.co...
[ "def", "fixed_step_return", "(", "reward", ",", "value", ",", "length", ",", "discount", ",", "window", ")", ":", "timestep", "=", "tf", ".", "range", "(", "reward", ".", "shape", "[", "1", "]", ".", "value", ")", "mask", "=", "tf", ".", "cast", "(...
N-step discounted return.
[ "N", "-", "step", "discounted", "return", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/algorithms/ppo/utility.py#L80-L91
train
google-research/batch-ppo
agents/algorithms/ppo/utility.py
lambda_return
def lambda_return(reward, value, length, discount, lambda_): """TD-lambda returns.""" 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.stac...
python
def lambda_return(reward, value, length, discount, lambda_): """TD-lambda returns.""" 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.stac...
[ "def", "lambda_return", "(", "reward", ",", "value", ",", "length", ",", "discount", ",", "lambda_", ")", ":", "timestep", "=", "tf", ".", "range", "(", "reward", ".", "shape", "[", "1", "]", ".", "value", ")", "mask", "=", "tf", ".", "cast", "(", ...
TD-lambda returns.
[ "TD", "-", "lambda", "returns", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/algorithms/ppo/utility.py#L94-L105
train
google-research/batch-ppo
agents/algorithms/ppo/utility.py
lambda_advantage
def lambda_advantage(reward, value, length, discount, gae_lambda): """Generalized Advantage Estimation.""" 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 = reward + discoun...
python
def lambda_advantage(reward, value, length, discount, gae_lambda): """Generalized Advantage Estimation.""" 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 = reward + discoun...
[ "def", "lambda_advantage", "(", "reward", ",", "value", ",", "length", ",", "discount", ",", "gae_lambda", ")", ":", "timestep", "=", "tf", ".", "range", "(", "reward", ".", "shape", "[", "1", "]", ".", "value", ")", "mask", "=", "tf", ".", "cast", ...
Generalized Advantage Estimation.
[ "Generalized", "Advantage", "Estimation", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/algorithms/ppo/utility.py#L108-L118
train
google-research/batch-ppo
agents/algorithms/ppo/utility.py
available_gpus
def available_gpus(): """List of GPU device names detected by TensorFlow.""" local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if x.device_type == 'GPU']
python
def available_gpus(): """List of GPU device names detected by TensorFlow.""" local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if x.device_type == 'GPU']
[ "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.
[ "List", "of", "GPU", "device", "names", "detected", "by", "TensorFlow", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/algorithms/ppo/utility.py#L121-L124
train
google-research/batch-ppo
agents/algorithms/ppo/utility.py
gradient_summaries
def gradient_summaries(grad_vars, groups=None, scope='gradients'): """Create histogram summaries of the gradient. Summaries can be grouped via regexes matching variables names. Args: grad_vars: List of (gradient, variable) tuples as returned by optimizers. groups: Mapping of name to regex for grouping s...
python
def gradient_summaries(grad_vars, groups=None, scope='gradients'): """Create histogram summaries of the gradient. Summaries can be grouped via regexes matching variables names. Args: grad_vars: List of (gradient, variable) tuples as returned by optimizers. groups: Mapping of name to regex for grouping s...
[ "def", "gradient_summaries", "(", "grad_vars", ",", "groups", "=", "None", ",", "scope", "=", "'gradients'", ")", ":", "groups", "=", "groups", "or", "{", "r'all'", ":", "r'.*'", "}", "grouped", "=", "collections", ".", "defaultdict", "(", "list", ")", "...
Create histogram summaries of the gradient. Summaries can be grouped via regexes matching variables names. Args: grad_vars: List of (gradient, variable) tuples as returned by optimizers. groups: Mapping of name to regex for grouping summaries. scope: Name scope for this operation. Returns: Summ...
[ "Create", "histogram", "summaries", "of", "the", "gradient", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/algorithms/ppo/utility.py#L127-L157
train
google-research/batch-ppo
agents/algorithms/ppo/utility.py
variable_summaries
def variable_summaries(vars_, groups=None, scope='weights'): """Create histogram summaries for the provided variables. Summaries can be grouped via regexes matching variables names. Args: vars_: List of variables to summarize. groups: Mapping of name to regex for grouping summaries. scope: Name scop...
python
def variable_summaries(vars_, groups=None, scope='weights'): """Create histogram summaries for the provided variables. Summaries can be grouped via regexes matching variables names. Args: vars_: List of variables to summarize. groups: Mapping of name to regex for grouping summaries. scope: Name scop...
[ "def", "variable_summaries", "(", "vars_", ",", "groups", "=", "None", ",", "scope", "=", "'weights'", ")", ":", "groups", "=", "groups", "or", "{", "r'all'", ":", "r'.*'", "}", "grouped", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", ...
Create histogram summaries for the provided variables. Summaries can be grouped via regexes matching variables names. Args: vars_: List of variables to summarize. groups: Mapping of name to regex for grouping summaries. scope: Name scope for this operation. Returns: Summary tensor.
[ "Create", "histogram", "summaries", "for", "the", "provided", "variables", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/algorithms/ppo/utility.py#L160-L189
train
google-research/batch-ppo
agents/algorithms/ppo/utility.py
set_dimension
def set_dimension(tensor, axis, value): """Set the length of a tensor along the specified dimension. Args: tensor: Tensor to define shape of. axis: Dimension to set the static shape for. value: Integer holding the length. Raises: ValueError: When the tensor already has a different length specifi...
python
def set_dimension(tensor, axis, value): """Set the length of a tensor along the specified dimension. Args: tensor: Tensor to define shape of. axis: Dimension to set the static shape for. value: Integer holding the length. Raises: ValueError: When the tensor already has a different length specifi...
[ "def", "set_dimension", "(", "tensor", ",", "axis", ",", "value", ")", ":", "shape", "=", "tensor", ".", "shape", ".", "as_list", "(", ")", "if", "shape", "[", "axis", "]", "not", "in", "(", "value", ",", "None", ")", ":", "message", "=", "'Cannot ...
Set the length of a tensor along the specified dimension. Args: tensor: Tensor to define shape of. axis: Dimension to set the static shape for. value: Integer holding the length. Raises: ValueError: When the tensor already has a different length specified.
[ "Set", "the", "length", "of", "a", "tensor", "along", "the", "specified", "dimension", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/algorithms/ppo/utility.py#L192-L208
train
google-research/batch-ppo
agents/scripts/configs.py
default
def default(): """Default configuration for PPO.""" # General algorithm = algorithms.PPO num_agents = 30 eval_episodes = 30 use_gpu = False # Environment normalize_ranges = True # Network network = networks.feed_forward_gaussian weight_summaries = dict( all=r'.*', policy=r'.*/policy/.*', val...
python
def default(): """Default configuration for PPO.""" # General algorithm = algorithms.PPO num_agents = 30 eval_episodes = 30 use_gpu = False # Environment normalize_ranges = True # Network network = networks.feed_forward_gaussian weight_summaries = dict( all=r'.*', policy=r'.*/policy/.*', val...
[ "def", "default", "(", ")", ":", "algorithm", "=", "algorithms", ".", "PPO", "num_agents", "=", "30", "eval_episodes", "=", "30", "use_gpu", "=", "False", "normalize_ranges", "=", "True", "network", "=", "networks", ".", "feed_forward_gaussian", "weight_summarie...
Default configuration for PPO.
[ "Default", "configuration", "for", "PPO", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/configs.py#L29-L57
train
google-research/batch-ppo
agents/scripts/configs.py
pendulum
def pendulum(): """Configuration for the pendulum classic control task.""" locals().update(default()) # Environment env = 'Pendulum-v0' max_length = 200 steps = 1e6 # 1M # Optimization batch_size = 20 chunk_length = 50 return locals()
python
def pendulum(): """Configuration for the pendulum classic control task.""" locals().update(default()) # Environment env = 'Pendulum-v0' max_length = 200 steps = 1e6 # 1M # Optimization batch_size = 20 chunk_length = 50 return locals()
[ "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.
[ "Configuration", "for", "the", "pendulum", "classic", "control", "task", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/configs.py#L60-L70
train
google-research/batch-ppo
agents/scripts/configs.py
cartpole
def cartpole(): """Configuration for the cart pole classic control task.""" locals().update(default()) # Environment env = 'CartPole-v1' max_length = 500 steps = 2e5 # 200k normalize_ranges = False # The env reports wrong ranges. # Network network = networks.feed_forward_categorical return locals(...
python
def cartpole(): """Configuration for the cart pole classic control task.""" locals().update(default()) # Environment env = 'CartPole-v1' max_length = 500 steps = 2e5 # 200k normalize_ranges = False # The env reports wrong ranges. # Network network = networks.feed_forward_categorical return locals(...
[ "def", "cartpole", "(", ")", ":", "locals", "(", ")", ".", "update", "(", "default", "(", ")", ")", "env", "=", "'CartPole-v1'", "max_length", "=", "500", "steps", "=", "2e5", "normalize_ranges", "=", "False", "network", "=", "networks", ".", "feed_forwa...
Configuration for the cart pole classic control task.
[ "Configuration", "for", "the", "cart", "pole", "classic", "control", "task", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/configs.py#L73-L83
train
google-research/batch-ppo
agents/scripts/configs.py
reacher
def reacher(): """Configuration for MuJoCo's reacher task.""" locals().update(default()) # Environment env = 'Reacher-v2' max_length = 1000 steps = 5e6 # 5M discount = 0.985 update_every = 60 return locals()
python
def reacher(): """Configuration for MuJoCo's reacher task.""" locals().update(default()) # Environment env = 'Reacher-v2' max_length = 1000 steps = 5e6 # 5M discount = 0.985 update_every = 60 return locals()
[ "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.
[ "Configuration", "for", "MuJoCo", "s", "reacher", "task", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/configs.py#L86-L95
train
google-research/batch-ppo
agents/scripts/configs.py
bullet_ant
def bullet_ant(): """Configuration for PyBullet's ant task.""" locals().update(default()) # Environment import pybullet_envs # noqa pylint: disable=unused-import env = 'AntBulletEnv-v0' max_length = 1000 steps = 3e7 # 30M update_every = 60 return locals()
python
def bullet_ant(): """Configuration for PyBullet's ant task.""" locals().update(default()) # Environment import pybullet_envs # noqa pylint: disable=unused-import env = 'AntBulletEnv-v0' max_length = 1000 steps = 3e7 # 30M update_every = 60 return locals()
[ "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.
[ "Configuration", "for", "PyBullet", "s", "ant", "task", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/configs.py#L151-L160
train
google-research/batch-ppo
agents/tools/batch_env.py
BatchEnv.step
def step(self, actions): """Forward a batch of actions to the wrapped environments. Args: actions: Batched action to apply to the environment. Raises: ValueError: Invalid actions. Returns: Batch of observations, rewards, and done flags. """ for index, (env, action) in enumer...
python
def step(self, actions): """Forward a batch of actions to the wrapped environments. Args: actions: Batched action to apply to the environment. Raises: ValueError: Invalid actions. Returns: Batch of observations, rewards, and done flags. """ for index, (env, action) in enumer...
[ "def", "step", "(", "self", ",", "actions", ")", ":", "for", "index", ",", "(", "env", ",", "action", ")", "in", "enumerate", "(", "zip", "(", "self", ".", "_envs", ",", "actions", ")", ")", ":", "if", "not", "env", ".", "action_space", ".", "con...
Forward a batch of actions to the wrapped environments. Args: actions: Batched action to apply to the environment. Raises: ValueError: Invalid actions. Returns: Batch of observations, rewards, and done flags.
[ "Forward", "a", "batch", "of", "actions", "to", "the", "wrapped", "environments", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/batch_env.py#L69-L99
train
google-research/batch-ppo
agents/tools/wrappers.py
ExternalProcess.call
def call(self, name, *args, **kwargs): """Asynchronously call a method of the external environment. Args: name: Name of the method to call. *args: Positional arguments to forward to the method. **kwargs: Keyword arguments to forward to the method. Returns: Promise object that block...
python
def call(self, name, *args, **kwargs): """Asynchronously call a method of the external environment. Args: name: Name of the method to call. *args: Positional arguments to forward to the method. **kwargs: Keyword arguments to forward to the method. Returns: Promise object that block...
[ "def", "call", "(", "self", ",", "name", ",", "*", "args", ",", "**", "kwargs", ")", ":", "payload", "=", "name", ",", "args", ",", "kwargs", "self", ".", "_conn", ".", "send", "(", "(", "self", ".", "_CALL", ",", "payload", ")", ")", "return", ...
Asynchronously call a method of the external environment. Args: name: Name of the method to call. *args: Positional arguments to forward to the method. **kwargs: Keyword arguments to forward to the method. Returns: Promise object that blocks and provides the return value when called.
[ "Asynchronously", "call", "a", "method", "of", "the", "external", "environment", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/wrappers.py#L363-L376
train
google-research/batch-ppo
agents/tools/wrappers.py
ExternalProcess.close
def close(self): """Send a close message to the external process and join it.""" try: self._conn.send((self._CLOSE, None)) self._conn.close() except IOError: # The connection was already closed. pass self._process.join()
python
def close(self): """Send a close message to the external process and join it.""" try: self._conn.send((self._CLOSE, None)) self._conn.close() except IOError: # The connection was already closed. pass self._process.join()
[ "def", "close", "(", "self", ")", ":", "try", ":", "self", ".", "_conn", ".", "send", "(", "(", "self", ".", "_CLOSE", ",", "None", ")", ")", "self", ".", "_conn", ".", "close", "(", ")", "except", "IOError", ":", "pass", "self", ".", "_process",...
Send a close message to the external process and join it.
[ "Send", "a", "close", "message", "to", "the", "external", "process", "and", "join", "it", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/wrappers.py#L378-L386
train
google-research/batch-ppo
agents/tools/wrappers.py
ExternalProcess.step
def step(self, action, blocking=True): """Step the environment. Args: action: The action to apply to the environment. blocking: Whether to wait for the result. Returns: Transition tuple when blocking, otherwise callable that returns the transition tuple. """ promise = self....
python
def step(self, action, blocking=True): """Step the environment. Args: action: The action to apply to the environment. blocking: Whether to wait for the result. Returns: Transition tuple when blocking, otherwise callable that returns the transition tuple. """ promise = self....
[ "def", "step", "(", "self", ",", "action", ",", "blocking", "=", "True", ")", ":", "promise", "=", "self", ".", "call", "(", "'step'", ",", "action", ")", "if", "blocking", ":", "return", "promise", "(", ")", "else", ":", "return", "promise" ]
Step the environment. Args: action: The action to apply to the environment. blocking: Whether to wait for the result. Returns: Transition tuple when blocking, otherwise callable that returns the transition tuple.
[ "Step", "the", "environment", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/wrappers.py#L388-L403
train
google-research/batch-ppo
agents/tools/wrappers.py
ExternalProcess._receive
def _receive(self): """Wait for a message from the worker process and return its payload. Raises: Exception: An exception was raised inside the worker process. KeyError: The received message is of an unknown type. Returns: Payload object of the message. """ message, payload = sel...
python
def _receive(self): """Wait for a message from the worker process and return its payload. Raises: Exception: An exception was raised inside the worker process. KeyError: The received message is of an unknown type. Returns: Payload object of the message. """ message, payload = sel...
[ "def", "_receive", "(", "self", ")", ":", "message", ",", "payload", "=", "self", ".", "_conn", ".", "recv", "(", ")", "if", "message", "==", "self", ".", "_EXCEPTION", ":", "stacktrace", "=", "payload", "raise", "Exception", "(", "stacktrace", ")", "i...
Wait for a message from the worker process and return its payload. Raises: Exception: An exception was raised inside the worker process. KeyError: The received message is of an unknown type. Returns: Payload object of the message.
[ "Wait", "for", "a", "message", "from", "the", "worker", "process", "and", "return", "its", "payload", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/wrappers.py#L421-L438
train
google-research/batch-ppo
agents/tools/wrappers.py
ExternalProcess._worker
def _worker(self, constructor, conn): """The process waits for actions and sends back environment results. Args: constructor: Constructor for the OpenAI Gym environment. conn: Connection for communication to the main process. Raises: KeyError: When receiving a message of unknown type. ...
python
def _worker(self, constructor, conn): """The process waits for actions and sends back environment results. Args: constructor: Constructor for the OpenAI Gym environment. conn: Connection for communication to the main process. Raises: KeyError: When receiving a message of unknown type. ...
[ "def", "_worker", "(", "self", ",", "constructor", ",", "conn", ")", ":", "try", ":", "env", "=", "constructor", "(", ")", "while", "True", ":", "try", ":", "if", "not", "conn", ".", "poll", "(", "0.1", ")", ":", "continue", "message", ",", "payloa...
The process waits for actions and sends back environment results. Args: constructor: Constructor for the OpenAI Gym environment. conn: Connection for communication to the main process. Raises: KeyError: When receiving a message of unknown type.
[ "The", "process", "waits", "for", "actions", "and", "sends", "back", "environment", "results", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/wrappers.py#L440-L478
train
google-research/batch-ppo
agents/tools/wrappers.py
ConvertTo32Bit.step
def step(self, action): """Forward action to the wrapped environment. Args: action: Action to apply to the environment. Raises: ValueError: Invalid action. Returns: Converted observation, converted reward, done flag, and info object. """ observ, reward, done, info = self._en...
python
def step(self, action): """Forward action to the wrapped environment. Args: action: Action to apply to the environment. Raises: ValueError: Invalid action. Returns: Converted observation, converted reward, done flag, and info object. """ observ, reward, done, info = self._en...
[ "def", "step", "(", "self", ",", "action", ")", ":", "observ", ",", "reward", ",", "done", ",", "info", "=", "self", ".", "_env", ".", "step", "(", "action", ")", "observ", "=", "self", ".", "_convert_observ", "(", "observ", ")", "reward", "=", "se...
Forward action to the wrapped environment. Args: action: Action to apply to the environment. Raises: ValueError: Invalid action. Returns: Converted observation, converted reward, done flag, and info object.
[ "Forward", "action", "to", "the", "wrapped", "environment", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/wrappers.py#L503-L518
train
google-research/batch-ppo
agents/tools/wrappers.py
ConvertTo32Bit._convert_observ
def _convert_observ(self, observ): """Convert the observation to 32 bits. Args: observ: Numpy observation. Raises: ValueError: Observation contains infinite values. Returns: Numpy observation with 32-bit data type. """ if not np.isfinite(observ).all(): raise ValueError...
python
def _convert_observ(self, observ): """Convert the observation to 32 bits. Args: observ: Numpy observation. Raises: ValueError: Observation contains infinite values. Returns: Numpy observation with 32-bit data type. """ if not np.isfinite(observ).all(): raise ValueError...
[ "def", "_convert_observ", "(", "self", ",", "observ", ")", ":", "if", "not", "np", ".", "isfinite", "(", "observ", ")", ".", "all", "(", ")", ":", "raise", "ValueError", "(", "'Infinite observation encountered.'", ")", "if", "observ", ".", "dtype", "==", ...
Convert the observation to 32 bits. Args: observ: Numpy observation. Raises: ValueError: Observation contains infinite values. Returns: Numpy observation with 32-bit data type.
[ "Convert", "the", "observation", "to", "32", "bits", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/wrappers.py#L530-L548
train
google-research/batch-ppo
agents/tools/wrappers.py
ConvertTo32Bit._convert_reward
def _convert_reward(self, reward): """Convert the reward to 32 bits. Args: reward: Numpy reward. Raises: ValueError: Rewards contain infinite values. Returns: Numpy reward with 32-bit data type. """ if not np.isfinite(reward).all(): raise ValueError('Infinite reward en...
python
def _convert_reward(self, reward): """Convert the reward to 32 bits. Args: reward: Numpy reward. Raises: ValueError: Rewards contain infinite values. Returns: Numpy reward with 32-bit data type. """ if not np.isfinite(reward).all(): raise ValueError('Infinite reward en...
[ "def", "_convert_reward", "(", "self", ",", "reward", ")", ":", "if", "not", "np", ".", "isfinite", "(", "reward", ")", ".", "all", "(", ")", ":", "raise", "ValueError", "(", "'Infinite reward encountered.'", ")", "return", "np", ".", "array", "(", "rewa...
Convert the reward to 32 bits. Args: reward: Numpy reward. Raises: ValueError: Rewards contain infinite values. Returns: Numpy reward with 32-bit data type.
[ "Convert", "the", "reward", "to", "32", "bits", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/wrappers.py#L550-L564
train
google-research/batch-ppo
agents/tools/streaming_mean.py
StreamingMean.value
def value(self): """The current value of the mean.""" return self._sum / tf.cast(self._count, self._dtype)
python
def value(self): """The current value of the mean.""" return self._sum / tf.cast(self._count, self._dtype)
[ "def", "value", "(", "self", ")", ":", "return", "self", ".", "_sum", "/", "tf", ".", "cast", "(", "self", ".", "_count", ",", "self", ".", "_dtype", ")" ]
The current value of the mean.
[ "The", "current", "value", "of", "the", "mean", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/streaming_mean.py#L42-L44
train
google-research/batch-ppo
agents/tools/streaming_mean.py
StreamingMean.submit
def submit(self, value): """Submit a single or batch tensor to refine the streaming mean.""" # Add a batch dimension if necessary. 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.ass...
python
def submit(self, value): """Submit a single or batch tensor to refine the streaming mean.""" # Add a batch dimension if necessary. 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.ass...
[ "def", "submit", "(", "self", ",", "value", ")", ":", "if", "value", ".", "shape", ".", "ndims", "==", "self", ".", "_sum", ".", "shape", ".", "ndims", ":", "value", "=", "value", "[", "None", ",", "...", "]", "return", "tf", ".", "group", "(", ...
Submit a single or batch tensor to refine the streaming mean.
[ "Submit", "a", "single", "or", "batch", "tensor", "to", "refine", "the", "streaming", "mean", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/streaming_mean.py#L51-L58
train
google-research/batch-ppo
agents/tools/streaming_mean.py
StreamingMean.clear
def clear(self): """Return the mean estimate and reset the streaming statistics.""" 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_depend...
python
def clear(self): """Return the mean estimate and reset the streaming statistics.""" 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_depend...
[ "def", "clear", "(", "self", ")", ":", "value", "=", "self", ".", "_sum", "/", "tf", ".", "cast", "(", "self", ".", "_count", ",", "self", ".", "_dtype", ")", "with", "tf", ".", "control_dependencies", "(", "[", "value", "]", ")", ":", "reset_value...
Return the mean estimate and reset the streaming statistics.
[ "Return", "the", "mean", "estimate", "and", "reset", "the", "streaming", "statistics", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/streaming_mean.py#L60-L67
train
google-research/batch-ppo
agents/tools/nested.py
zip_
def zip_(*structures, **kwargs): # pylint: disable=differing-param-doc,missing-param-doc """Combine corresponding elements in multiple nested structure to tuples. The nested structures can consist of any combination of lists, tuples, and dicts. All provided structures must have the same nesting. Args: *...
python
def zip_(*structures, **kwargs): # pylint: disable=differing-param-doc,missing-param-doc """Combine corresponding elements in multiple nested structure to tuples. The nested structures can consist of any combination of lists, tuples, and dicts. All provided structures must have the same nesting. Args: *...
[ "def", "zip_", "(", "*", "structures", ",", "**", "kwargs", ")", ":", "flatten", "=", "kwargs", ".", "pop", "(", "'flatten'", ",", "False", ")", "assert", "not", "kwargs", ",", "'zip() got unexpected keyword arguments.'", "return", "map", "(", "lambda", "*",...
Combine corresponding elements in multiple nested structure to tuples. The nested structures can consist of any combination of lists, tuples, and dicts. All provided structures must have the same nesting. Args: *structures: Nested structures. flatten: Whether to flatten the resulting structure into a tu...
[ "Combine", "corresponding", "elements", "in", "multiple", "nested", "structure", "to", "tuples", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/nested.py#L29-L50
train
google-research/batch-ppo
agents/tools/nested.py
map_
def map_(function, *structures, **kwargs): # pylint: disable=differing-param-doc,missing-param-doc """Apply a function to every element in a nested structure. If multiple structures are provided as input, their structure must match and the function will be applied to corresponding groups of elements. The neste...
python
def map_(function, *structures, **kwargs): # pylint: disable=differing-param-doc,missing-param-doc """Apply a function to every element in a nested structure. If multiple structures are provided as input, their structure must match and the function will be applied to corresponding groups of elements. The neste...
[ "def", "map_", "(", "function", ",", "*", "structures", ",", "**", "kwargs", ")", ":", "flatten", "=", "kwargs", ".", "pop", "(", "'flatten'", ",", "False", ")", "assert", "not", "kwargs", ",", "'map() got unexpected keyword arguments.'", "def", "impl", "(",...
Apply a function to every element in a nested structure. If multiple structures are provided as input, their structure must match and the function will be applied to corresponding groups of elements. The nested structure can consist of any combination of lists, tuples, and dicts. Args: function: The funct...
[ "Apply", "a", "function", "to", "every", "element", "in", "a", "nested", "structure", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/nested.py#L53-L98
train
google-research/batch-ppo
agents/tools/nested.py
flatten_
def flatten_(structure): """Combine all leaves of a nested structure into a tuple. The nested structure can consist of any combination of tuples, lists, and dicts. Dictionary keys will be discarded but values will ordered by the sorting of the keys. Args: structure: Nested structure. Returns: Fla...
python
def flatten_(structure): """Combine all leaves of a nested structure into a tuple. The nested structure can consist of any combination of tuples, lists, and dicts. Dictionary keys will be discarded but values will ordered by the sorting of the keys. Args: structure: Nested structure. Returns: Fla...
[ "def", "flatten_", "(", "structure", ")", ":", "if", "isinstance", "(", "structure", ",", "dict", ")", ":", "if", "structure", ":", "structure", "=", "zip", "(", "*", "sorted", "(", "structure", ".", "items", "(", ")", ",", "key", "=", "lambda", "x",...
Combine all leaves of a nested structure into a tuple. The nested structure can consist of any combination of tuples, lists, and dicts. Dictionary keys will be discarded but values will ordered by the sorting of the keys. Args: structure: Nested structure. Returns: Flat tuple.
[ "Combine", "all", "leaves", "of", "a", "nested", "structure", "into", "a", "tuple", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/nested.py#L101-L125
train
google-research/batch-ppo
agents/tools/nested.py
filter_
def filter_(predicate, *structures, **kwargs): # pylint: disable=differing-param-doc,missing-param-doc, too-many-branches """Select elements of a nested structure based on a predicate function. If multiple structures are provided as input, their structure must match and the function will be applied to correspo...
python
def filter_(predicate, *structures, **kwargs): # pylint: disable=differing-param-doc,missing-param-doc, too-many-branches """Select elements of a nested structure based on a predicate function. If multiple structures are provided as input, their structure must match and the function will be applied to correspo...
[ "def", "filter_", "(", "predicate", ",", "*", "structures", ",", "**", "kwargs", ")", ":", "flatten", "=", "kwargs", ".", "pop", "(", "'flatten'", ",", "False", ")", "assert", "not", "kwargs", ",", "'filter() got unexpected keyword arguments.'", "def", "impl",...
Select elements of a nested structure based on a predicate function. If multiple structures are provided as input, their structure must match and the function will be applied to corresponding groups of elements. The nested structure can consist of any combination of lists, tuples, and dicts. Args: predica...
[ "Select", "elements", "of", "a", "nested", "structure", "based", "on", "a", "predicate", "function", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/nested.py#L128-L192
train
google-research/batch-ppo
agents/tools/loop.py
Loop.add_phase
def add_phase( self, name, done, score, summary, steps, report_every=None, log_every=None, checkpoint_every=None, feed=None): """Add a phase to the loop protocol. If the model breaks long computation into multiple steps, the done tensor indicates whether the current score should be added to the...
python
def add_phase( self, name, done, score, summary, steps, report_every=None, log_every=None, checkpoint_every=None, feed=None): """Add a phase to the loop protocol. If the model breaks long computation into multiple steps, the done tensor indicates whether the current score should be added to the...
[ "def", "add_phase", "(", "self", ",", "name", ",", "done", ",", "score", ",", "summary", ",", "steps", ",", "report_every", "=", "None", ",", "log_every", "=", "None", ",", "checkpoint_every", "=", "None", ",", "feed", "=", "None", ")", ":", "done", ...
Add a phase to the loop protocol. If the model breaks long computation into multiple steps, the done tensor indicates whether the current score should be added to the mean counter. For example, in reinforcement learning we only have a valid score at the end of the episode. Score and done tensors c...
[ "Add", "a", "phase", "to", "the", "loop", "protocol", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/loop.py#L66-L106
train
google-research/batch-ppo
agents/tools/loop.py
Loop.run
def run(self, sess, saver, max_step=None): """Run the loop schedule for a specified number of steps. Call the operation of the current phase until the global step reaches the specified maximum step. Phases are repeated over and over in the order they were added. Args: sess: Session to use to...
python
def run(self, sess, saver, max_step=None): """Run the loop schedule for a specified number of steps. Call the operation of the current phase until the global step reaches the specified maximum step. Phases are repeated over and over in the order they were added. Args: sess: Session to use to...
[ "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"...
Run the loop schedule for a specified number of steps. Call the operation of the current phase until the global step reaches the specified maximum step. Phases are repeated over and over in the order they were added. Args: sess: Session to use to run the phase operation. saver: Saver used ...
[ "Run", "the", "loop", "schedule", "for", "a", "specified", "number", "of", "steps", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/loop.py#L108-L152
train
google-research/batch-ppo
agents/tools/loop.py
Loop._is_every_steps
def _is_every_steps(self, phase_step, batch, every): """Determine whether a periodic event should happen at this step. Args: phase_step: The incrementing step. batch: The number of steps progressed at once. every: The interval of the period. Returns: Boolean of whether the event sh...
python
def _is_every_steps(self, phase_step, batch, every): """Determine whether a periodic event should happen at this step. Args: phase_step: The incrementing step. batch: The number of steps progressed at once. every: The interval of the period. Returns: Boolean of whether the event sh...
[ "def", "_is_every_steps", "(", "self", ",", "phase_step", ",", "batch", ",", "every", ")", ":", "if", "not", "every", ":", "return", "False", "covered_steps", "=", "range", "(", "phase_step", ",", "phase_step", "+", "batch", ")", "return", "any", "(", "(...
Determine whether a periodic event should happen at this step. Args: phase_step: The incrementing step. batch: The number of steps progressed at once. every: The interval of the period. Returns: Boolean of whether the event should happen.
[ "Determine", "whether", "a", "periodic", "event", "should", "happen", "at", "this", "step", "." ]
3d09705977bae4e7c3eb20339a3b384d2a5531e4
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/loop.py#L154-L168
train