_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q262300
BaseAXUIElement._performAction
validation
def _performAction(self, action): """Perform the specified action.""" try: _a11y.AXUIElement._performAction(self, 'AX%s' % action) except _a11y.ErrorUnsupported as e: sierra_ver = '10.12' if mac_ver()[0] < sierra_ver: raise e else: pass
python
{ "resource": "" }
q262301
BaseAXUIElement._generateChildren
validation
def _generateChildren(self): """Generator which yields all AXChildren of the object.""" try: children = self.AXChildren except _a11y.Error: return if children: for child in children: yield child
python
{ "resource": "" }
q262302
BaseAXUIElement._generateChildrenR
validation
def _generateChildrenR(self, target=None): """Generator which recursively yields all AXChildren of the object.""" if target is None: target = self try: children = target.AXChildren except _a11y.Error: return if children: for child in children: yield child for c in self._generateChildrenR(child): yield c
python
{ "resource": "" }
q262303
BaseAXUIElement._match
validation
def _match(self, **kwargs): """Method which indicates if the object matches specified criteria. Match accepts criteria as kwargs and looks them up on attributes. Actual matching is performed with fnmatch, so shell-like wildcards work within match strings. Examples: obj._match(AXTitle='Terminal*') obj._match(AXRole='TextField', AXRoleDescription='search text field') """ for k in kwargs.keys(): try: val = getattr(self, k) except _a11y.Error: return False # Not all values may be strings (e.g. size, position) if sys.version_info[:2] <= (2, 6): if isinstance(val, basestring): if not fnmatch.fnmatch(unicode(val), kwargs[k]): return False else: if val != kwargs[k]: return False elif sys.version_info[0] == 3: if isinstance(val, str): if not fnmatch.fnmatch(val, str(kwargs[k])): return False else: if val != kwargs[k]: return False else: if isinstance(val, str) or isinstance(val, unicode): if not fnmatch.fnmatch(val, kwargs[k]): return False else: if val != kwargs[k]: return False return True
python
{ "resource": "" }
q262304
BaseAXUIElement._matchOther
validation
def _matchOther(self, obj, **kwargs): """Perform _match but on another object, not self.""" if obj is not None: # Need to check that the returned UI element wasn't destroyed first: if self._findFirstR(**kwargs): return obj._match(**kwargs) return False
python
{ "resource": "" }
q262305
BaseAXUIElement._generateFind
validation
def _generateFind(self, **kwargs): """Generator which yields matches on AXChildren.""" for needle in self._generateChildren(): if needle._match(**kwargs): yield needle
python
{ "resource": "" }
q262306
BaseAXUIElement._generateFindR
validation
def _generateFindR(self, **kwargs): """Generator which yields matches on AXChildren and their children.""" for needle in self._generateChildrenR(): if needle._match(**kwargs): yield needle
python
{ "resource": "" }
q262307
BaseAXUIElement._findAll
validation
def _findAll(self, **kwargs): """Return a list of all children that match the specified criteria.""" result = [] for item in self._generateFind(**kwargs): result.append(item) return result
python
{ "resource": "" }
q262308
BaseAXUIElement._getApplication
validation
def _getApplication(self): """Get the base application UIElement. If the UIElement is a child of the application, it will try to get the AXParent until it reaches the top application level element. """ app = self while True: try: app = app.AXParent except _a11y.ErrorUnsupported: break return app
python
{ "resource": "" }
q262309
BaseAXUIElement._getBundleId
validation
def _getBundleId(self): """Return the bundle ID of the application.""" ra = AppKit.NSRunningApplication app = ra.runningApplicationWithProcessIdentifier_( self._getPid()) return app.bundleIdentifier()
python
{ "resource": "" }
q262310
NativeUIElement.popUpItem
validation
def popUpItem(self, *args): """Return the specified item in a pop up menu.""" self.Press() time.sleep(.5) return self._menuItem(self, *args)
python
{ "resource": "" }
q262311
NativeUIElement.dragMouseButtonLeft
validation
def dragMouseButtonLeft(self, coord, dest_coord, interval=0.5): """Drag the left mouse button without modifiers pressed. Parameters: coordinates to click on screen (tuple (x, y)) dest coordinates to drag to (tuple (x, y)) interval to send event of btn down, drag and up Returns: None """ modFlags = 0 self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags, dest_coord=dest_coord) self._postQueuedEvents(interval=interval)
python
{ "resource": "" }
q262312
NativeUIElement.doubleClickDragMouseButtonLeft
validation
def doubleClickDragMouseButtonLeft(self, coord, dest_coord, interval=0.5): """Double-click and drag the left mouse button without modifiers pressed. Parameters: coordinates to double-click on screen (tuple (x, y)) dest coordinates to drag to (tuple (x, y)) interval to send event of btn down, drag and up Returns: None """ modFlags = 0 self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags, dest_coord=dest_coord) self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags, dest_coord=dest_coord, clickCount=2) self._postQueuedEvents(interval=interval)
python
{ "resource": "" }
q262313
NativeUIElement.clickMouseButtonLeft
validation
def clickMouseButtonLeft(self, coord, interval=None): """Click the left mouse button without modifiers pressed. Parameters: coordinates to click on screen (tuple (x, y)) Returns: None """ modFlags = 0 self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags) if interval: self._postQueuedEvents(interval=interval) else: self._postQueuedEvents()
python
{ "resource": "" }
q262314
NativeUIElement.clickMouseButtonRight
validation
def clickMouseButtonRight(self, coord): """Click the right mouse button without modifiers pressed. Parameters: coordinates to click on scren (tuple (x, y)) Returns: None """ modFlags = 0 self._queueMouseButton(coord, Quartz.kCGMouseButtonRight, modFlags) self._postQueuedEvents()
python
{ "resource": "" }
q262315
NativeUIElement.clickMouseButtonRightWithMods
validation
def clickMouseButtonRightWithMods(self, coord, modifiers): """Click the right mouse button with modifiers pressed. Parameters: coordinates to click; modifiers (list) Returns: None """ modFlags = self._pressModifiers(modifiers) self._queueMouseButton(coord, Quartz.kCGMouseButtonRight, modFlags) self._releaseModifiers(modifiers) self._postQueuedEvents()
python
{ "resource": "" }
q262316
NativeUIElement.leftMouseDragged
validation
def leftMouseDragged(self, stopCoord, strCoord=(0, 0), speed=1): """Click the left mouse button and drag object. Parameters: stopCoord, the position of dragging stopped strCoord, the position of dragging started (0,0) will get current position speed is mouse moving speed, 0 to unlimited Returns: None """ self._leftMouseDragged(stopCoord, strCoord, speed)
python
{ "resource": "" }
q262317
NativeUIElement.doubleClickMouse
validation
def doubleClickMouse(self, coord): """Double-click primary mouse button. Parameters: coordinates to click (assume primary is left button) Returns: None """ modFlags = 0 self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags) # This is a kludge: # If directed towards a Fusion VM the clickCount gets ignored and this # will be seen as a single click, so in sequence this will be a double- # click # Otherwise to a host app only this second one will count as a double- # click self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags, clickCount=2) self._postQueuedEvents()
python
{ "resource": "" }
q262318
NativeUIElement.tripleClickMouse
validation
def tripleClickMouse(self, coord): """Triple-click primary mouse button. Parameters: coordinates to click (assume primary is left button) Returns: None """ # Note above re: double-clicks applies to triple-clicks modFlags = 0 for i in range(2): self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags) self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags, clickCount=3) self._postQueuedEvents()
python
{ "resource": "" }
q262319
NativeUIElement.waitFor
validation
def waitFor(self, timeout, notification, **kwargs): """Generic wait for a UI event that matches the specified criteria to occur. For customization of the callback, use keyword args labeled 'callback', 'args', and 'kwargs' for the callback fn, callback args, and callback kwargs, respectively. Also note that on return, the observer-returned UI element will be included in the first argument if 'args' are given. Note also that if the UI element is destroyed, callback should not use it, otherwise the function will hang. """ return self._waitFor(timeout, notification, **kwargs)
python
{ "resource": "" }
q262320
NativeUIElement.waitForCreation
validation
def waitForCreation(self, timeout=10, notification='AXCreated'): """Convenience method to wait for creation of some UI element. Returns: The element created """ callback = AXCallbacks.returnElemCallback retelem = None args = (retelem,) return self.waitFor(timeout, notification, callback=callback, args=args)
python
{ "resource": "" }
q262321
NativeUIElement.waitForWindowToDisappear
validation
def waitForWindowToDisappear(self, winName, timeout=10): """Convenience method to wait for a window with the given name to disappear. Returns: Boolean """ callback = AXCallbacks.elemDisappearedCallback retelem = None args = (retelem, self) # For some reason for the AXUIElementDestroyed notification to fire, # we need to have a reference to it first win = self.findFirst(AXRole='AXWindow', AXTitle=winName) return self.waitFor(timeout, 'AXUIElementDestroyed', callback=callback, args=args, AXRole='AXWindow', AXTitle=winName)
python
{ "resource": "" }
q262322
NativeUIElement.waitForValueToChange
validation
def waitForValueToChange(self, timeout=10): """Convenience method to wait for value attribute of given element to change. Some types of elements (e.g. menu items) have their titles change, so this will not work for those. This seems to work best if you set the notification at the application level. Returns: Element or None """ # Want to identify that the element whose value changes matches this # object's. Unique identifiers considered include role and position # This seems to work best if you set the notification at the application # level callback = AXCallbacks.returnElemCallback retelem = None return self.waitFor(timeout, 'AXValueChanged', callback=callback, args=(retelem,))
python
{ "resource": "" }
q262323
NativeUIElement.waitForFocusedWindowToChange
validation
def waitForFocusedWindowToChange(self, nextWinName, timeout=10): """Convenience method to wait for focused window to change Returns: Boolean """ callback = AXCallbacks.returnElemCallback retelem = None return self.waitFor(timeout, 'AXFocusedWindowChanged', AXTitle=nextWinName)
python
{ "resource": "" }
q262324
removecallback
validation
def removecallback(window_name): """ Remove registered callback on window create @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @return: 1 if registration was successful, 0 if not. @rtype: integer """ if window_name in _pollEvents._callback: del _pollEvents._callback[window_name] return _remote_removecallback(window_name)
python
{ "resource": "" }
q262325
stopEventLoop
validation
def stopEventLoop(): """ Stop the current event loop if possible returns True if it expects that it was successful, False otherwise """ stopper = PyObjCAppHelperRunLoopStopper_wrap.currentRunLoopStopper() if stopper is None: if NSApp() is not None: NSApp().terminate_(None) return True return False NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( 0.0, stopper, 'performStop:', None, False) return True
python
{ "resource": "" }
q262326
main
validation
def main(port=4118, parentpid=None): """Main entry point. Parse command line options and start up a server.""" if "LDTP_DEBUG" in os.environ: _ldtp_debug = True else: _ldtp_debug = False _ldtp_debug_file = os.environ.get('LDTP_DEBUG_FILE', None) if _ldtp_debug: print("Parent PID: {}".format(int(parentpid))) if _ldtp_debug_file: with open(unicode(_ldtp_debug_file), "a") as fp: fp.write("Parent PID: {}".format(int(parentpid))) server = LDTPServer(('', port), allow_none=True, logRequests=_ldtp_debug, requestHandler=RequestHandler) server.register_introspection_functions() server.register_multicall_functions() ldtp_inst = core.Core() server.register_instance(ldtp_inst) if parentpid: thread.start_new_thread(notifyclient, (parentpid,)) try: server.serve_forever() except KeyboardInterrupt: pass except: if _ldtp_debug: print(traceback.format_exc()) if _ldtp_debug_file: with open(_ldtp_debug_file, "a") as fp: fp.write(traceback.format_exc())
python
{ "resource": "" }
q262327
LDTPServer.server_bind
validation
def server_bind(self, *args, **kwargs): '''Server Bind. Forces reuse of port.''' self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Can't use super() here since SimpleXMLRPCServer is an old-style class SimpleXMLRPCServer.server_bind(self, *args, **kwargs)
python
{ "resource": "" }
q262328
ooldtp.log
validation
def log(self, message, level=logging.DEBUG): """ Logs the message in the root logger with the log level @param message: Message to be logged @type message: string @param level: Log level, defaul DEBUG @type level: integer @return: 1 on success and 0 on error @rtype: integer """ if _ldtp_debug: print(message) self.logger.log(level, str(message)) return 1
python
{ "resource": "" }
q262329
ooldtp.stoplog
validation
def stoplog(self): """ Stop logging. @return: 1 on success and 0 on error @rtype: integer """ if self._file_logger: self.logger.removeHandler(_file_logger) self._file_logger = None return 1
python
{ "resource": "" }
q262330
ooldtp.imagecapture
validation
def imagecapture(self, window_name=None, out_file=None, x=0, y=0, width=None, height=None): """ Captures screenshot of the whole desktop or given window @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param x: x co-ordinate value @type x: integer @param y: y co-ordinate value @type y: integer @param width: width co-ordinate value @type width: integer @param height: height co-ordinate value @type height: integer @return: screenshot filename @rtype: string """ if not out_file: out_file = tempfile.mktemp('.png', 'ldtp_') else: out_file = os.path.expanduser(out_file) ### Windows compatibility if _ldtp_windows_env: if width == None: width = -1 if height == None: height = -1 if window_name == None: window_name = '' ### Windows compatibility - End data = self._remote_imagecapture(window_name, x, y, width, height) f = open(out_file, 'wb') f.write(b64decode(data)) f.close() return out_file
python
{ "resource": "" }
q262331
ooldtp.onwindowcreate
validation
def onwindowcreate(self, window_name, fn_name, *args): """ On window create, call the function with given arguments @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param fn_name: Callback function @type fn_name: function @param *args: arguments to be passed to the callback function @type *args: var args @return: 1 if registration was successful, 0 if not. @rtype: integer """ self._pollEvents._callback[window_name] = ["onwindowcreate", fn_name, args] return self._remote_onwindowcreate(window_name)
python
{ "resource": "" }
q262332
ooldtp.registerevent
validation
def registerevent(self, event_name, fn_name, *args): """ Register at-spi event @param event_name: Event name in at-spi format. @type event_name: string @param fn_name: Callback function @type fn_name: function @param *args: arguments to be passed to the callback function @type *args: var args @return: 1 if registration was successful, 0 if not. @rtype: integer """ if not isinstance(event_name, str): raise ValueError("event_name should be string") self._pollEvents._callback[event_name] = [event_name, fn_name, args] return self._remote_registerevent(event_name)
python
{ "resource": "" }
q262333
ooldtp.registerkbevent
validation
def registerkbevent(self, keys, modifiers, fn_name, *args): """ Register keystroke events @param keys: key to listen @type keys: string @param modifiers: control / alt combination using gtk MODIFIERS @type modifiers: int @param fn_name: Callback function @type fn_name: function @param *args: arguments to be passed to the callback function @type *args: var args @return: 1 if registration was successful, 0 if not. @rtype: integer """ event_name = "kbevent%s%s" % (keys, modifiers) self._pollEvents._callback[event_name] = [event_name, fn_name, args] return self._remote_registerkbevent(keys, modifiers)
python
{ "resource": "" }
q262334
ooldtp.windowuptime
validation
def windowuptime(self, window_name): """ Get window uptime @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @return: "starttime, endtime" as datetime python object """ tmp_time = self._remote_windowuptime(window_name) if tmp_time: tmp_time = tmp_time.split('-') start_time = tmp_time[0].split(' ') end_time = tmp_time[1].split(' ') _start_time = datetime.datetime(int(start_time[0]), int(start_time[1]), int(start_time[2]), int(start_time[3]), int(start_time[4]), int(start_time[5])) _end_time = datetime.datetime(int(end_time[0]), int(end_time[1]), int(end_time[2]), int(end_time[3]), int(end_time[4]), int(end_time[5])) return _start_time, _end_time return None
python
{ "resource": "" }
q262335
Value.verifyscrollbarvertical
validation
def verifyscrollbarvertical(self, window_name, object_name): """ Verify scrollbar is vertical @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ try: object_handle = self._get_object_handle(window_name, object_name) if object_handle.AXOrientation == "AXVerticalOrientation": return 1 except: pass return 0
python
{ "resource": "" }
q262336
Value.verifyscrollbarhorizontal
validation
def verifyscrollbarhorizontal(self, window_name, object_name): """ Verify scrollbar is horizontal @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ try: object_handle = self._get_object_handle(window_name, object_name) if object_handle.AXOrientation == "AXHorizontalOrientation": return 1 except: pass return 0
python
{ "resource": "" }
q262337
Value.setmax
validation
def setmax(self, window_name, object_name): """ Set max value @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) object_handle.AXValue = 1 return 1
python
{ "resource": "" }
q262338
Value.setmin
validation
def setmin(self, window_name, object_name): """ Set min value @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: 1 on success. @rtype: integer """ object_handle = self._get_object_handle(window_name, object_name) object_handle.AXValue = 0 return 1
python
{ "resource": "" }
q262339
Value.onedown
validation
def onedown(self, window_name, object_name, iterations): """ Press scrollbar down with number of iterations @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param interations: iterations to perform on slider increase @type iterations: integer @return: 1 on success. @rtype: integer """ if not self.verifyscrollbarvertical(window_name, object_name): raise LdtpServerException('Object not vertical scrollbar') object_handle = self._get_object_handle(window_name, object_name) i = 0 maxValue = 1.0 / 8 flag = False while i < iterations: if object_handle.AXValue >= 1: raise LdtpServerException('Maximum limit reached') object_handle.AXValue += maxValue time.sleep(1.0 / 100) flag = True i += 1 if flag: return 1 else: raise LdtpServerException('Unable to increase scrollbar')
python
{ "resource": "" }
q262340
Value.oneup
validation
def oneup(self, window_name, object_name, iterations): """ Press scrollbar up with number of iterations @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param interations: iterations to perform on slider increase @type iterations: integer @return: 1 on success. @rtype: integer """ if not self.verifyscrollbarvertical(window_name, object_name): raise LdtpServerException('Object not vertical scrollbar') object_handle = self._get_object_handle(window_name, object_name) i = 0 minValue = 1.0 / 8 flag = False while i < iterations: if object_handle.AXValue <= 0: raise LdtpServerException('Minimum limit reached') object_handle.AXValue -= minValue time.sleep(1.0 / 100) flag = True i += 1 if flag: return 1 else: raise LdtpServerException('Unable to decrease scrollbar')
python
{ "resource": "" }
q262341
Value.oneright
validation
def oneright(self, window_name, object_name, iterations): """ Press scrollbar right with number of iterations @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param interations: iterations to perform on slider increase @type iterations: integer @return: 1 on success. @rtype: integer """ if not self.verifyscrollbarhorizontal(window_name, object_name): raise LdtpServerException('Object not horizontal scrollbar') object_handle = self._get_object_handle(window_name, object_name) i = 0 maxValue = 1.0 / 8 flag = False while i < iterations: if object_handle.AXValue >= 1: raise LdtpServerException('Maximum limit reached') object_handle.AXValue += maxValue time.sleep(1.0 / 100) flag = True i += 1 if flag: return 1 else: raise LdtpServerException('Unable to increase scrollbar')
python
{ "resource": "" }
q262342
Value.oneleft
validation
def oneleft(self, window_name, object_name, iterations): """ Press scrollbar left with number of iterations @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param interations: iterations to perform on slider increase @type iterations: integer @return: 1 on success. @rtype: integer """ if not self.verifyscrollbarhorizontal(window_name, object_name): raise LdtpServerException('Object not horizontal scrollbar') object_handle = self._get_object_handle(window_name, object_name) i = 0 minValue = 1.0 / 8 flag = False while i < iterations: if object_handle.AXValue <= 0: raise LdtpServerException('Minimum limit reached') object_handle.AXValue -= minValue time.sleep(1.0 / 100) flag = True i += 1 if flag: return 1 else: raise LdtpServerException('Unable to decrease scrollbar')
python
{ "resource": "" }
q262343
ComboBox.getallitem
validation
def getallitem(self, window_name, object_name): """ Get all combo box item @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @return: list of string on success. @rtype: list """ object_handle = self._get_object_handle(window_name, object_name) if not object_handle.AXEnabled: raise LdtpServerException(u"Object %s state disabled" % object_name) object_handle.Press() # Required for menuitem to appear in accessibility list self.wait(1) child = None try: if not object_handle.AXChildren: raise LdtpServerException(u"Unable to find menu") # Get AXMenu children = object_handle.AXChildren[0] if not children: raise LdtpServerException(u"Unable to find menu") children = children.AXChildren items = [] for child in children: label = self._get_title(child) # Don't add empty label # Menu separator have empty label's if label: items.append(label) finally: if child: # Set it back, by clicking combo box child.Cancel() return items
python
{ "resource": "" }
q262344
MobileClientWrapper.login
validation
def login(self, username=None, password=None, android_id=None): """Authenticate the gmusicapi Mobileclient instance. Parameters: username (Optional[str]): Your Google Music username. Will be prompted if not given. password (Optional[str]): Your Google Music password. Will be prompted if not given. android_id (Optional[str]): The 16 hex digits from an Android device ID. Default: Use gmusicapi.Mobileclient.FROM_MAC_ADDRESS to create ID from computer's MAC address. Returns: ``True`` on successful login or ``False`` on unsuccessful login. """ cls_name = type(self).__name__ if username is None: username = input("Enter your Google username or email address: ") if password is None: password = getpass.getpass("Enter your Google Music password: ") if android_id is None: android_id = Mobileclient.FROM_MAC_ADDRESS try: self.api.login(username, password, android_id) except OSError: logger.exception("{} authentication failed.".format(cls_name)) if not self.is_authenticated: logger.warning("{} authentication failed.".format(cls_name)) return False logger.info("{} authentication succeeded.\n".format(cls_name)) return True
python
{ "resource": "" }
q262345
MobileClientWrapper.get_google_playlist
validation
def get_google_playlist(self, playlist): """Get playlist information of a user-generated Google Music playlist. Parameters: playlist (str): Name or ID of Google Music playlist. Names are case-sensitive. Google allows multiple playlists with the same name. If multiple playlists have the same name, the first one encountered is used. Returns: dict: The playlist dict as returned by Mobileclient.get_all_user_playlist_contents. """ logger.info("Loading playlist {0}".format(playlist)) for google_playlist in self.api.get_all_user_playlist_contents(): if google_playlist['name'] == playlist or google_playlist['id'] == playlist: return google_playlist else: logger.warning("Playlist {0} does not exist.".format(playlist)) return {}
python
{ "resource": "" }
q262346
MobileClientWrapper.get_google_playlist_songs
validation
def get_google_playlist_songs(self, playlist, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False): """Create song list from a user-generated Google Music playlist. Parameters: playlist (str): Name or ID of Google Music playlist. Names are case-sensitive. Google allows multiple playlists with the same name. If multiple playlists have the same name, the first one encountered is used. include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Musicmanager client. Patterns are Python regex patterns. Google Music songs are filtered out if the given metadata field values don't match any of the given patterns. exclude_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Musicmanager client. Patterns are Python regex patterns. Google Music songs are filtered out if the given metadata field values match any of the given patterns. all_includes (bool): If ``True``, all include_filters criteria must match to include a song. all_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song. Returns: A list of Google Music song dicts in the playlist matching criteria and a list of Google Music song dicts in the playlist filtered out using filter criteria. """ logger.info("Loading Google Music playlist songs...") google_playlist = self.get_google_playlist(playlist) if not google_playlist: return [], [] playlist_song_ids = [track['trackId'] for track in google_playlist['tracks']] playlist_songs = [song for song in self.api.get_all_songs() if song['id'] in playlist_song_ids] matched_songs, filtered_songs = filter_google_songs( playlist_songs, include_filters=include_filters, exclude_filters=exclude_filters, all_includes=all_includes, all_excludes=all_excludes ) logger.info("Filtered {0} Google playlist songs".format(len(filtered_songs))) logger.info("Loaded {0} Google playlist songs".format(len(matched_songs))) return matched_songs, filtered_songs
python
{ "resource": "" }
q262347
cast_to_list
validation
def cast_to_list(position): """Cast the positional argument at given position into a list if not already a list.""" @wrapt.decorator def wrapper(function, instance, args, kwargs): if not isinstance(args[position], list): args = list(args) args[position] = [args[position]] args = tuple(args) return function(*args, **kwargs) return wrapper
python
{ "resource": "" }
q262348
_pybossa_req
validation
def _pybossa_req(method, domain, id=None, payload=None, params={}, headers={'content-type': 'application/json'}, files=None): """ Send a JSON request. Returns True if everything went well, otherwise it returns the status code of the response. """ url = _opts['endpoint'] + '/api/' + domain if id is not None: url += '/' + str(id) if 'api_key' in _opts: params['api_key'] = _opts['api_key'] if method == 'get': r = requests.get(url, params=params) elif method == 'post': if files is None and headers['content-type'] == 'application/json': r = requests.post(url, params=params, headers=headers, data=json.dumps(payload)) else: r = requests.post(url, params=params, files=files, data=payload) elif method == 'put': r = requests.put(url, params=params, headers=headers, data=json.dumps(payload)) elif method == 'delete': r = requests.delete(url, params=params, headers=headers, data=json.dumps(payload)) if r.status_code // 100 == 2: if r.text and r.text != '""': return json.loads(r.text) else: return True else: return json.loads(r.text)
python
{ "resource": "" }
q262349
get_projects
validation
def get_projects(limit=100, offset=0, last_id=None): """Return a list of registered projects. :param limit: Number of returned items, default 100 :type limit: integer :param offset: Offset for the query, default 0 :type offset: integer :param last_id: id of the last project, used for pagination. If provided, offset is ignored :type last_id: integer :rtype: list :returns: A list of PYBOSSA Projects """ if last_id is not None: params = dict(limit=limit, last_id=last_id) else: print(OFFSET_WARNING) params = dict(limit=limit, offset=offset) try: res = _pybossa_req('get', 'project', params=params) if type(res).__name__ == 'list': return [Project(project) for project in res] else: raise TypeError except: # pragma: no cover raise
python
{ "resource": "" }
q262350
get_project
validation
def get_project(project_id): """Return a PYBOSSA Project for the project_id. :param project_id: PYBOSSA Project ID :type project_id: integer :rtype: PYBOSSA Project :returns: A PYBOSSA Project object """ try: res = _pybossa_req('get', 'project', project_id) if res.get('id'): return Project(res) else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262351
find_project
validation
def find_project(**kwargs): """Return a list with matching project arguments. :param kwargs: PYBOSSA Project members :rtype: list :returns: A list of projects that match the kwargs """ try: res = _pybossa_req('get', 'project', params=kwargs) if type(res).__name__ == 'list': return [Project(project) for project in res] else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262352
create_project
validation
def create_project(name, short_name, description): """Create a project. :param name: PYBOSSA Project Name :type name: string :param short_name: PYBOSSA Project short name or slug :type short_name: string :param description: PYBOSSA Project description :type decription: string :returns: True -- the response status code """ try: project = dict(name=name, short_name=short_name, description=description) res = _pybossa_req('post', 'project', payload=project) if res.get('id'): return Project(res) else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262353
update_project
validation
def update_project(project): """Update a project instance. :param project: PYBOSSA project :type project: PYBOSSA Project :returns: True -- the response status code """ try: project_id = project.id project = _forbidden_attributes(project) res = _pybossa_req('put', 'project', project_id, payload=project.data) if res.get('id'): return Project(res) else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262354
delete_project
validation
def delete_project(project_id): """Delete a Project with id = project_id. :param project_id: PYBOSSA Project ID :type project_id: integer :returns: True -- the response status code """ try: res = _pybossa_req('delete', 'project', project_id) if type(res).__name__ == 'bool': return True else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262355
get_categories
validation
def get_categories(limit=20, offset=0, last_id=None): """Return a list of registered categories. :param limit: Number of returned items, default 20 :type limit: integer :param offset: Offset for the query, default 0 :type offset: integer :param last_id: id of the last category, used for pagination. If provided, offset is ignored :type last_id: integer :rtype: list :returns: A list of PYBOSSA Categories """ if last_id is not None: params = dict(limit=limit, last_id=last_id) else: params = dict(limit=limit, offset=offset) print(OFFSET_WARNING) try: res = _pybossa_req('get', 'category', params=params) if type(res).__name__ == 'list': return [Category(category) for category in res] else: raise TypeError except: raise
python
{ "resource": "" }
q262356
get_category
validation
def get_category(category_id): """Return a PYBOSSA Category for the category_id. :param category_id: PYBOSSA Category ID :type category_id: integer :rtype: PYBOSSA Category :returns: A PYBOSSA Category object """ try: res = _pybossa_req('get', 'category', category_id) if res.get('id'): return Category(res) else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262357
find_category
validation
def find_category(**kwargs): """Return a list with matching Category arguments. :param kwargs: PYBOSSA Category members :rtype: list :returns: A list of project that match the kwargs """ try: res = _pybossa_req('get', 'category', params=kwargs) if type(res).__name__ == 'list': return [Category(category) for category in res] else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262358
create_category
validation
def create_category(name, description): """Create a Category. :param name: PYBOSSA Category Name :type name: string :param description: PYBOSSA Category description :type decription: string :returns: True -- the response status code """ try: category = dict(name=name, short_name=name.lower().replace(" ", ""), description=description) res = _pybossa_req('post', 'category', payload=category) if res.get('id'): return Category(res) else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262359
update_category
validation
def update_category(category): """Update a Category instance. :param category: PYBOSSA Category :type category: PYBOSSA Category :returns: True -- the response status code """ try: res = _pybossa_req('put', 'category', category.id, payload=category.data) if res.get('id'): return Category(res) else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262360
delete_category
validation
def delete_category(category_id): """Delete a Category with id = category_id. :param category_id: PYBOSSA Category ID :type category_id: integer :returns: True -- the response status code """ try: res = _pybossa_req('delete', 'category', category_id) if type(res).__name__ == 'bool': return True else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262361
get_tasks
validation
def get_tasks(project_id, limit=100, offset=0, last_id=None): """Return a list of tasks for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param limit: Number of returned items, default 100 :type limit: integer :param offset: Offset for the query, default 0 :param last_id: id of the last task, used for pagination. If provided, offset is ignored :type last_id: integer :type offset: integer :returns: True -- the response status code """ if last_id is not None: params = dict(limit=limit, last_id=last_id) else: params = dict(limit=limit, offset=offset) print(OFFSET_WARNING) params['project_id'] = project_id try: res = _pybossa_req('get', 'task', params=params) if type(res).__name__ == 'list': return [Task(task) for task in res] else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262362
find_tasks
validation
def find_tasks(project_id, **kwargs): """Return a list of matched tasks for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param kwargs: PYBOSSA Task members :type info: dict :rtype: list :returns: A list of tasks that match the kwargs """ try: kwargs['project_id'] = project_id res = _pybossa_req('get', 'task', params=kwargs) if type(res).__name__ == 'list': return [Task(task) for task in res] else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262363
create_task
validation
def create_task(project_id, info, n_answers=30, priority_0=0, quorum=0): """Create a task for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param info: PYBOSSA Project info JSON field :type info: dict :param n_answers: Number of answers or TaskRuns per task, default 30 :type n_answers: integer :param priority_0: Value between 0 and 1 indicating priority of task within Project (higher = more important), default 0.0 :type priority_0: float :param quorum: Number of times this task should be done by different users, default 0 :type quorum: integer :returns: True -- the response status code """ try: task = dict( project_id=project_id, info=info, calibration=0, priority_0=priority_0, n_answers=n_answers, quorum=quorum ) res = _pybossa_req('post', 'task', payload=task) if res.get('id'): return Task(res) else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262364
update_task
validation
def update_task(task): """Update a task for a given task ID. :param task: PYBOSSA task """ try: task_id = task.id task = _forbidden_attributes(task) res = _pybossa_req('put', 'task', task_id, payload=task.data) if res.get('id'): return Task(res) else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262365
delete_task
validation
def delete_task(task_id): """Delete a task for a given task ID. :param task: PYBOSSA task """ #: :arg task: A task try: res = _pybossa_req('delete', 'task', task_id) if type(res).__name__ == 'bool': return True else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262366
get_taskruns
validation
def get_taskruns(project_id, limit=100, offset=0, last_id=None): """Return a list of task runs for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param limit: Number of returned items, default 100 :type limit: integer :param offset: Offset for the query, default 0 :type offset: integer :param last_id: id of the last taskrun, used for pagination. If provided, offset is ignored :type last_id: integer :rtype: list :returns: A list of task runs for the given project ID """ if last_id is not None: params = dict(limit=limit, last_id=last_id) else: params = dict(limit=limit, offset=offset) print(OFFSET_WARNING) params['project_id'] = project_id try: res = _pybossa_req('get', 'taskrun', params=params) if type(res).__name__ == 'list': return [TaskRun(taskrun) for taskrun in res] else: raise TypeError except: raise
python
{ "resource": "" }
q262367
find_taskruns
validation
def find_taskruns(project_id, **kwargs): """Return a list of matched task runs for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param kwargs: PYBOSSA Task Run members :rtype: list :returns: A List of task runs that match the query members """ try: kwargs['project_id'] = project_id res = _pybossa_req('get', 'taskrun', params=kwargs) if type(res).__name__ == 'list': return [TaskRun(taskrun) for taskrun in res] else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262368
delete_taskrun
validation
def delete_taskrun(taskrun_id): """Delete the given taskrun. :param task: PYBOSSA task """ try: res = _pybossa_req('delete', 'taskrun', taskrun_id) if type(res).__name__ == 'bool': return True else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262369
get_results
validation
def get_results(project_id, limit=100, offset=0, last_id=None): """Return a list of results for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param limit: Number of returned items, default 100 :type limit: integer :param offset: Offset for the query, default 0 :param last_id: id of the last result, used for pagination. If provided, offset is ignored :type last_id: integer :type offset: integer :returns: True -- the response status code """ if last_id is not None: params = dict(limit=limit, last_id=last_id) else: params = dict(limit=limit, offset=offset) print(OFFSET_WARNING) params['project_id'] = project_id try: res = _pybossa_req('get', 'result', params=params) if type(res).__name__ == 'list': return [Result(result) for result in res] else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262370
find_results
validation
def find_results(project_id, **kwargs): """Return a list of matched results for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param kwargs: PYBOSSA Results members :type info: dict :rtype: list :returns: A list of results that match the kwargs """ try: kwargs['project_id'] = project_id res = _pybossa_req('get', 'result', params=kwargs) if type(res).__name__ == 'list': return [Result(result) for result in res] else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262371
update_result
validation
def update_result(result): """Update a result for a given result ID. :param result: PYBOSSA result """ try: result_id = result.id result = _forbidden_attributes(result) res = _pybossa_req('put', 'result', result_id, payload=result.data) if res.get('id'): return Result(res) else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262372
_forbidden_attributes
validation
def _forbidden_attributes(obj): """Return the object without the forbidden attributes.""" for key in list(obj.data.keys()): if key in list(obj.reserved_keys.keys()): obj.data.pop(key) return obj
python
{ "resource": "" }
q262373
create_helpingmaterial
validation
def create_helpingmaterial(project_id, info, media_url=None, file_path=None): """Create a helping material for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param info: PYBOSSA Helping Material info JSON field :type info: dict :param media_url: URL for a media file (image, video or audio) :type media_url: string :param file_path: File path to the local image, video or sound to upload. :type file_path: string :returns: True -- the response status code """ try: helping = dict( project_id=project_id, info=info, media_url=None, ) if file_path: files = {'file': open(file_path, 'rb')} payload = {'project_id': project_id} res = _pybossa_req('post', 'helpingmaterial', payload=payload, files=files) else: res = _pybossa_req('post', 'helpingmaterial', payload=helping) if res.get('id'): return HelpingMaterial(res) else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262374
get_helping_materials
validation
def get_helping_materials(project_id, limit=100, offset=0, last_id=None): """Return a list of helping materials for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param limit: Number of returned items, default 100 :type limit: integer :param offset: Offset for the query, default 0 :param last_id: id of the last helping material, used for pagination. If provided, offset is ignored :type last_id: integer :type offset: integer :returns: True -- the response status code """ if last_id is not None: params = dict(limit=limit, last_id=last_id) else: params = dict(limit=limit, offset=offset) print(OFFSET_WARNING) params['project_id'] = project_id try: res = _pybossa_req('get', 'helpingmaterial', params=params) if type(res).__name__ == 'list': return [HelpingMaterial(helping) for helping in res] else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262375
find_helping_materials
validation
def find_helping_materials(project_id, **kwargs): """Return a list of matched helping materials for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param kwargs: PYBOSSA HelpingMaterial members :type info: dict :rtype: list :returns: A list of helping materials that match the kwargs """ try: kwargs['project_id'] = project_id res = _pybossa_req('get', 'helpingmaterial', params=kwargs) if type(res).__name__ == 'list': return [HelpingMaterial(helping) for helping in res] else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262376
update_helping_material
validation
def update_helping_material(helpingmaterial): """Update a helping material for a given helping material ID. :param helpingmaterial: PYBOSSA helping material """ try: helpingmaterial_id = helpingmaterial.id helpingmaterial = _forbidden_attributes(helpingmaterial) res = _pybossa_req('put', 'helpingmaterial', helpingmaterial_id, payload=helpingmaterial.data) if res.get('id'): return HelpingMaterial(res) else: return res except: # pragma: no cover raise
python
{ "resource": "" }
q262377
MusicManagerWrapper.login
validation
def login(self, oauth_filename="oauth", uploader_id=None): """Authenticate the gmusicapi Musicmanager instance. Parameters: oauth_filename (str): The filename of the oauth credentials file to use/create for login. Default: ``oauth`` uploader_id (str): A unique id as a MAC address (e.g. ``'00:11:22:33:AA:BB'``). This should only be provided in cases where the default (host MAC address incremented by 1) won't work. Returns: ``True`` on successful login, ``False`` on unsuccessful login. """ cls_name = type(self).__name__ oauth_cred = os.path.join(os.path.dirname(OAUTH_FILEPATH), oauth_filename + '.cred') try: if not self.api.login(oauth_credentials=oauth_cred, uploader_id=uploader_id): try: self.api.perform_oauth(storage_filepath=oauth_cred) except OSError: logger.exception("\nUnable to login with specified oauth code.") self.api.login(oauth_credentials=oauth_cred, uploader_id=uploader_id) except (OSError, ValueError): logger.exception("{} authentication failed.".format(cls_name)) return False if not self.is_authenticated: logger.warning("{} authentication failed.".format(cls_name)) return False logger.info("{} authentication succeeded.\n".format(cls_name)) return True
python
{ "resource": "" }
q262378
MusicManagerWrapper.download
validation
def download(self, songs, template=None): """Download Google Music songs. Parameters: songs (list or dict): Google Music song dict(s). template (str): A filepath which can include template patterns. Returns: A list of result dictionaries. :: [ {'result': 'downloaded', 'id': song_id, 'filepath': downloaded[song_id]}, # downloaded {'result': 'error', 'id': song_id, 'message': error[song_id]} # error ] """ if not template: template = os.getcwd() songnum = 0 total = len(songs) results = [] errors = {} pad = len(str(total)) for result in self._download(songs, template): song_id = songs[songnum]['id'] songnum += 1 downloaded, error = result if downloaded: logger.info( "({num:>{pad}}/{total}) Successfully downloaded -- {file} ({song_id})".format( num=songnum, pad=pad, total=total, file=downloaded[song_id], song_id=song_id ) ) results.append({'result': 'downloaded', 'id': song_id, 'filepath': downloaded[song_id]}) elif error: title = songs[songnum].get('title', "<empty>") artist = songs[songnum].get('artist', "<empty>") album = songs[songnum].get('album', "<empty>") logger.info( "({num:>{pad}}/{total}) Error on download -- {title} -- {artist} -- {album} ({song_id})".format( num=songnum, pad=pad, total=total, title=title, artist=artist, album=album, song_id=song_id ) ) results.append({'result': 'error', 'id': song_id, 'message': error[song_id]}) if errors: logger.info("\n\nThe following errors occurred:\n") for filepath, e in errors.items(): logger.info("{file} | {error}".format(file=filepath, error=e)) logger.info("\nThese files may need to be synced again.\n") return results
python
{ "resource": "" }
q262379
convert_cygwin_path
validation
def convert_cygwin_path(path): """Convert Unix path from Cygwin to Windows path.""" try: win_path = subprocess.check_output(["cygpath", "-aw", path], universal_newlines=True).strip() except (FileNotFoundError, subprocess.CalledProcessError): logger.exception("Call to cygpath failed.") raise return win_path
python
{ "resource": "" }
q262380
_get_mutagen_metadata
validation
def _get_mutagen_metadata(filepath): """Get mutagen metadata dict from a file.""" try: metadata = mutagen.File(filepath, easy=True) except mutagen.MutagenError: logger.warning("Can't load {} as music file.".format(filepath)) raise return metadata
python
{ "resource": "" }
q262381
_mutagen_fields_to_single_value
validation
def _mutagen_fields_to_single_value(metadata): """Replace mutagen metadata field list values in mutagen tags with the first list value.""" return dict((k, v[0]) for k, v in metadata.items() if v)
python
{ "resource": "" }
q262382
_normalize_metadata
validation
def _normalize_metadata(metadata): """Normalize metadata to improve match accuracy.""" metadata = str(metadata) metadata = metadata.lower() metadata = re.sub(r'\/\s*\d+', '', metadata) # Remove "/<totaltracks>" from track number. metadata = re.sub(r'^0+([0-9]+)', r'\1', metadata) # Remove leading zero(s) from track number. metadata = re.sub(r'^\d+\.+', '', metadata) # Remove dots from track number. metadata = re.sub(r'[^\w\s]', '', metadata) # Remove any non-words. metadata = re.sub(r'\s+', ' ', metadata) # Reduce multiple spaces to a single space. metadata = re.sub(r'^\s+', '', metadata) # Remove leading space. metadata = re.sub(r'\s+$', '', metadata) # Remove trailing space. metadata = re.sub(r'^the\s+', '', metadata, re.I) # Remove leading "the". return metadata
python
{ "resource": "" }
q262383
compare_song_collections
validation
def compare_song_collections(src_songs, dst_songs): """Compare two song collections to find missing songs. Parameters: src_songs (list): Google Music song dicts or filepaths of local songs. dest_songs (list): Google Music song dicts or filepaths of local songs. Returns: A list of Google Music song dicts or local song filepaths from source missing in destination. """ def gather_field_values(song): return tuple((_normalize_metadata(song[field]) for field in _filter_comparison_fields(song))) dst_songs_criteria = {gather_field_values(_normalize_song(dst_song)) for dst_song in dst_songs} return [src_song for src_song in src_songs if gather_field_values(_normalize_song(src_song)) not in dst_songs_criteria]
python
{ "resource": "" }
q262384
get_supported_filepaths
validation
def get_supported_filepaths(filepaths, supported_extensions, max_depth=float('inf')): """Get filepaths with supported extensions from given filepaths. Parameters: filepaths (list or str): Filepath(s) to check. supported_extensions (tuple or str): Supported file extensions or a single file extension. max_depth (int): The depth in the directory tree to walk. A depth of '0' limits the walk to the top directory. Default: No limit. Returns: A list of supported filepaths. """ supported_filepaths = [] for path in filepaths: if os.name == 'nt' and CYGPATH_RE.match(path): path = convert_cygwin_path(path) if os.path.isdir(path): for root, __, files in walk_depth(path, max_depth): for f in files: if f.lower().endswith(supported_extensions): supported_filepaths.append(os.path.join(root, f)) elif os.path.isfile(path) and path.lower().endswith(supported_extensions): supported_filepaths.append(path) return supported_filepaths
python
{ "resource": "" }
q262385
exclude_filepaths
validation
def exclude_filepaths(filepaths, exclude_patterns=None): """Exclude file paths based on regex patterns. Parameters: filepaths (list or str): Filepath(s) to check. exclude_patterns (list): Python regex patterns to check filepaths against. Returns: A list of filepaths to include and a list of filepaths to exclude. """ if not exclude_patterns: return filepaths, [] exclude_re = re.compile("|".join(pattern for pattern in exclude_patterns)) included_songs = [] excluded_songs = [] for filepath in filepaths: if exclude_patterns and exclude_re.search(filepath): excluded_songs.append(filepath) else: included_songs.append(filepath) return included_songs, excluded_songs
python
{ "resource": "" }
q262386
_check_field_value
validation
def _check_field_value(field_value, pattern): """Check a song metadata field value for a pattern.""" if isinstance(field_value, list): return any(re.search(pattern, str(value), re.I) for value in field_value) else: return re.search(pattern, str(field_value), re.I)
python
{ "resource": "" }
q262387
_check_filters
validation
def _check_filters(song, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False): """Check a song metadata dict against a set of metadata filters.""" include = True if include_filters: if all_includes: if not all(field in song and _check_field_value(song[field], pattern) for field, pattern in include_filters): include = False else: if not any(field in song and _check_field_value(song[field], pattern) for field, pattern in include_filters): include = False if exclude_filters: if all_excludes: if all(field in song and _check_field_value(song[field], pattern) for field, pattern in exclude_filters): include = False else: if any(field in song and _check_field_value(song[field], pattern) for field, pattern in exclude_filters): include = False return include
python
{ "resource": "" }
q262388
filter_google_songs
validation
def filter_google_songs(songs, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False): """Match a Google Music song dict against a set of metadata filters. Parameters: songs (list): Google Music song dicts to filter. include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Musicmanager client. Patterns are Python regex patterns. Google Music songs are filtered out if the given metadata field values don't match any of the given patterns. exclude_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the Musicmanager client. Patterns are Python regex patterns. Google Music songs are filtered out if the given metadata field values match any of the given patterns. all_includes (bool): If ``True``, all include_filters criteria must match to include a song. all_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song. Returns: A list of Google Music song dicts matching criteria and a list of Google Music song dicts filtered out using filter criteria. :: (matched, filtered) """ matched_songs = [] filtered_songs = [] if include_filters or exclude_filters: for song in songs: if _check_filters( song, include_filters=include_filters, exclude_filters=exclude_filters, all_includes=all_includes, all_excludes=all_excludes): matched_songs.append(song) else: filtered_songs.append(song) else: matched_songs += songs return matched_songs, filtered_songs
python
{ "resource": "" }
q262389
filter_local_songs
validation
def filter_local_songs(filepaths, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False): """Match a local file against a set of metadata filters. Parameters: filepaths (list): Filepaths to filter. include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid mutagen metadata fields. Patterns are Python regex patterns. Local songs are filtered out if the given metadata field values don't match any of the given patterns. exclude_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid mutagen metadata fields. Patterns are Python regex patterns. Local songs are filtered out if the given metadata field values match any of the given patterns. all_includes (bool): If ``True``, all include_filters criteria must match to include a song. all_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song. Returns: A list of local song filepaths matching criteria and a list of local song filepaths filtered out using filter criteria. Invalid music files are also filtered out. :: (matched, filtered) """ matched_songs = [] filtered_songs = [] for filepath in filepaths: try: song = _get_mutagen_metadata(filepath) except mutagen.MutagenError: filtered_songs.append(filepath) else: if include_filters or exclude_filters: if _check_filters( song, include_filters=include_filters, exclude_filters=exclude_filters, all_includes=all_includes, all_excludes=all_excludes): matched_songs.append(filepath) else: filtered_songs.append(filepath) else: matched_songs.append(filepath) return matched_songs, filtered_songs
python
{ "resource": "" }
q262390
get_suggested_filename
validation
def get_suggested_filename(metadata): """Generate a filename for a song based on metadata. Parameters: metadata (dict): A metadata dict. Returns: A filename. """ if metadata.get('title') and metadata.get('track_number'): suggested_filename = '{track_number:0>2} {title}'.format(**metadata) elif metadata.get('title') and metadata.get('trackNumber'): suggested_filename = '{trackNumber:0>2} {title}'.format(**metadata) elif metadata.get('title') and metadata.get('tracknumber'): suggested_filename = '{tracknumber:0>2} {title}'.format(**metadata) else: suggested_filename = '00 {}'.format(metadata.get('title', '')) return suggested_filename
python
{ "resource": "" }
q262391
template_to_filepath
validation
def template_to_filepath(template, metadata, template_patterns=None): """Create directory structure and file name based on metadata template. Parameters: template (str): A filepath which can include template patterns as defined by :param template_patterns:. metadata (dict): A metadata dict. template_patterns (dict): A dict of ``pattern: field`` pairs used to replace patterns with metadata field values. Default: :const TEMPLATE_PATTERNS: Returns: A filepath. """ if template_patterns is None: template_patterns = TEMPLATE_PATTERNS metadata = metadata if isinstance(metadata, dict) else _mutagen_fields_to_single_value(metadata) assert isinstance(metadata, dict) suggested_filename = get_suggested_filename(metadata).replace('.mp3', '') if template == os.getcwd() or template == '%suggested%': filepath = suggested_filename else: t = template.replace('%suggested%', suggested_filename) filepath = _replace_template_patterns(t, metadata, template_patterns) return filepath
python
{ "resource": "" }
q262392
walk_depth
validation
def walk_depth(path, max_depth=float('inf')): """Walk a directory tree with configurable depth. Parameters: path (str): A directory path to walk. max_depth (int): The depth in the directory tree to walk. A depth of '0' limits the walk to the top directory. Default: No limit. """ start_level = os.path.abspath(path).count(os.path.sep) for dir_entry in os.walk(path): root, dirs, _ = dir_entry level = root.count(os.path.sep) - start_level yield dir_entry if level >= max_depth: dirs[:] = []
python
{ "resource": "" }
q262393
_BaseWrapper.get_local_songs
validation
def get_local_songs( filepaths, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False, exclude_patterns=None, max_depth=float('inf')): """Load songs from local filepaths. Parameters: filepaths (list or str): Filepath(s) to search for music files. include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid mutagen metadata fields. Patterns are Python regex patterns. Local songs are filtered out if the given metadata field values don't match any of the given patterns. exclude_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid mutagen metadata fields. Patterns are Python regex patterns. Local songs are filtered out if the given metadata field values match any of the given patterns. all_includes (bool): If ``True``, all include_filters criteria must match to include a song. all_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song. exclude_patterns (list or str): Pattern(s) to exclude. Patterns are Python regex patterns. Filepaths are excluded if they match any of the exclude patterns. max_depth (int): The depth in the directory tree to walk. A depth of '0' limits the walk to the top directory. Default: No limit. Returns: A list of local song filepaths matching criteria, a list of local song filepaths filtered out using filter criteria, and a list of local song filepaths excluded using exclusion criteria. """ logger.info("Loading local songs...") supported_filepaths = get_supported_filepaths(filepaths, SUPPORTED_SONG_FORMATS, max_depth=max_depth) included_songs, excluded_songs = exclude_filepaths(supported_filepaths, exclude_patterns=exclude_patterns) matched_songs, filtered_songs = filter_local_songs( included_songs, include_filters=include_filters, exclude_filters=exclude_filters, all_includes=all_includes, all_excludes=all_excludes ) logger.info("Excluded {0} local songs".format(len(excluded_songs))) logger.info("Filtered {0} local songs".format(len(filtered_songs))) logger.info("Loaded {0} local songs".format(len(matched_songs))) return matched_songs, filtered_songs, excluded_songs
python
{ "resource": "" }
q262394
_BaseWrapper.get_local_playlists
validation
def get_local_playlists(filepaths, exclude_patterns=None, max_depth=float('inf')): """Load playlists from local filepaths. Parameters: filepaths (list or str): Filepath(s) to search for music files. exclude_patterns (list or str): Pattern(s) to exclude. Patterns are Python regex patterns. Filepaths are excluded if they match any of the exclude patterns. max_depth (int): The depth in the directory tree to walk. A depth of '0' limits the walk to the top directory. Default: No limit. Returns: A list of local playlist filepaths matching criteria and a list of local playlist filepaths excluded using exclusion criteria. """ logger.info("Loading local playlists...") included_playlists = [] excluded_playlists = [] supported_filepaths = get_supported_filepaths(filepaths, SUPPORTED_PLAYLIST_FORMATS, max_depth=max_depth) included_playlists, excluded_playlists = exclude_filepaths(supported_filepaths, exclude_patterns=exclude_patterns) logger.info("Excluded {0} local playlists".format(len(excluded_playlists))) logger.info("Loaded {0} local playlists".format(len(included_playlists))) return included_playlists, excluded_playlists
python
{ "resource": "" }
q262395
_BaseWrapper.get_local_playlist_songs
validation
def get_local_playlist_songs( playlist, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False, exclude_patterns=None): """Load songs from local playlist. Parameters: playlist (str): An M3U(8) playlist filepath. include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid mutagen metadata fields. Patterns are Python regex patterns. Local songs are filtered out if the given metadata field values don't match any of the given patterns. exclude_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid mutagen metadata fields. Patterns are Python regex patterns. Local songs are filtered out if the given metadata field values match any of the given patterns. all_includes (bool): If ``True``, all include_filters criteria must match to include a song. all_excludes (bool): If ``True``, all exclude_filters criteria must match to exclude a song. exclude_patterns (list or str): Pattern(s) to exclude. Patterns are Python regex patterns. Filepaths are excluded if they match any of the exclude patterns. Returns: A list of local playlist song filepaths matching criteria, a list of local playlist song filepaths filtered out using filter criteria, and a list of local playlist song filepaths excluded using exclusion criteria. """ logger.info("Loading local playlist songs...") if os.name == 'nt' and CYGPATH_RE.match(playlist): playlist = convert_cygwin_path(playlist) filepaths = [] base_filepath = os.path.dirname(os.path.abspath(playlist)) with open(playlist) as local_playlist: for line in local_playlist.readlines(): line = line.strip() if line.lower().endswith(SUPPORTED_SONG_FORMATS): path = line if not os.path.isabs(path): path = os.path.join(base_filepath, path) if os.path.isfile(path): filepaths.append(path) supported_filepaths = get_supported_filepaths(filepaths, SUPPORTED_SONG_FORMATS) included_songs, excluded_songs = exclude_filepaths(supported_filepaths, exclude_patterns=exclude_patterns) matched_songs, filtered_songs = filter_local_songs( included_songs, include_filters=include_filters, exclude_filters=exclude_filters, all_includes=all_includes, all_excludes=all_excludes ) logger.info("Excluded {0} local playlist songs".format(len(excluded_songs))) logger.info("Filtered {0} local playlist songs".format(len(filtered_songs))) logger.info("Loaded {0} local playlist songs".format(len(matched_songs))) return matched_songs, filtered_songs, excluded_songs
python
{ "resource": "" }
q262396
Material._create_element_list_
validation
def _create_element_list_(self): """ Extract an alphabetically sorted list of elements from the compounds of the material. :returns: An alphabetically sorted list of elements. """ element_set = stoich.elements(self.compounds) return sorted(list(element_set))
python
{ "resource": "" }
q262397
MaterialPackage.get_assay
validation
def get_assay(self): """ Determine the assay of self. :returns: [mass fractions] An array containing the assay of self. """ masses_sum = sum(self.compound_masses) return [m / masses_sum for m in self.compound_masses]
python
{ "resource": "" }
q262398
MaterialPackage.get_element_masses
validation
def get_element_masses(self): """ Get the masses of elements in the package. :returns: [kg] An array of element masses. The sequence of the elements in the result corresponds with the sequence of elements in the element list of the material. """ result = [0] * len(self.material.elements) for compound in self.material.compounds: c = self.get_compound_mass(compound) f = [c * x for x in emf(compound, self.material.elements)] result = [v+f[ix] for ix, v in enumerate(result)] return result
python
{ "resource": "" }
q262399
MaterialPackage.add_to
validation
def add_to(self, other): """ Add another chem material package to this material package. :param other: The other material package. """ # Add another package. if type(other) is MaterialPackage: # Packages of the same material. if self.material == other.material: self.compound_masses += other.compound_masses # Packages of different materials. else: for compound in other.material.compounds: if compound not in self.material.compounds: raise Exception("Packages of '" + other.material.name + "' cannot be added to packages of '" + self.material.name + "'. The compound '" + compound + "' was not found in '" + self.material.name + "'.") self.add_to((compound, other.get_compound_mass(compound))) # Add the specified mass of the specified compound. elif self._is_compound_mass_tuple(other): # Added material variables. compound = other[0] compound_index = self.material.get_compound_index(compound) mass = other[1] # Create the result package. self.compound_masses[compound_index] += mass # If not one of the above, it must be an invalid argument. else: raise TypeError('Invalid addition argument.')
python
{ "resource": "" }