code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
d = self.declaration selection = self.scene.selectedItems() self._guards |= 0x01 try: d.selected_items = [item.ref().declaration for item in selection if item.ref()] finally: self._guards &= ~0x01
def on_selection_changed(self)
Callback invoked one the selection has changed.
7.171004
6.71511
1.067891
scene = self.scene scene.setBackgroundBrush(QColor.fromRgba(background.argb))
def set_background(self, background)
Set the background color of the widget.
8.821166
7.753749
1.137665
d = self.declaration factor = self.widget.transform().scale(x, y).mapRect( QRectF(0, 0, 1, 1)).width() if (d.min_zoom > factor > d.max_zoom): return self.widget.scale(x, y) return factor
def scale_view(self, x, y)
Scale the zoom but keep in in the min and max zoom bounds.
4.861115
4.395929
1.105822
self._teardown_features() focus_registry.unregister(self.widget) widget = self.widget if widget is not None: del self.widget super(QtGraphicsItem, self).destroy() # If a QWidgetAction was created for this widget, then it has # taken ownership of the widget and the widget will be deleted # when the QWidgetAction is garbage collected. This means the # superclass destroy() method must run before the reference to # the QWidgetAction is dropped. del self._widget_action
def destroy(self)
Destroy the underlying QWidget object.
7.837932
7.137409
1.098148
parent = self.parent() if parent is not None and isinstance(parent, QtGraphicsItem): return parent.widget
def parent_widget(self)
Reimplemented to only return GraphicsItems
5.487659
3.770837
1.455289
self.widget = QGraphicsProxyWidget(self.parent_widget()) widget = self.widget for item in self.child_widgets(): widget.setWidget(item) break super(QtGraphicsWidget, self).init_widget() super(QtGraphicsWidget, self).init_layout()
def init_layout(self)
Create the widget in the layout pass after the child widget has been created and intialized. We do this so the child widget does not attempt to use this proxy widget as its parent and because repositioning must be done after the widget is set.
5.268918
3.827159
1.376718
def _dequeue_update(self,change): self._update_count -=1 if self._update_count !=0: return self.update_shape(change)
Only update when all changes are done
null
null
null
def create_shape(self): d = self.declaration if d.shape1 and d.shape2: self.shape = self._do_operation(d.shape1, d.shape2) else: self.shape = None
Create the toolkit shape for the proxy object. This method is called during the top-down pass, just before the 'init_shape()' method is called. This method should create the toolkit widget and assign it to the 'widget' attribute.
null
null
null
self.visible = True if self.proxy_is_active: self.proxy.ensure_visible()
def show(self)
Ensure the widget is shown. Calling this method will also set the widget visibility to True.
9.35833
6.105377
1.532801
self.visible = False if self.proxy_is_active: self.proxy.ensure_hidden()
def hide(self)
Ensure the widget is hidden. Calling this method will also set the widget visibility to False.
10.299714
6.817924
1.510682
return self.proxy.get_item_at(coerce_point(*args, **kwargs))
def get_item_at(self, *args, **kwargs)
Return the items at the given position
11.395937
10.50145
1.085178
if not isinstance(item, GraphicsItem): item = coerce_point(item) self.proxy.center_on(item)
def center_on(self, item)
Center on the given item or point.
8.519823
6.682812
1.274886
token_stream = default_make_token_stream(self) for processor in _token_stream_processors: token_stream = processor(token_stream) return token_stream
def _custom_token_stream(self)
A wrapper for the BaseEnamlLexer's make_token_stream which allows the stream to be customized by adding "token_stream_processors". A token_stream_processor is a generator function which takes the token_stream as it's single input argument and yields each processed token as it's output. Each token will be an instance of `ply.lex.LexToken`.
4.809587
3.804077
1.264324
in_enamldef = False depth = 0 for tok in token_stream: if tok.type == 'ENAMLDEF': in_enamldef = True elif tok.type == 'INDENT': depth += 1 elif in_enamldef and tok.type == 'DEF': # Since functions are not allowed on the RHS we can # transform the token type to a NAME so it's picked up by the # parser as a decl_funcdef instead of funcdef tok.type = 'NAME' tok.value = 'func' elif tok.type == 'DEDENT': depth -= 1 if depth == 0: in_enamldef = False yield tok
def convert_enamldef_def_to_func(token_stream)
A token stream processor which processes all enaml declarative functions to allow using `def` instead of `func`. It does this by transforming DEF tokens to NAME within enamldef blocks and then changing the token value to `func`. Notes ------ Use this at your own risk! This was a feature intentionally dismissed by the author of enaml because declarative func's are not the same as python functions.
3.364263
3.157215
1.065579
super(AbstractItemView, self).child_added(child) self.get_member('_items').reset(self)
def child_added(self, child)
Reset the item cache when a child is added
13.554038
8.59464
1.577034
super(AbstractItemView, self).child_removed(child) self.get_member('_items').reset(self)
def child_removed(self, child)
Reset the item cache when a child is removed
13.671965
8.786924
1.555944
super(AbstractWidgetItemGroup, self).child_added(child) self.get_member('_items').reset(self)
def child_added(self, child)
Reset the item cache when a child is added
15.314967
10.405619
1.471798
super(AbstractWidgetItemGroup, self).child_removed(child) self.get_member('_items').reset(self)
def child_removed(self, child)
Reset the item cache when a child is removed
16.134678
10.925417
1.476802
if change['name'] in ['row', 'column']: super(AbstractWidgetItem, self)._update_proxy(change) else: self.proxy.data_changed(change)
def _update_proxy(self, change)
An observer which sends state change to the proxy.
6.317024
5.121412
1.233453
def init_signal(self): signal.signal(signal.SIGINT, lambda sig, frame: self.exit(-2)) # need a timer, so that QApplication doesn't block until a real # Qt event fires (can require mouse movement) # timer trick from http://stackoverflow.com/q/4938723/938949 timer = QtCore.QTimer() # Let the interpreter run each 200 ms: timer.timeout.connect(lambda: None) timer.start(200) # hold onto ref, so the timer doesn't get cleaned up self._sigint_timer = timer
allow clean shutdown on sigint
null
null
null
def _update_position(self, change): if change['type']!='update': return pt = gp_Pnt(self.x,self.y,self.z) if not pt.IsEqual(self.position,self.tolerance): self.position = pt
Keep position in sync with x,y,z
null
null
null
def _update_xyz(self, change): self.x,self.y,self.z = self.position.X(),self.position.Y(),self.position.Z()
Keep x,y,z in sync with position
null
null
null
def _update_state(self, change): self._block_updates = True try: self.position = self.axis.Location() self.direction = self.axis.Direction() finally: self._block_updates = False
Keep position and direction in sync with axis
null
null
null
d = self.declaration #: Create a separate viewbox self.viewbox = pg.ViewBox() #: If this is the first nested plot, use the parent right axis _plots = [c for c in self.parent().children() if isinstance(c,AbstractQtPlotItem)] i = _plots.index(self) if i==0: self.axis = self.widget.getAxis('right') self.widget.showAxis('right') else: self.axis = pg.AxisItem('right') self.axis.setZValue(-10000) #: Add new axis to scene self.widget.layout.addItem(self.axis,2,i+2) #: Link x axis to the parent axis self.viewbox.setXLink(self.widget.vb) #: Link y axis to the view self.axis.linkToView(self.viewbox) #: Set axis label self.axis.setLabel(d.label_right) #: Add Viewbox to parent scene self.parent().parent_widget().scene().addItem(self.viewbox)
def _refresh_multi_axis(self)
If linked axis' are used, setup and link them
4.724369
4.691055
1.007102
d = self.declaration if d.auto_range[0]: return self.widget.setXRange(*val,padding=0)
def set_range_x(self,val)
Set visible range of x data. Note: Padding must be 0 or it will create an infinite loop
10.066707
9.56458
1.052499
d = self.declaration if d.auto_range[1]: return self.widget.setYRange(*val,padding=0)
def set_range_y(self,val)
Set visible range of y data. Note: Padding must be 0 or it will create an infinite loop
9.890415
9.73947
1.015498
d = self.declaration if not self.is_root and d.parent.multi_axis: if self.viewbox: self.viewbox.setGeometry(self.widget.vb.sceneBoundingRect()) self.viewbox.linkedViewChanged(self.widget.vb,self.viewbox.XAxis)
def on_resized(self)
Update linked views
8.327663
7.63254
1.091074
return [self] + [c for c in self.children if isinstance(c, TreeViewColumn)]
def _get_columns(self)
List of child TreeViewColumns including this item as the first column
9.778548
4.173746
2.342871
for row, item in enumerate(self._items): item.row = row # Row is the Parent item item.column = 0 for column, item in enumerate(self._columns): item.row = self.row # Row is the Parent item item.column = column
def _update_rows(self)
Update the row and column numbers of child items.
4.527962
3.33218
1.358859
assert isinstance(declaration.proxy, ProxyAbstractItemView), \ "The model declaration must be a QtAbstractItemView subclass. " \ "Got {]".format(declaration) self.declaration = declaration
def setDeclaration(self, declaration)
Set the declaration this model will use for rendering the the headers.
16.713568
14.767411
1.131787
item = self.itemAt(index) if not item: return None d = item.declaration if role == Qt.DisplayRole: return d.text elif role == Qt.ToolTipRole: return d.tool_tip elif role == Qt.CheckStateRole and d.checkable: return d.checked and Qt.Checked or Qt.Unchecked elif role == Qt.DecorationRole and d.icon: return get_cached_qicon(d.icon) elif role == Qt.EditRole and d.editable: return d.text elif role == Qt.StatusTipRole: return d.status_tip elif role == Qt.TextAlignmentRole: h, v = d.text_alignment return TEXT_H_ALIGNMENTS[h] | TEXT_V_ALIGNMENTS[v] elif role == Qt.ForegroundRole and d.foreground: return get_cached_qcolor(d.foreground) elif role == Qt.BackgroundRole and d.background: return get_cached_qcolor(d.background) #elif role == Qt.SizeHintRole and d.minimum_size: # return d.minimum_size return None
def data(self, index, role)
Retrieve the data for the item at the given index
2.01664
1.99827
1.009193
item = self.itemAt(index) if not item: return False d = item.declaration if role == Qt.CheckStateRole: checked = value == Qt.Checked if checked != d.checked: d.checked = checked d.toggled(checked) return True elif role == Qt.EditRole: if value != d.text: d.text = value return True return super(QAbstractAtomItemModel, self).setData(index, value, role)
def setData(self, index, value, role=Qt.EditRole)
Set the data for the item at the given index to the given value.
2.729871
2.656919
1.027457
d = self.declaration if orientation == Qt.Horizontal and role == Qt.DisplayRole: try: return d.horizontal_headers[index] \ if d.horizontal_headers else index except IndexError: return index elif orientation == Qt.Vertical and role == Qt.DisplayRole: try: return d.vertical_headers[index] \ if d.vertical_headers else index except IndexError: return index return None
def headerData(self, index, orientation, role)
QHeaderView respects the following item data roles: TextAlignmentRole, DisplayRole, FontRole, DecorationRole, ForegroundRole, BackgroundRole.
2.206958
2.183593
1.0107
self.widget.activated.connect(self.on_item_activated) self.widget.clicked.connect(self.on_item_clicked) self.widget.doubleClicked.connect(self.on_item_double_clicked) self.widget.entered.connect(self.on_item_entered) self.widget.pressed.connect(self.on_item_pressed) self.widget.customContextMenuRequested.connect( self.on_custom_context_menu_requested) self.selection_model = self.widget.selectionModel() self.selection_model.selectionChanged.connect( self.on_selection_changed) self.widget.horizontalScrollBar().valueChanged.connect( self.on_horizontal_scrollbar_moved) self.widget.verticalScrollBar().valueChanged.connect( self.on_vertical_scrollbar_moved)
def init_signals(self)
Connect signals
1.654233
1.624267
1.018449
self._pending_view_refreshes +=1 timed_call(self._pending_timeout, self._refresh_layout)
def set_items(self, items)
Defer until later so the view is only updated after all items are added.
24.278887
16.176546
1.50087
self._pending_view_refreshes -= 1 if self._pending_view_refreshes == 0: try: self.model.layoutChanged.emit() self.on_layout_refreshed() except RuntimeError: # View can be destroyed before we get here return self._refresh_sizes()
def _refresh_layout(self)
This queues and batches model changes so that the layout is only refreshed after the `_pending_timeout` expires. This prevents the UI from refreshing when inserting or removing a large number of items until the operation is complete.
4.84877
3.966311
1.222489
item = parent.internalPointer() #: If the parent is None d = self.declaration if item is None else item.declaration if row < len(d._items): proxy = d._items[row].proxy assert isinstance(proxy, QtTreeViewItem), \ "Invalid item {}".format(proxy) else: proxy = d.proxy return self.createIndex(row, column, proxy)
def index(self, row, column, parent)
The index should point to the corresponding QtControl in the enaml object hierarchy.
6.050198
5.52979
1.09411
parent = self.parent() if isinstance(parent, QtTreeView): return parent return parent.view
def _default_view(self)
If this is the root item, return the parent which must be a TreeView, otherwise return the parent Item's view.
8.86251
5.676572
1.561243
return cls._name_search(five9.configuration.getWebConnectors, filters)
def search(cls, five9, filters)
Search for a record on the remote and return the results. Args: five9 (five9.Five9): The authenticated Five9 remote. filters (dict): A dictionary of search parameters, keyed by the name of the field to search. This should conform to the schema defined in :func:`five9.Five9.create_criteria`. Returns: list[BaseModel]: A list of records representing the result.
47.640556
112.821693
0.422264
results = cls.search(five9, {cls.__uid_field__: external_id}) if not results: return None return results[0]
def read(cls, five9, external_id)
Return a record singleton for the ID. Args: five9 (five9.Five9): The authenticated Five9 remote. external_id (mixed): The identified on Five9. This should be the value that is in the ``__uid_field__`` field on the record. Returns: BaseModel: The record, if found. Otherwise ``None``
4.66107
4.199783
1.109836
for key, value in data.items(): setattr(self, key, value)
def update(self, data)
Update the current memory record with the given data dict. Args: data (dict): Data dictionary to update the record attributes with.
3.311173
4.040965
0.819401
method(data) if refresh: return cls.read(method.__self__, data[cls.__uid_field__]) else: return cls.deserialize(cls._get_non_empty_dict(data))
def _call_and_serialize(cls, method, data, refresh=False)
Call the remote method with data, and optionally refresh. Args: method (callable): The method on the Authenticated Five9 object that should be called. data (dict): A data dictionary that will be passed as the first and only position argument to ``method``. refresh (bool, optional): Set to ``True`` to get the record data from Five9 before returning the record. Returns: BaseModel: The newly created record. If ``refresh`` is ``True``, this will be fetched from Five9. Otherwise, it's the data record that was sent to the server.
7.575765
11.016932
0.687647
filters = filters.get(cls.__uid_field__) if not filters: filters = '.*' elif not isinstance(filters, string_types): filters = r'(%s)' % ('|'.join(filters)) return filters
def _get_name_filters(cls, filters)
Return a regex filter for the UID column only.
4.866127
3.207103
1.517297
res = {} for key, value in mapping.items(): if hasattr(value, 'items'): value = cls._get_non_empty_dict(value) elif isinstance(value, list): value = cls._get_non_empty_list(value) if value not in [[], {}, None]: res[key] = value return res
def _get_non_empty_dict(cls, mapping)
Return the mapping without any ``None`` values (recursive).
2.202788
2.132175
1.033118
res = [] for value in iter: if hasattr(value, 'items'): value = cls._get_non_empty_dict(value) or None if value is not None: res.append(value) return res
def _get_non_empty_list(cls, iter)
Return a list of the input, excluding all ``None`` values.
2.984819
2.841271
1.050523
filters = cls._get_name_filters(filters) return [ cls.deserialize(cls._zeep_to_dict(row)) for row in method(filters) ]
def _name_search(cls, method, filters)
Helper for search methods that use name filters. Args: method (callable): The Five9 API method to call with the name filters. filters (dict): A dictionary of search parameters, keyed by the name of the field to search. This should conform to the schema defined in :func:`five9.Five9.create_criteria`. Returns: list[BaseModel]: A list of records representing the result.
8.111035
9.972805
0.813315
res = serialize_object(obj) res = cls._get_non_empty_dict(res) return res
def _zeep_to_dict(cls, obj)
Convert a zeep object to a dictionary.
8.650144
7.15954
1.208198
if not self._props.get(key): raise KeyError( 'The field "%s" does not exist on "%s"' % ( key, self.__class__.__name__, ), )
def __check_field(self, key)
Raises a KeyError if the field doesn't exist.
4.399801
3.730293
1.179479
supervisor = self._cached_client('supervisor') if not self._api_supervisor_session: self._api_supervisor_session = self.__create_supervisor_session( supervisor, ) return supervisor
def supervisor(self)
Return an authenticated connection for use, open new if required. Returns: SupervisorWebService: New or existing session with the Five9 Statistics API.
7.518207
6.887951
1.091501
ordered = OrderedDict() field_mappings = [] for key, value in record.items(): ordered[key] = value field_mappings.append({ 'columnNumber': len(ordered), # Five9 is not zero indexed. 'fieldName': key, 'key': key in keys, }) return { 'field_mappings': field_mappings, 'data': ordered, 'fields': list(ordered.values()), }
def create_mapping(record, keys)
Create a field mapping for use in API updates and creates. Args: record (BaseModel): Record that should be mapped. keys (list[str]): Fields that should be mapped as keys. Returns: dict: Dictionary with keys: * ``field_mappings``: Field mappings as required by API. * ``data``: Ordered data dictionary for input record.
5.310137
4.74654
1.118739
data = [i['values']['data'] for i in records] return [ {fields[idx]: row for idx, row in enumerate(d)} for d in data ]
def parse_response(fields, records)
Parse an API response into usable objects. Args: fields (list[str]): List of strings indicating the fields that are represented in the records, in the order presented in the records.:: [ 'number1', 'number2', 'number3', 'first_name', 'last_name', 'company', 'street', 'city', 'state', 'zip', ] records (list[dict]): A really crappy data structure representing records as returned by Five9:: [ { 'values': { 'data': [ '8881234567', None, None, 'Dave', 'Lasley', 'LasLabs Inc', None, 'Las Vegas', 'NV', '89123', ] } } ] Returns: list[dict]: List of parsed records.
5.744274
5.970528
0.962105
criteria = [] for name, value in query.items(): if isinstance(value, list): for inner_value in value: criteria += cls.create_criteria({name: inner_value}) else: criteria.append({ 'criteria': { 'field': name, 'value': value, }, }) return criteria or None
def create_criteria(cls, query)
Return a criteria from a dictionary containing a query. Query should be a dictionary, keyed by field name. If the value is a list, it will be divided into multiple criteria as required.
2.602664
2.433412
1.069553
return zeep.Client( wsdl % quote(self.username), transport=zeep.Transport( session=self._get_authenticated_session(), ), )
def _get_authenticated_client(self, wsdl)
Return an authenticated SOAP client. Returns: zeep.Client: Authenticated API client.
6.035049
6.215855
0.970912
session = requests.Session() session.auth = self.auth return session
def _get_authenticated_session(self)
Return an authenticated requests session. Returns: requests.Session: Authenticated session for use.
4.849268
5.995872
0.808768
session_params = { 'forceLogoutSession': self.force_logout_session, 'rollingPeriod': self.rolling_period, 'statisticsRange': self.statistics_range, 'shiftStart': self.__to_milliseconds( self.shift_start_hour, ), 'timeZone': self.__to_milliseconds( self.time_zone_offset, ), } supervisor.setSessionParameters(session_params) return session_params
def __create_supervisor_session(self, supervisor)
Create a new session on the supervisor service. This is required in order to use most methods for the supervisor, so it is called implicitly when generating a supervisor session.
4.835426
4.861605
0.994615
def wrapper(self, *args, **kwargs): if self.__model__ is None: raise ValidationError( 'You cannot perform CRUD operations without selecting a ' 'model first.', ) return method(self, *args, **kwargs) return wrapper
def model(method)
Use this to decorate methods that expect a model.
4.131547
3.555115
1.162142
def wrapper(self, *args, **kwargs): if self.__records__ is None: raise ValidationError( 'There are no records in the set.', ) return method(self, *args, **kwargs) return Api.model(wrapper)
def recordset(method)
Use this to decorate methods that expect a record set.
5.291436
5.216301
1.014404
self.__model__.create(self.__five9__, data) if refresh: return self.read(data[self.__model__.__name__]) else: return self.new(data)
def create(self, data, refresh=False)
Create the data on the remote, optionally refreshing.
10.550447
10.997156
0.95938
data = self.__model__._get_non_empty_dict(data) return self.__class__( self.__five9__, self.__model__, records=[self.__model__.deserialize(data)], )
def new(self, data)
Create a new memory record, but do not create on the remote.
12.530839
11.450353
1.094363
records = self.__model__.search(self.__five9__, filters) return self.__class__( self.__five9__, self.__model__, records, )
def search(self, filters)
Search Five9 given a filter. Args: filters (dict): A dictionary of search strings, keyed by the name of the field to search. Returns: Environment: An environment representing the recordset.
13.994923
10.548048
1.326778
return cls._call_and_serialize( five9.configuration.createDisposition, data, refresh, )
def create(cls, five9, data, refresh=False)
Create a record on Five9. Args: five9 (five9.Five9): The authenticated Five9 remote. data (dict): A data dictionary that can be fed to ``deserialize``. refresh (bool, optional): Set to ``True`` to get the record data from Five9 before returning the record. Returns: BaseModel: The newly created record. If ``refresh`` is ``True``, this will be fetched from Five9. Otherwise, it's the data record that was sent to the server.
21.848698
39.780186
0.549236
return cls._name_search(five9.configuration.getDispositions, filters)
def search(cls, five9, filters)
Search for a record on the remote and return the results. Args: five9 (five9.Five9): The authenticated Five9 remote. filters (dict): A dictionary of search parameters, keyed by the name of the field to search. This should conform to the schema defined in :func:`five9.Five9.create_criteria`. Returns: list[BaseModel]: A list of records representing the result.
36.524452
96.203506
0.379658
def check(cls, *args, **kwargs): if cls.authenticated: return meth(cls, *args, **kwargs) raise Error("Authentication required") return check
def authentication_required(meth)
Simple class method decorator. Checks if the client is currently connected. :param meth: the original called method
4.590062
4.705193
0.975531
buf = b"" if len(self.__read_buffer): limit = ( size if size <= len(self.__read_buffer) else len(self.__read_buffer) ) buf = self.__read_buffer[:limit] self.__read_buffer = self.__read_buffer[limit:] size -= limit if not size: return buf try: buf += self.sock.recv(size) except (socket.timeout, ssl.SSLError): raise Error("Failed to read %d bytes from the server" % size) self.__dprint(buf) return buf
def __read_block(self, size)
Read a block of 'size' bytes from the server. An internal buffer is used to read data from the server. If enough data is available from it, we return that data. Eventually, we try to grab the missing part from the server for Client.read_timeout seconds. If no data can be retrieved, it is considered as a fatal error and an 'Error' exception is raised. :param size: number of bytes to read :rtype: string :returns: the read block (can be empty)
2.891294
2.932937
0.985802
ret = b"" while True: try: pos = self.__read_buffer.index(CRLF) ret = self.__read_buffer[:pos] self.__read_buffer = self.__read_buffer[pos + len(CRLF):] break except ValueError: pass try: nval = self.sock.recv(self.read_size) self.__dprint(nval) if not len(nval): break self.__read_buffer += nval except (socket.timeout, ssl.SSLError): raise Error("Failed to read data from the server") if len(ret): m = self.__size_expr.match(ret) if m: raise Literal(int(m.group(1))) m = self.__respcode_expr.match(ret) if m: if m.group(1) == b"BYE": raise Error("Connection closed by server") if m.group(1) == b"NO": self.__parse_error(m.group(2)) raise Response(m.group(1), m.group(2)) return ret
def __read_line(self)
Read one line from the server. An internal buffer is used to read data from the server (blocks of Client.read_size bytes). If the buffer is not empty, we try to find an entire line to return. If we failed, we try to read new content from the server for Client.read_timeout seconds. If no data can be retrieved, it is considered as a fatal error and an 'Error' exception is raised. :rtype: string :return: the read line
2.955604
2.886984
1.023769
resp, code, data = (b"", None, None) cpt = 0 while True: try: line = self.__read_line() except Response as inst: code = inst.code data = inst.data break except Literal as inst: resp += self.__read_block(inst.value) if not resp.endswith(CRLF): resp += self.__read_line() + CRLF continue if not len(line): continue resp += line + CRLF cpt += 1 if nblines != -1 and cpt == nblines: break return (code, data, resp)
def __read_response(self, nblines=-1)
Read a response from the server. In the usual case, we read lines until we find one that looks like a response (OK|NO|BYE\s*(.+)?). If *nblines* > 0, we read excactly nblines before returning. :param nblines: number of lines to read (default : -1) :rtype: tuple :return: a tuple of the form (code, data, response). If nblines is provided, code and data can be equal to None.
3.59753
3.422733
1.05107
ret = [] for a in args: if isinstance(a, six.binary_type): if self.__size_expr.match(a): ret += [a] else: ret += [b'"' + a + b'"'] continue ret += [bytes(str(a).encode("utf-8"))] return ret
def __prepare_args(self, args)
Format command arguments before sending them. Command arguments of type string must be quoted, the only exception concerns size indication (of the form {\d\+?}). :param args: list of arguments :return: a list for transformed arguments
3.886076
3.482639
1.115843
tosend = name.encode("utf-8") if args: tosend += b" " + b" ".join(self.__prepare_args(args)) self.__dprint(b"Command: " + tosend) self.sock.sendall(tosend + CRLF) if extralines: for l in extralines: self.sock.sendall(l + CRLF) code, data, content = self.__read_response(nblines) if isinstance(code, six.binary_type): code = code.decode("utf-8") if isinstance(data, six.binary_type): data = data.decode("utf-8") if withcontent: return (code, data, content) return (code, data)
def __send_command( self, name, args=None, withcontent=False, extralines=None, nblines=-1)
Send a command to the server. If args is not empty, we concatenate the given command with the content of this list. If extralines is not empty, they are sent one by one to the server. (CLRF are automatically appended to them) We wait for a response just after the command has been sent. :param name: the command to sent :param args: a list of arguments for this command :param withcontent: tells the function to return the server's response or not :param extralines: a list of extra lines to sent after the command :param nblines: the number of response lines to read (all by default) :returns: a tuple of the form (code, data[, response])
2.353156
2.495883
0.942815
m = self.__size_expr.match(text) if m is not None: self.errcode = b"" self.errmsg = self.__read_block(int(m.group(1)) + 2) return m = self.__error_expr.match(text) if m is None: raise Error("Bad error message") if m.group(1) is not None: self.errcode = m.group(1).strip(b"()") else: self.errcode = b"" self.errmsg = m.group(2).strip(b'"')
def __parse_error(self, text)
Parse an error received from the server. if text corresponds to a size indication, we grab the remaining content from the server. Otherwise, we try to match an error of the form \(\w+\)?\s*".+" On succes, the two public members errcode and errmsg are filled with the parsing results. :param text: the response to parse
3.225209
2.656428
1.214115
if isinstance(login, six.text_type): login = login.encode("utf-8") if isinstance(password, six.text_type): password = password.encode("utf-8") params = base64.b64encode(b'\0'.join([authz_id, login, password])) code, data = self.__send_command("AUTHENTICATE", [b"PLAIN", params]) if code == "OK": return True return False
def _plain_authentication(self, login, password, authz_id=b"")
SASL PLAIN authentication :param login: username :param password: clear password :return: True on success, False otherwise.
2.578613
2.500327
1.031311
extralines = [b'"%s"' % base64.b64encode(login.encode("utf-8")), b'"%s"' % base64.b64encode(password.encode("utf-8"))] code, data = self.__send_command("AUTHENTICATE", [b"LOGIN"], extralines=extralines) if code == "OK": return True return False
def _login_authentication(self, login, password, authz_id="")
SASL LOGIN authentication :param login: username :param password: clear password :return: True on success, False otherwise.
3.581429
3.526067
1.015701
code, data, challenge = \ self.__send_command("AUTHENTICATE", [b"DIGEST-MD5"], withcontent=True, nblines=1) dmd5 = DigestMD5(challenge, "sieve/%s" % self.srvaddr) code, data, challenge = self.__send_command( '"%s"' % dmd5.response(login, password, authz_id), withcontent=True, nblines=1 ) if not challenge: return False if not dmd5.check_last_challenge(login, password, challenge): self.errmsg = "Bad challenge received from server" return False code, data = self.__send_command('""') if code == "OK": return True return False
def _digest_md5_authentication(self, login, password, authz_id="")
SASL DIGEST-MD5 authentication :param login: username :param password: clear password :return: True on success, False otherwise.
5.481914
5.52274
0.992608
if "SASL" not in self.__capabilities: raise Error("SASL not supported by the server") srv_mechanisms = self.get_sasl_mechanisms() if authmech is None or authmech not in SUPPORTED_AUTH_MECHS: mech_list = SUPPORTED_AUTH_MECHS else: mech_list = [authmech] for mech in mech_list: if mech not in srv_mechanisms: continue mech = mech.lower().replace("-", "_") auth_method = getattr(self, "_%s_authentication" % mech) if auth_method(login, password, authz_id): self.authenticated = True return True return False self.errmsg = b"No suitable mechanism found" return False
def __authenticate(self, login, password, authz_id=b"", authmech=None)
AUTHENTICATE command Actually, it is just a wrapper to the real commands (one by mechanism). We try all supported mechanisms (from the strongest to the weakest) until we find one supported by the server. Then we try to authenticate (only once). :param login: username :param password: clear password :param authz_id: authorization ID :param authmech: prefered authentication mechanism :return: True on success, False otherwise
2.865011
2.91677
0.982255
if not self.has_tls_support(): raise Error("STARTTLS not supported by the server") code, data = self.__send_command("STARTTLS") if code != "OK": return False try: nsock = ssl.wrap_socket(self.sock, keyfile, certfile) except ssl.SSLError as e: raise Error("SSL error: %s" % str(e)) self.sock = nsock self.__capabilities = {} self.__get_capabilities() return True
def __starttls(self, keyfile=None, certfile=None)
STARTTLS command See MANAGESIEVE specifications, section 2.2. :param keyfile: an eventual private key to use :param certfile: an eventual certificate to use :rtype: boolean
3.361962
3.448006
0.975045
if isinstance(self.__capabilities["SIEVE"], six.string_types): self.__capabilities["SIEVE"] = self.__capabilities["SIEVE"].split() return self.__capabilities["SIEVE"]
def get_sieve_capabilities(self)
Returns the SIEVE extensions supported by the server. They're read from server capabilities. (see the CAPABILITY command) :rtype: string
3.497522
3.666383
0.953944
try: self.sock = socket.create_connection((self.srvaddr, self.srvport)) self.sock.settimeout(Client.read_timeout) except socket.error as msg: raise Error("Connection to server failed: %s" % str(msg)) if not self.__get_capabilities(): raise Error("Failed to read capabilities from server") if starttls and not self.__starttls(): return False if self.__authenticate(login, password, authz_id, authmech): return True return False
def connect( self, login, password, authz_id=b"", starttls=False, authmech=None)
Establish a connection with the server. This function must be used. It read the server capabilities and wraps calls to STARTTLS and AUTHENTICATE commands. :param login: username :param password: clear password :param starttls: use a TLS connection or not :param authmech: prefered authenticate mechanism :rtype: boolean
2.869631
2.8942
0.991511
code, data, capabilities = ( self.__send_command("CAPABILITY", withcontent=True)) if code == "OK": return capabilities return None
def capability(self)
Ask server capabilities. See MANAGESIEVE specifications, section 2.4 This command does not affect capabilities recorded by this client. :rtype: string
13.620024
15.054545
0.904712
code, data = self.__send_command( "HAVESPACE", [scriptname.encode("utf-8"), scriptsize]) if code == "OK": return True return False
def havespace(self, scriptname, scriptsize)
Ask for available space. See MANAGESIEVE specifications, section 2.5 :param scriptname: script's name :param scriptsize: script's size :rtype: boolean
4.641022
4.759645
0.975077
code, data, listing = self.__send_command( "LISTSCRIPTS", withcontent=True) if code == "NO": return None ret = [] active_script = None for l in listing.splitlines(): if self.__size_expr.match(l): continue m = re.match(br'"([^"]+)"\s*(.+)', l) if m is None: ret += [l.strip(b'"').decode("utf-8")] continue script = m.group(1).decode("utf-8") if self.__active_expr.match(m.group(2)): active_script = script continue ret += [script] self.__dprint(ret) return (active_script, ret)
def listscripts(self)
List available scripts. See MANAGESIEVE specifications, section 2.7 :returns: a 2-uple (active script, [script1, ...])
4.02608
3.944288
1.020737
code, data, content = self.__send_command( "GETSCRIPT", [name.encode("utf-8")], withcontent=True) if code == "OK": lines = content.splitlines() if self.__size_expr.match(lines[0]) is not None: lines = lines[1:] return u"\n".join([line.decode("utf-8") for line in lines]) return None
def getscript(self, name)
Download a script from the server See MANAGESIEVE specifications, section 2.9 :param name: script's name :rtype: string :returns: the script's content on succes, None otherwise
4.432898
4.376386
1.012913
content = tools.to_bytes(content) content = tools.to_bytes("{%d+}" % len(content)) + CRLF + content code, data = ( self.__send_command("PUTSCRIPT", [name.encode("utf-8"), content])) if code == "OK": return True return False
def putscript(self, name, content)
Upload a script to the server See MANAGESIEVE specifications, section 2.6 :param name: script's name :param content: script's content :rtype: boolean
6.581013
7.185267
0.915904
code, data = self.__send_command( "DELETESCRIPT", [name.encode("utf-8")]) if code == "OK": return True return False
def deletescript(self, name)
Delete a script from the server See MANAGESIEVE specifications, section 2.10 :param name: script's name :rtype: boolean
4.842524
4.836594
1.001226
if "VERSION" in self.__capabilities: code, data = self.__send_command( "RENAMESCRIPT", [oldname.encode("utf-8"), newname.encode("utf-8")]) if code == "OK": return True return False (active_script, scripts) = self.listscripts() condition = ( oldname != active_script and (scripts is None or oldname not in scripts) ) if condition: self.errmsg = b"Old script does not exist" return False if newname in scripts: self.errmsg = b"New script already exists" return False oldscript = self.getscript(oldname) if oldscript is None: return False if not self.putscript(newname, oldscript): return False if active_script == oldname: if not self.setactive(newname): return False if not self.deletescript(oldname): return False return True
def renamescript(self, oldname, newname)
Rename a script on the server See MANAGESIEVE specifications, section 2.11.1 As this command is optional, we emulate it if the server does not support it. :param oldname: current script's name :param newname: new script's name :rtype: boolean
3.254567
2.997517
1.085754
code, data = self.__send_command( "SETACTIVE", [scriptname.encode("utf-8")]) if code == "OK": return True return False
def setactive(self, scriptname)
Define the active script See MANAGESIEVE specifications, section 2.8 If scriptname is empty, the current active script is disabled, ie. there will be no active script anymore. :param scriptname: script's name :rtype: boolean
5.040133
5.180737
0.97286
if "VERSION" not in self.__capabilities: raise NotImplementedError( "server does not support CHECKSCRIPT command") content = tools.to_bytes(content) content = tools.to_bytes("{%d+}" % len(content)) + CRLF + content code, data = self.__send_command("CHECKSCRIPT", [content]) if code == "OK": return True return False
def checkscript(self, content)
Check whether a script is valid See MANAGESIEVE specifications, section 2.12 :param name: script's content :rtype: boolean
6.779582
6.21635
1.090605
self.pos = 0 self.text = text while self.pos < len(text): m = self.wsregexp.match(text, self.pos) if m is not None: self.pos = m.end() continue m = self.regexp.match(text, self.pos) if m is None: raise ParseError("unknown token %s" % text[self.pos:]) self.pos = m.end() yield (m.lastgroup, m.group(m.lastgroup))
def scan(self, text)
Analyse some data Analyse the passed content. Each time a token is recognized, a 2-uple containing its name and parsed value is raised (via yield). On error, a ParseError exception is raised. :param text: a binary string containing the data to parse
2.146567
2.137357
1.004309
self.result = [] self.hash_comments = [] self.__cstate = None self.__curcommand = None self.__curstringlist = None self.__expected = None self.__opened_blocks = 0 RequireCommand.loaded_extensions = []
def __reset_parser(self)
Reset parser's internal variables Restore the parser to an initial state. Useful when creating a new parser or reusing an existing one.
16.702444
15.945015
1.047503
if self.__curcommand.must_follow is not None: if not self.__curcommand.parent: prevcmd = self.result[-1] if len(self.result) else None else: prevcmd = self.__curcommand.parent.children[-2] \ if len(self.__curcommand.parent.children) >= 2 else None if prevcmd is None or prevcmd.name not in self.__curcommand.must_follow: raise ParseError("the %s command must follow an %s command" % (self.__curcommand.name, " or ".join(self.__curcommand.must_follow))) if not self.__curcommand.parent: # collect current amount of hash comments for later # parsing into names and desciptions self.__curcommand.hash_comments = self.hash_comments self.hash_comments = [] self.result += [self.__curcommand] if not onlyrecord: while self.__curcommand: self.__curcommand = self.__curcommand.parent # Make sure to detect all done tests (including 'not' ones). condition = ( self.__curcommand and self.__curcommand.get_type() == "test" and self.__curcommand.iscomplete() ) if condition: continue break
def __up(self, onlyrecord=False)
Return to the current command's parent This method should be called each time a command is complete. In case of a top level command (no parent), it is recorded into a specific list for further usage. :param onlyrecord: tell to only record the new command into its parent.
4.374853
4.368166
1.001531
if not self.__curcommand.iscomplete(): return True ctype = self.__curcommand.get_type() if ctype == "action" or \ (ctype == "control" and not self.__curcommand.accept_children): if testsemicolon: self.__set_expected("semicolon") return True while self.__curcommand.parent: cmd = self.__curcommand self.__curcommand = self.__curcommand.parent if self.__curcommand.get_type() in ["control", "test"]: if self.__curcommand.iscomplete(): if self.__curcommand.get_type() == "control": break continue if not self.__curcommand.check_next_arg("test", cmd, add=False): return False if not self.__curcommand.iscomplete(): if self.__curcommand.variable_args_nb: self.__set_expected("comma", "right_parenthesis") break return True
def __check_command_completion(self, testsemicolon=True)
Check for command(s) completion This function should be called each time a new argument is seen by the parser in order to check a command is complete. As not only one command can be ended when receiving a new argument (nested commands case), we apply the same work to parent commands. :param testsemicolon: if True, indicates that the next expected token must be a semicolon (for commands that need one) :return: True if command is considered as complete, False otherwise.
4.197077
4.106044
1.02217
if ttype == "string": self.__curstringlist += [tvalue.decode("utf-8")] self.__set_expected("comma", "right_bracket") return True if ttype == "comma": self.__set_expected("string") return True if ttype == "right_bracket": self.__curcommand.check_next_arg("stringlist", self.__curstringlist) self.__cstate = self.__arguments return self.__check_command_completion() return False
def __stringlist(self, ttype, tvalue)
Specific method to parse the 'string-list' type Syntax: string-list = "[" string *("," string) "]" / string ; if there is only a single string, the brackets ; are optional
5.175104
5.490751
0.942513
if ttype in ["multiline", "string"]: return self.__curcommand.check_next_arg("string", tvalue.decode("utf-8")) if ttype in ["number", "tag"]: return self.__curcommand.check_next_arg(ttype, tvalue.decode("ascii")) if ttype == "left_bracket": self.__cstate = self.__stringlist self.__curstringlist = [] self.__set_expected("string") return True condition = ( ttype in ["left_cbracket", "comma"] and self.__curcommand.non_deterministic_args ) if condition: self.__curcommand.reassign_arguments() # rewind lexer self.lexer.pos -= 1 return True return False
def __argument(self, ttype, tvalue)
Argument parsing method This method acts as an entry point for 'argument' parsing. Syntax: string-list / number / tag :param ttype: current token type :param tvalue: current token value :return: False if an error is encountered, True otherwise
6.145847
5.922264
1.037753
if ttype == "identifier": test = get_command_instance(tvalue.decode("ascii"), self.__curcommand) self.__curcommand.check_next_arg("test", test) self.__expected = test.get_expected_first() self.__curcommand = test return self.__check_command_completion(testsemicolon=False) if ttype == "left_parenthesis": self.__set_expected("identifier") return True if ttype == "comma": self.__set_expected("identifier") return True if ttype == "right_parenthesis": self.__up() return True if self.__argument(ttype, tvalue): return self.__check_command_completion(testsemicolon=False) return False
def __arguments(self, ttype, tvalue)
Arguments parsing method Entry point for command arguments parsing. The parser must call this method for each parsed command (either a control, action or test). Syntax: *argument [ test / test-list ] :param ttype: current token type :param tvalue: current token value :return: False if an error is encountered, True otherwise
5.07175
4.824348
1.051282
if self.__cstate is None: if ttype == "right_cbracket": self.__up() self.__opened_blocks -= 1 self.__cstate = None return True if ttype != "identifier": return False command = get_command_instance( tvalue.decode("ascii"), self.__curcommand) if command.get_type() == "test": raise ParseError( "%s may not appear as a first command" % command.name) if command.get_type() == "control" and command.accept_children \ and command.has_arguments(): self.__set_expected("identifier") if self.__curcommand is not None: if not self.__curcommand.addchild(command): raise ParseError("%s unexpected after a %s" % (tvalue, self.__curcommand.name)) self.__curcommand = command self.__cstate = self.__arguments return True if self.__cstate(ttype, tvalue): return True if ttype == "left_cbracket": self.__opened_blocks += 1 self.__cstate = None return True if ttype == "semicolon": self.__cstate = None if not self.__check_command_completion(testsemicolon=False): return False self.__curcommand.complete_cb() self.__up() return True return False
def __command(self, ttype, tvalue)
Command parsing method Entry point for command parsing. Here is expected behaviour: * Handle command beginning if detected, * Call the appropriate sub-method (specified by __cstate) to handle the body, * Handle command ending or block opening if detected. Syntax: identifier arguments (";" / block) :param ttype: current token type :param tvalue: current token value :return: False if an error is encountered, True otherwise
4.422555
4.146367
1.06661
if isinstance(text, text_type): text = text.encode("utf-8") self.__reset_parser() try: for ttype, tvalue in self.lexer.scan(text): if ttype == "hash_comment": self.hash_comments += [tvalue.strip()] continue if ttype == "bracket_comment": continue if self.__expected is not None: if ttype not in self.__expected: if self.lexer.pos < len(text): msg = ( "%s found while %s expected near '%s'" % (ttype, "|".join(self.__expected), text[self.lexer.pos]) ) else: msg = ( "%s found while %s expected at end of file" % (ttype, "|".join(self.__expected)) ) raise ParseError(msg) self.__expected = None if not self.__command(ttype, tvalue): msg = ( "unexpected token '%s' found near '%s'" % (tvalue.decode(), text.decode()[self.lexer.pos]) ) raise ParseError(msg) if self.__opened_blocks: self.__set_expected("right_cbracket") if self.__expected is not None: raise ParseError("end of script reached while %s expected" % "|".join(self.__expected)) except (ParseError, CommandError) as e: self.error = "line %d: %s" % (self.lexer.curlineno(), str(e)) return False return True
def parse(self, text)
The parser entry point. Parse the provided text to check for its validity. On success, the parsing tree is available into the result attribute. It is a list of sievecommands.Command objects (see the module documentation for specific information). On error, an string containing the explicit reason is available into the error attribute. :param text: a string containing the data to parse :return: True on success (no error detected), False otherwise
3.240722
3.32228
0.975451
with open(name, "rb") as fp: return self.parse(fp.read())
def parse_file(self, name)
Parse the content of a file. See 'parse' method for information. :param name: the pathname of the file to parse :return: True on success (no error detected), False otherwise
4.065458
5.031655
0.807976
for r in self.result: r.dump(target=target)
def dump(self, target=sys.stdout)
Dump the parsing tree. This method displays the parsing tree on the standard output.
7.186004
9.72468
0.738945
if not isinstance(cmds, Iterable): cmds = [cmds] for command in cmds: if command.__name__.endswith("Command"): globals()[command.__name__] = command
def add_commands(cmds)
Adds one or more commands to the module namespace. Commands must end in "Command" to be added. Example (see tests/parser.py): sievelib.commands.add_commands(MytestCommand) :param cmds: a single Command Object or list of Command Objects
3.639553
4.299887
0.84643
cname = "%sCommand" % name.lower().capitalize() gl = globals() condition = ( cname not in gl or (checkexists and gl[cname].extension and gl[cname].extension not in RequireCommand.loaded_extensions) ) if condition: raise UnknownCommand(name) return gl[cname](parent)
def get_command_instance(name, parent=None, checkexists=True)
Try to guess and create the appropriate command instance Given a command name (encountered by the parser), construct the associated class name and, if known, return a new instance. If the command is not known or has not been loaded using require, an UnknownCommand exception is raised. :param name: the command's name :param parent: the eventual parent command :return: a new class instance
6.513616
5.791601
1.124666
self.__print(self.name, indentlevel, nocr=True, target=target) if self.has_arguments(): for arg in self.args_definition: if not arg["name"] in self.arguments: continue target.write(" ") value = self.arguments[arg["name"]] atype = arg["type"] if "tag" in atype: target.write(value) if arg["name"] in self.extra_arguments: value = self.extra_arguments[arg["name"]] atype = arg["extra_arg"]["type"] target.write(" ") else: continue if type(value) == list: if self.__get_arg_type(arg["name"]) == ["testlist"]: target.write("(") for t in value: t.tosieve(target=target) if value.index(t) != len(value) - 1: target.write(", ") target.write(")") else: target.write( "[{}]".format(", ".join( ['"%s"' % v.strip('"') for v in value]) ) ) continue if isinstance(value, Command): value.tosieve(indentlevel, target=target) continue if "string" in atype: target.write(value) if not value.startswith('"') and not value.startswith("["): target.write("\n") else: target.write(value) if not self.accept_children: if self.get_type() != "test": target.write(";\n") return if self.get_type() != "control": return target.write(" {\n") for ch in self.children: ch.tosieve(indentlevel + 4, target=target) self.__print("}", indentlevel, target=target)
def tosieve(self, indentlevel=0, target=sys.stdout)
Generate the sieve syntax corresponding to this command Recursive method. :param indentlevel: current indentation level :param target: opened file pointer where the content will be printed
3.019226
3.101591
0.973444
self.__print(self, indentlevel, target=target) indentlevel += 4 if self.has_arguments(): for arg in self.args_definition: if not arg["name"] in self.arguments: continue value = self.arguments[arg["name"]] atype = arg["type"] if "tag" in atype: self.__print(str(value), indentlevel, target=target) if arg["name"] in self.extra_arguments: value = self.extra_arguments[arg["name"]] atype = arg["extra_arg"]["type"] else: continue if type(value) == list: if self.__get_arg_type(arg["name"]) == ["testlist"]: for t in value: t.dump(indentlevel, target) else: self.__print("[" + (",".join(value)) + "]", indentlevel, target=target) continue if isinstance(value, Command): value.dump(indentlevel, target) continue self.__print(str(value), indentlevel, target=target) for ch in self.children: ch.dump(indentlevel, target)
def dump(self, indentlevel=0, target=sys.stdout)
Display the command Pretty printing of this command and its eventual arguments and children. (recursively) :param indentlevel: integer that indicates indentation level to apply
2.881629
2.841798
1.014016