code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
self._menus.remove(menu) for action in menu.actions(): self.removeAction(action)
def remove_menu(self, menu)
Removes a sub-menu from the context menu. :param menu: Sub-menu to remove.
3.711182
4.837438
0.767179
helper = TextHelper(self) line, result = DlgGotoLine.get_line( self, helper.current_line_nbr(), helper.line_count()) if not result: return return helper.goto_line(line, move=True)
def goto_line(self)
Shows the *go to line dialog* and go to the selected line.
6.918173
6.592952
1.049329
self.zoom_level += increment TextHelper(self).mark_whole_doc_dirty() self._reset_stylesheet()
def zoom_in(self, increment=1)
Zooms in the editor (makes the font bigger). :param increment: zoom level increment. Default is 1.
19.358694
20.557518
0.941684
self.zoom_level -= decrement # make sure font size remains > 0 if self.font_size + self.zoom_level <= 0: self.zoom_level = -self._font_size + 1 TextHelper(self).mark_whole_doc_dirty() self._reset_stylesheet()
def zoom_out(self, decrement=1)
Zooms out the editor (makes the font smaller). :param decrement: zoom level decrement. Default is 1. The value is given as an absolute value.
8.141847
8.162662
0.99745
cursor = self.textCursor() assert isinstance(cursor, QtGui.QTextCursor) has_selection = True if not cursor.hasSelection(): cursor.select(cursor.LineUnderCursor) has_selection = False line = cursor.selectedText() line = '\n'.join(line.split...
def duplicate_line(self)
Duplicates the line under the cursor. If multiple lines are selected, only the last one is duplicated.
2.492956
2.393485
1.041559
tc = self.textCursor() helper = TextHelper(self) tc.beginEditBlock() no_selection = False sText = tc.selection().toPlainText() if not helper.current_line_text() and sText.count("\n") > 1: tc.deleteChar() else: if not self.textCurso...
def cut(self)
Cuts the selected text or the whole line if no text was selected.
4.038074
3.623608
1.114379
if self.select_line_on_copy_empty and not self.textCursor().hasSelection(): TextHelper(self).select_whole_line() super(CodeEdit, self).copy()
def copy(self)
Copy the selected text to the clipboard. If no text was selected, the entire line is copied (this feature can be turned off by setting :attr:`select_line_on_copy_empty` to False.
9.03212
3.990103
2.263631
super(CodeEdit, self).resizeEvent(e) self.panels.resize()
def resizeEvent(self, e)
Overrides resize event to resize the editor's panels. :param e: resize event
9.378269
7.83878
1.196394
self._update_visible_blocks(e) super(CodeEdit, self).paintEvent(e) self.painted.emit(e)
def paintEvent(self, e)
Overrides paint event to update the list of visible blocks and emit the painted event. :param e: paint event
7.144384
4.314197
1.656017
if self.isReadOnly(): return initial_state = event.isAccepted() event.ignore() self.key_pressed.emit(event) state = event.isAccepted() if not event.isAccepted(): if event.key() == QtCore.Qt.Key_Tab and event.modifiers() == \ ...
def keyPressEvent(self, event)
Overrides the keyPressEvent to emit the key_pressed signal. Also takes care of indenting and handling smarter home key. :param event: QKeyEvent
2.389875
2.30803
1.035461
if self.isReadOnly(): return initial_state = event.isAccepted() event.ignore() self.key_released.emit(event) if not event.isAccepted(): event.setAccepted(initial_state) super(CodeEdit, self).keyReleaseEvent(event)
def keyReleaseEvent(self, event)
Overrides keyReleaseEvent to emit the key_released signal. :param event: QKeyEvent
3.770809
3.833872
0.983551
self.focused_in.emit(event) super(CodeEdit, self).focusInEvent(event)
def focusInEvent(self, event)
Overrides focusInEvent to emits the focused_in signal :param event: QFocusEvent
6.595259
5.12785
1.286165
initial_state = event.isAccepted() event.ignore() self.mouse_pressed.emit(event) if event.button() == QtCore.Qt.LeftButton: cursor = self.cursorForPosition(event.pos()) for sel in self.decorations: if sel.cursor.blockNumber() == cursor.blo...
def mousePressEvent(self, event)
Overrides mousePressEvent to emits mouse_pressed signal :param event: QMouseEvent
3.733794
3.705164
1.007727
initial_state = event.isAccepted() event.ignore() self.mouse_released.emit(event) if not event.isAccepted(): event.setAccepted(initial_state) super(CodeEdit, self).mouseReleaseEvent(event)
def mouseReleaseEvent(self, event)
Emits mouse_released signal. :param event: QMouseEvent
4.351307
4.570853
0.951968
initial_state = event.isAccepted() event.ignore() self.mouse_wheel_activated.emit(event) if not event.isAccepted(): event.setAccepted(initial_state) super(CodeEdit, self).wheelEvent(event)
def wheelEvent(self, event)
Emits the mouse_wheel_activated signal. :param event: QMouseEvent
5.010043
4.281971
1.170032
cursor = self.cursorForPosition(event.pos()) self._last_mouse_pos = event.pos() block_found = False for sel in self.decorations: if sel.contains_cursor(cursor) and sel.tooltip: if (self._prev_tooltip_block_nbr != cursor.blockNumber() or ...
def mouseMoveEvent(self, event)
Overrides mouseMovedEvent to display any decoration tooltip and emits the mouse_moved event. :param event: QMouseEvent
3.515723
3.460048
1.016091
super(CodeEdit, self).showEvent(event) self.panels.refresh()
def showEvent(self, event)
Overrides showEvent to update the viewport margins
10.501373
9.182616
1.143615
mnu = QtWidgets.QMenu() mnu.addActions(self._actions) mnu.addSeparator() for menu in self._menus: mnu.addMenu(menu) return mnu
def get_context_menu(self)
Gets the editor context menu. :return: QMenu
3.257473
3.584662
0.908725
tc = self.textCursor() nc = self.cursorForPosition(point) if not nc.position() in range(tc.selectionStart(), tc.selectionEnd()): self.setTextCursor(nc) self._mnu = self.get_context_menu() if len(self._mnu.actions()) > 1 and self.show_context_menu: ...
def _show_context_menu(self, point)
Shows the context menu
3.110121
3.035633
1.024538
doc = self.document() options = doc.defaultTextOption() if show: options.setFlags(options.flags() | QtGui.QTextOption.ShowTabsAndSpaces) else: options.setFlags( options.flags() & ~QtGui.QTextOption.ShowTabsAndS...
def _set_whitespaces_flags(self, show)
Sets show white spaces flag
2.351329
2.252153
1.044036
self._show_whitespaces = False self._tab_length = 4 self._use_spaces_instead_of_tabs = True self.setTabStopWidth(self._tab_length * self.fontMetrics().width(" ")) self._set_whitespaces_flags(self._show_whitespaces)
def _init_settings(self)
Init setting
3.920037
3.786747
1.035199
self._background = QtGui.QColor('white') self._foreground = QtGui.QColor('black') self._whitespaces_foreground = QtGui.QColor('light gray') app = QtWidgets.QApplication.instance() self._sel_background = app.palette().highlight().color() self._sel_foreground = app...
def _init_style(self)
Inits style options
3.40266
3.233997
1.052153
self._visible_blocks[:] = [] block = self.firstVisibleBlock() block_nbr = block.blockNumber() top = int(self.blockBoundingGeometry(block).translated( self.contentOffset()).top()) bottom = top + int(self.blockBoundingRect(block).height()) ebottom_top =...
def _update_visible_blocks(self, *args)
Updates the list of visible blocks
2.610386
2.52067
1.035592
if not self._cleaning: ln = TextHelper(self).cursor_position()[0] self._modified_lines.add(ln)
def _on_text_changed(self)
Adjust dirty flag depending on editor's content
13.328331
10.092902
1.320565
self.setFont(QtGui.QFont(self._font_family, self._font_size + self._zoom_level)) flg_stylesheet = hasattr(self, '_flg_stylesheet') if QtWidgets.QApplication.instance().styleSheet() or flg_stylesheet: self._flg_stylesheet = True # ...
def _reset_stylesheet(self)
Resets stylesheet
4.217772
4.193925
1.005686
# get nb char to first significative char delta = (self.textCursor().positionInBlock() - TextHelper(self).line_indent()) cursor = self.textCursor() move = QtGui.QTextCursor.MoveAnchor if select: move = QtGui.QTextCursor.KeepAnchor if ...
def _do_home_key(self, event=None, select=False)
Performs home key action
4.397761
4.376843
1.004779
def decorator(f): @wraps(f) def wrapped(*args, **kwargs): cache = get_cache() # Check if key is a function if callable(key): cache_key = key(*args, **kwargs) else: cache_key = key # Try to get the value...
def cached(key, timeout=3600)
Cache the return value of the decorated function with the given key. Key can be a String or a function. If key is a function, it must have the same arguments as the decorated function, otherwise it cannot be called successfully.
2.011827
1.877228
1.071701
txt = self.currentItem().text() QtWidgets.QApplication.clipboard().setText(txt)
def _copy_cell_text(self)
Copies the description of the selected message to the clipboard
6.882356
5.232058
1.315421
QtWidgets.QTableWidget.clear(self) self.setRowCount(0) self.setColumnCount(4) self.setHorizontalHeaderLabels( ["Type", "File name", "Line", "Description"])
def clear(self)
Clears the tables and the message list
4.248166
3.931954
1.080421
icon = cls.ICONS[status] if isinstance(icon, tuple): return QtGui.QIcon.fromTheme( icon[0], QtGui.QIcon(icon[1])) elif isinstance(icon, str): return QtGui.QIcon(icon) elif isinstance(icon, QtGui.QIcon): return icon else...
def _make_icon(cls, status)
Make icon from icon filename/tuple (if you want to use a theme)
2.283237
2.072958
1.101439
row = self.rowCount() self.insertRow(row) # type item = QtWidgets.QTableWidgetItem( self._make_icon(msg.status), msg.status_string) item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) item.setData(QtCore.Qt.UserRole, msg) self...
def add_message(self, msg)
Adds a checker message to the table. :param msg: The message to append :type msg: pyqode.core.modes.CheckerMessage
1.705276
1.686091
1.011379
msg = item.data(QtCore.Qt.UserRole) self.msg_activated.emit(msg)
def _on_item_activated(self, item)
Emits the message activated signal
5.750654
3.967176
1.449559
msg = self.currentItem().data(QtCore.Qt.UserRole) desc = msg.description desc = desc.replace('\r\n', '\n').replace('\r', '\n') desc = desc.replace('\n', '<br/>') QtWidgets.QMessageBox.information( self, _('Message details'), _() % (desc, msg.path,...
def showDetails(self)
Shows the error details.
4.70029
4.562224
1.030263
dlg = DlgGotoLine(parent, current_line + 1, line_count) if dlg.exec_() == dlg.Accepted: return dlg.spinBox.value() - 1, True return current_line, False
def get_line(cls, parent, current_line, line_count)
Gets user selected line. :param parent: Parent widget :param current_line: Current line number :param line_count: Number of lines in the current text document. :returns: tuple(line, status) status is False if the dialog has been rejected.
4.121407
4.927745
0.836368
self.hide() self.lineEditReplace.clear() self.lineEditSearch.clear()
def close_panel(self)
Closes the panel
8.763348
8.58568
1.020693
if self.checkBoxRegex.isChecked(): try: re.compile(self.lineEditSearch.text(), re.DOTALL) except sre_constants.error as e: self._show_error(e) return else: self._show_error(None) if txt is None ...
def request_search(self, txt=None)
Requests a search operation. :param txt: The text to replace. If None, the content of lineEditSearch is used instead.
4.214069
4.087563
1.030949
pal = widget.palette() pal.setColor(pal.Base, color) widget.setPalette(pal)
def _set_widget_background_color(widget, color)
Changes the base color of a widget (background). :param widget: widget to modify :param color: the color to apply
4.176498
4.52006
0.923992
current_occurence = self._current_occurrence() occurrences = self.get_occurences() if not occurrences: return current = self._occurrences[current_occurence] cursor_pos = self.editor.textCursor().position() if cursor_pos not in range(current[0], curren...
def select_next(self)
Selects the next occurrence. :return: True in case of success, false if no occurrence could be selected.
2.318696
2.300123
1.008075
if text is None or isinstance(text, bool): text = self.lineEditReplace.text() current_occurences = self._current_occurrence() occurrences = self.get_occurences() if current_occurences == -1: self.select_next() current_occurences = self._curren...
def replace(self, text=None)
Replaces the selected occurrence. :param text: The replacement text. If it is None, the lineEditReplace's text is used instead. :return True if the text could be replace properly, False if there is no more occurrences to replace.
3.113654
2.939075
1.059399
cursor = self.editor.textCursor() cursor.beginEditBlock() remains = self.replace(text=text) while remains: remains = self.replace(text=text) cursor.endEditBlock()
def replace_all(self, text=None)
Replaces all occurrences in the editor's document. :param text: The replacement text. If None, the content of the lineEdit replace will be used instead
3.437855
4.262695
0.806498
return (self.checkBoxRegex.isChecked(), self.checkBoxCase.isChecked(), self.checkBoxWholeWords.isChecked(), self.checkBoxInSelection.isChecked())
def _search_flags(self)
Returns the user search flag: (regex, case_sensitive, whole_words).
6.282009
3.573318
1.758032
deco = TextDecoration(self.editor.document(), selection_start, selection_end) deco.set_background(QtGui.QBrush(self.background)) deco.set_outline(self._outline) deco.set_foreground(QtCore.Qt.black) deco.draw_order = 1 return deco
def _create_decoration(self, selection_start, selection_end)
Creates the text occurences decoration
3.931429
3.678389
1.068791
if isinstance(self._worker, str): classname = self._worker else: classname = '%s.%s' % (self._worker.__module__, self._worker.__name__) self.request_id = str(uuid.uuid4()) self.send({'request_id': self.request_id, 'worke...
def _send_request(self)
Sends the request to the backend.
3.469976
3.250261
1.067599
comm('sending request: %r', obj) msg = json.dumps(obj) msg = msg.encode(encoding) header = struct.pack('=I', len(msg)) self.write(header) self.write(msg)
def send(self, obj, encoding='utf-8')
Sends a python object to the backend. The object **must be JSON serialisable**. :param obj: object to send :param encoding: encoding used to encode the json message into a bytes array, this should match CodeEdit.file.encoding.
4.035265
4.790328
0.842378
if self is None: return comm('connecting to 127.0.0.1:%d', self._port) address = QtNetwork.QHostAddress('127.0.0.1') self.connectToHost(address, self._port) if sys.platform == 'darwin': self.waitForConnected()
def _connect(self)
Connects our client socket to the backend socket
4.686756
4.403387
1.064353
comm('reading payload data') comm('remaining bytes to read: %d', self._to_read) data_read = self.read(self._to_read) nb_bytes_read = len(data_read) comm('%d bytes read', nb_bytes_read) self._data_buf += data_read self._to_read -= nb_bytes_read if ...
def _read_payload(self)
Reads the payload (=data)
3.395355
3.346805
1.014506
while self.bytesAvailable(): if not self._header_complete: self._read_header() else: self._read_payload()
def _on_ready_read(self)
Read bytes when ready read
6.960778
6.55409
1.062051
comm('backend process started') if self is None: return self.starting = False self.running = True
def _on_process_started(self)
Logs process started
17.862623
14.98608
1.191948
if self is None: return if error not in PROCESS_ERROR_STRING: error = -1 if not self._prevent_logs: _logger().warning(PROCESS_ERROR_STRING[error])
def _on_process_error(self, error)
Logs process error
8.974971
7.997123
1.122275
if not self: return o = self.readAllStandardOutput() try: output = bytes(o).decode(self._encoding) except TypeError: output = bytes(o.data()).decode(self._encoding) for line in output.splitlines(): self._srv_logger.log(1, l...
def _on_process_stdout_ready(self)
Logs process output
4.825662
4.61818
1.044927
try: o = self.readAllStandardError() except (TypeError, RuntimeError): # widget already deleted return try: output = bytes(o).decode(self._encoding) except TypeError: output = bytes(o.data()).decode(self._encoding) ...
def _on_process_stderr_ready(self)
Logs process output (stderr)
5.388658
5.59708
0.962762
for state in tokens.values(): for index, pattern in enumerate(state): if isinstance(pattern, tuple) and pattern[1] == new_pattern[1]: state[index] = new_pattern
def replace_pattern(tokens, new_pattern)
Given a RegexLexer token dictionary 'tokens', replace all patterns that match the token specified in 'new_pattern' with 'new_pattern'.
3.3973
3.332911
1.019319
self._clear_caches() self._update_style() super(PygmentsSH, self).on_install(editor)
def on_install(self, editor)
:type editor: pyqode.code.api.CodeEdit
8.82015
5.861557
1.504745
try: self.set_lexer_from_mime_type(mime_type) except ClassNotFound: _logger().exception('failed to get lexer from mimetype') self._lexer = TextLexer() return False except ImportError: # import error while loading some pygments ...
def set_mime_type(self, mime_type)
Update the highlighter lexer based on a mime type. :param mime_type: mime type of the new lexer to setup.
4.761523
4.594349
1.036387
self._lexer = None if filename.endswith("~"): filename = filename[0:len(filename) - 1] try: self._lexer = get_lexer_for_filename(filename) except (ClassNotFound, ImportError): print('class not found for url', filename) try: ...
def set_lexer_from_filename(self, filename)
Change the lexer based on the filename (actually only the extension is needed) :param filename: Filename or extension
2.844932
2.9061
0.978952
self._lexer = get_lexer_for_mimetype(mime, **options) _logger().debug('lexer for mimetype (%s): %r', mime, self._lexer)
def set_lexer_from_mime_type(self, mime, **options)
Sets the pygments lexer from mime type. :param mime: mime type :param options: optional addtional options.
4.166307
4.723399
0.882057
if self.color_scheme.name != self._pygments_style: self._pygments_style = self.color_scheme.name self._update_style() original_text = text if self.editor and self._lexer and self.enabled: if block.blockNumber(): prev_data = self._prev_...
def highlight_block(self, text, block)
Highlights the block using a pygments lexer. :param text: text of the block to highlith :param block: block to highlight
3.326172
3.418626
0.972956
try: self._style = get_style_by_name(self._pygments_style) except ClassNotFound: # unknown style, also happen with plugins style when used from a # frozen app. if self._pygments_style == 'qt': from pyqode.core.styles import QtStyle...
def _update_style(self)
Sets the style to the specified Pygments style.
3.7321
3.204852
1.164516
if token == Whitespace: return self.editor.whitespaces_foreground if token in self._formats: return self._formats[token] result = self._get_format_from_style(token, self._style) self._formats[token] = result return result
def _get_format(self, token)
Returns a QTextCharFormat for token or None.
4.642482
3.680073
1.261519
text_cursor = self.move_cursor_to(line) if column: text_cursor.movePosition(text_cursor.Right, text_cursor.MoveAnchor, column) if move: block = text_cursor.block() # unfold parent fold trigger if the block is colla...
def goto_line(self, line, column=0, move=True)
Moves the text cursor to the specified position.. :param line: Number of the line to go to (0 based) :param column: Optional column number. Default is 0 (start of line). :param move: True to move the cursor. False will return the cursor without setting it on the editor. ...
4.08743
4.066749
1.005085
editor = self._editor if end == -1: end = self.line_count() - 1 if start < 0: start = 0 text_cursor = self.move_cursor_to(start) if end > start: # Going down text_cursor.movePosition(text_cursor.Down, ...
def select_lines(self, start=0, end=-1, apply_selection=True)
Selects entire lines between start and end line numbers. This functions apply the selection and returns the text cursor that contains the selection. Optionally it is possible to prevent the selection from being applied on the code editor widget by setting ``apply_selection`` to False. ...
2.174572
2.209912
0.984008
if line_nbr is None: line_nbr = self.current_line_nbr() elif isinstance(line_nbr, QtGui.QTextBlock): line_nbr = line_nbr.blockNumber() line = self.line_text(line_nbr) indentation = len(line) - len(line.lstrip()) return indentation
def line_indent(self, line_nbr=None)
Returns the indent level of the specified line :param line_nbr: Number of the line to get indentation (1 base). Pass None to use the current line number. Note that you can also pass a QTextBlock instance instead of an int. :return: Number of spaces that makes the indentation lev...
2.47603
2.378584
1.040968
if cursor is None: cursor = self._editor.textCursor() cursor.movePosition(QtGui.QTextCursor.WordRight, QtGui.QTextCursor.KeepAnchor) return cursor.selectedText().strip()
def get_right_word(self, cursor=None)
Gets the character on the right of the text cursor. :param cursor: QTextCursor where the search will start. :return: The word that is on the right of the text cursor.
2.69006
3.27108
0.822376
def compare_cursors(cursor_a, cursor_b): return (cursor_b.selectionStart() >= cursor_a.selectionStart() and cursor_b.selectionEnd() <= cursor_a.selectionEnd()) text_document = self._editor.document() occurrences = [] index = -1 ...
def search_text(self, text_cursor, search_txt, search_flags)
Searches a text in a text document. :param text_cursor: Current text cursor :param search_txt: Text to search :param search_flags: QTextDocument.FindFlags :returns: the list of occurrences, the current occurrence index :rtype: tuple([], int)
2.582669
2.432206
1.061863
if formats is None: formats = ["comment", "string", "docstring"] layout = None pos = 0 if isinstance(cursor_or_block, QtGui.QTextBlock): pos = len(cursor_or_block.text()) - 1 layout = cursor_or_block.layout() elif isinstance(cursor_or_...
def is_comment_or_string(self, cursor_or_block, formats=None)
Checks if a block/cursor is a string or a comment. :param cursor_or_block: QTextCursor or QTextBlock :param formats: the list of color scheme formats to consider. By default, it will consider the following keys: 'comment', 'string', 'docstring'.
3.219948
3.086499
1.043236
def filter_matching(ignored_symbols, matching): if ignored_symbols is not None: for symbol in matching.keys(): if symbol in ignored_symbols: matching.pop(symbol) return matching def find_opening_sy...
def match_select(self, ignored_symbols=None)
Performs matched selection, selects text between matching quotes or parentheses. :param ignored_symbols; matching symbols to ignore.
2.139164
2.091631
1.022725
parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() appengine.register_commands(subparsers) requirements.register_commands(subparsers) pylint.register_commands(subparsers) args = parser.parse_args() args.func(args)
def main()
Entrypoint for the console script gcp-devrel-py-tools.
3.123278
2.902115
1.076207
try: client = Client('17015', websession) print('Client instantiated for ZIP "{0}"'.format(client.zip_code)) print() print('CURRENT ALLERGENS') print(await client.allergens.current()) print() print('EXTENDED ALLERGENS') print(await client.allerg...
async def run(websession)
Run.
2.725584
2.703941
1.008004
try: return await self._request( 'get', 'https://www.pollen.com/api/forecast/outlook') except RequestError as err: if '404' in str(err): raise InvalidZipError('No data returned for ZIP code') else: raise Request...
async def outlook(self) -> dict
Get allergen outlook.
5.56998
4.889748
1.139114
def dev(): env.roledefs = { 'web': ['192.168.1.2'], 'lb': ['192.168.1.2'], } env.user = 'vagrant' env.backends = env.roledefs['web'] env.server_name = 'django_search_model-dev.net' env.short_server_name = 'django_search_model-dev' env.static_folder = '/site_med...
Define dev stage
null
null
null
def install_postgres(user=None, dbname=None, password=None): execute(pydiploy.django.install_postgres_server, user=user, dbname=dbname, password=password)
Install Postgres on remote
null
null
null
field_dict = {} for field in fields: d_tmp = field_dict for part in field.split(LOOKUP_SEP)[:-1]: d_tmp = d_tmp.setdefault(part, {}) d_tmp = d_tmp.setdefault( field.split(LOOKUP_SEP)[-1], deepcopy(EMPTY_DICT) ).update(deepcopy(EMPTY_DICT))...
def field_to_dict(fields)
Build dictionnary which dependancy for each field related to "root" fields = ["toto", "toto__tata", "titi__tutu"] dico = { "toto": { EMPTY_DICT, "tata": EMPTY_DICT }, "titi" : { "tutu": EMPTY_DICT } ...
2.972398
2.683025
1.107853
for part in field.split(LOOKUP_SEP)[:-1]: model = associate_model(model,part) return model.__name__ + "-" + field.split(LOOKUP_SEP)[-1]
def alias_field(model, field)
Return the prefix name of a field
4.541735
4.357827
1.042202
class_field = model._meta.get_field(field) if hasattr(class_field, "field"): return class_field.field.related.related_model else: return class_field.related_model
def associate_model(model, field)
Return the model associate to the ForeignKey or ManyToMany relation
2.944308
2.779972
1.059114
class_field = model._meta.get_field(field) if hasattr(class_field, "field"): formfield = class_field.field.formfield() else: formfield = class_field.formfield() # Otherwise the formfield contain the reverse relation if isinstance(formfield, ChoiceField): formfield....
def get_formfield(model, field)
Return the formfied associate to the field of the model
3.457147
3.312694
1.043606
q_object = Q() for field in self.searchable_fields: value = self.request.GET.getlist(alias_field(self.model, field), None) mini_q = Q() for val in value: attr = "{0}{1}".format(field, self.specifications.get(field, '')) if val:...
def get_q_object(self)
Build Q object to filter the queryset
4.479765
4.157555
1.0775
magic_dico_form = self.get_dict_for_forms() forms = [] initial = list(self.request.GET.lists()) for key, value in magic_dico_form.items(): form = Form() model = value["model"] if not value["fields"]: continue for f...
def get_search_form(self)
Return list of form based on model
3.415624
3.270533
1.044363
magic_dico = field_to_dict(self.searchable_fields) dico = {} def dict_from_fields_r(mini_dict, dico, model): dico[str(model)] = {} dico[str(model)]["model"] = model dico[str(model)]["fields"] = [] for key, value in mini_dic...
def get_dict_for_forms(self)
Build a dictionnary where searchable_fields are next to their model to be use in modelform_factory dico = { "str(model)" : { "model" : Model, "fields" = [] #searchable_fields which are attribute of Model } }
2.93553
2.593532
1.131866
async def decorator(*args: list, **kwargs: dict) -> dict: data = await func(*args, **kwargs) if not data['Location']['periods']: raise InvalidZipError('No data returned for ZIP code') return data return decorator
def raise_on_invalid_zip(func: Callable) -> Callable
Raise an exception when there's no data (via a bad ZIP code).
6.61332
5.273556
1.254053
d = { 'pathname': None, 'protocols': self._get_protocols(), 'protocol': 'ssh', 'href': self._url, 'resource': None, 'user': None, 'port': None, 'name': None, 'owner': None, } for ...
def parse(self)
Parses a GIT URL and returns an object. Raises an exception on invalid URL. :returns: Parsed object :raise: :class:`.ParserError`
4.204238
3.64353
1.153892
full_url = '{0}/{1}'.format(url, self.zip_code) pieces = urlparse(url) if not headers: headers = {} headers.update({ 'Content-Type': 'application/json', 'Referer': '{0}://{1}'.format(pieces.scheme, pieces.netloc), 'User-Agent': AP...
async def _request( self, method: str, url: str, *, headers: dict = None, params: dict = None, json: dict = None) -> dict
Make a request against AirVisual.
2.668189
2.598294
1.0269
def error_handler(error): if isinstance(error, HTTPException): description = error.get_description(request.environ) code = error.code name = error.name else: description = error code = 500 name = "Internal Server Error" ...
def setup_errors(app, error_template="error.html")
Add a handler for each of the available HTTP error responses.
2.284394
2.201423
1.03769
if not domain and not company: raise MissingCompanyError( 'You must supply at least a domain name or a company name' ) if domain: params = {'domain': domain, 'api_key': self.api_key} elif company: params = {'company': comp...
def domain_search(self, domain=None, company=None, limit=None, offset=None, emails_type=None, raw=False)
Return all the email addresses found for a given domain. :param domain: The domain on which to search for emails. Must be defined if company is not. :param company: The name of the company on which to search for emails. Must be defined if domain is not. :param limit: The maxim...
2.257354
2.497085
0.903996
params = self.base_params if not domain and not company: raise MissingCompanyError( 'You must supply at least a domain name or a company name' ) if domain: params['domain'] = domain elif company: params['company']...
def email_finder(self, domain=None, company=None, first_name=None, last_name=None, full_name=None, raw=False)
Find the email address of a person given its name and company's domain. :param domain: The domain of the company where the person works. Must be defined if company is not. :param company: The name of the company where the person works. Must be defined if domain is not. :param ...
2.344451
2.316592
1.012026
params = {'email': email, 'api_key': self.api_key} endpoint = self.base_endpoint.format('email-verifier') return self._query_hunter(endpoint, params, raw=raw)
def email_verifier(self, email, raw=False)
Verify the deliverability of a given email adress.abs :param email: The email adress to check. :param raw: Gives back the entire response instead of just the 'data'. :return: Full payload of the query as a dict.
4.462775
5.187624
0.860273
params = self.base_params if not domain and not company: raise MissingCompanyError( 'You must supply at least a domain name or a company name' ) if domain: params['domain'] = domain elif company: params['company']...
def email_count(self, domain=None, company=None, raw=False)
Give back the number of email adresses Hunter has for this domain/company. :param domain: The domain of the company where the person works. Must be defined if company is not. If both 'domain' and 'company' are given, the 'domain' will be used. :param company: The name of the company wh...
3.339895
3.403611
0.98128
params = self.base_params endpoint = self.base_endpoint.format('account') res = self._query_hunter(endpoint, params, raw=raw) if raw: return res res['calls']['left'] = res['calls']['available'] - res['calls']['used'] return res
def account_information(self, raw=False)
Gives the information about the account associated with the api_key. :param raw: Gives back the entire response instead of just the 'data'. :return: Full payload of the query as a dict.
5.455943
6.428183
0.848754
args = locals() args_params = dict((key, value) for key, value in args.items() if value is not None) args_params.pop('self') params = self.base_params params.update(args_params) endpoint = self.base_endpoint.format('leads') r...
def get_leads(self, offset=None, limit=None, lead_list_id=None, first_name=None, last_name=None, email=None, company=None, phone_number=None, twitter=None)
Gives back all the leads saved in your account. :param offset: Number of leads to skip. :param limit: Maximum number of leads to return. :param lead_list_id: Id of a lead list to query leads on. :param first_name: First name to filter on. :param last_name: Last name to filte...
3.86037
4.670043
0.826624
params = self.base_params endpoint = self.base_endpoint.format('leads/' + str(lead_id)) return self._query_hunter(endpoint, params)
def get_lead(self, lead_id)
Get a specific lead saved on your account. :param lead_id: Id of the lead to search. Must be defined. :return: Lead found as a dict.
6.311426
8.428303
0.748837
args = locals() payload = dict((key, value) for key, value in args.items() if value is not None) payload.pop('self') params = self.base_params endpoint = self.base_endpoint.format('leads') return self._query_hunter(endpoint, params, 'pos...
def create_lead(self, first_name, last_name, email=None, position=None, company=None, company_industry=None, company_size=None, confidence_score=None, website=None, country_code=None, postal_code=None, source=None, linkedin_url=None, phone_...
Create a lead on your account. :param first_name: The first name of the lead to create. Must be defined. :param last_name: The last name of the lead to create. Must be defined. :param email: The email of the lead to create. :param position: The professional position of the le...
4.676573
5.6067
0.834104
params = self.base_params if offset: params['offset'] = offset if limit: params['limit'] = limit endpoint = self.base_endpoint.format('leads_lists') return self._query_hunter(endpoint, params)
def get_leads_lists(self, offset=None, limit=None)
Gives back all the leads lists saved on your account. :param offset: Number of lists to skip. :param limit: Maximum number of lists to return. :return: Leads lists found as a dict.
3.614997
4.748733
0.761255
params = self.base_params payload = {'name': name} if team_id: payload['team_id'] = team_id endpoint = self.base_endpoint.format('leads_lists') return self._query_hunter(endpoint, params, 'post', payload)
def create_leads_list(self, name, team_id=None)
Create a leads list. :param name: Name of the list to create. Must be defined. :param team_id: The id of the list to share this list with. :return: The created leads list as a dict.
4.031461
4.711395
0.855683
params = self.base_params payload = {'name': name} if team_id: payload['team_id'] = team_id endpoint = self.base_endpoint.format('leads_lists/' + str(leads_list_id)) return self._query_hunter(endpoint, params, 'put', payload)
def update_leads_list(self, leads_list_id, name, team_id=None)
Update a leads list. :param name: Name of the list to update. Must be defined. :param team_id: The id of the list to share this list with. :return: 204 Response.
3.41332
4.085503
0.835471
params = self.base_params endpoint = self.base_endpoint.format( 'leads_lists/' + str(leads_list_id) ) return self._query_hunter(endpoint, params, 'delete')
def delete_leads_list(self, leads_list_id)
Delete a leads list. :param leads_list_id: The id of the list to delete. :return: 204 Response.
5.278272
7.013673
0.752569
try: return int(s.replace('_', '')) except ValueError: return int(ast.literal_eval(s))
def to_int(s)
converts a string to an integer >>> to_int('1_000_000') 1000000 >>> to_int('1e6') 1000000 >>> to_int('1000') 1000
3.718045
5.477267
0.678814
lines = iter(lines) for line in lines: line = line.strip() if not line: continue # skip empty lines try: yield json.loads(line, object_pairs_hook=OrderedDict) except json.decoder.JSONDecodeError: content = line + ''.join(lines) ...
def dicts_from_lines(lines)
returns a generator producing dicts from json lines 1 JSON object per line is supported: {"name": "n1"} {"name": "n2"} Or 1 JSON object: { "name": "n1" } Or a list of JSON objects: [ {"name": "n1"}, {"name": "n2"}, ]
2.318551
2.528868
0.916834
def compose_two(f1, f2): return lambda *args, **kwargs: f1(f2(*args, **kwargs)) return functools.reduce(compose_two, funcs)
def compose(*funcs)
Compose any number of unary functions into a single unary function. >>> import textwrap >>> from six import text_type >>> stripped = text_type.strip(textwrap.dedent(compose.__doc__)) >>> compose(text_type.strip, textwrap.dedent)(compose.__doc__) == stripped True Compose also allows the innermost function to tak...
2.922415
2.847308
1.026378
def call_method(target): func = getattr(target, method_name) return func(*args, **kwargs) return call_method
def method_caller(method_name, *args, **kwargs)
Return a function that will call a named method on the target object with optional positional and keyword arguments. >>> lower = method_caller('lower') >>> lower('MyString') 'mystring'
2.774021
3.6573
0.758489
@functools.wraps(func) def wrapper(*args, **kwargs): if not hasattr(wrapper, 'saved_result'): wrapper.saved_result = func(*args, **kwargs) return wrapper.saved_result wrapper.reset = lambda: vars(wrapper).__delitem__('saved_result') return wrapper
def once(func)
Decorate func so it's only ever called the first time. This decorator can ensure that an expensive or non-idempotent function will not be expensive on subsequent calls and is idempotent. >>> add_three = once(lambda a: a+3) >>> add_three(3) 6 >>> add_three(9) 6 >>> add_three('12') 6 To reset the stored valu...
2.229954
1.909862
1.167599
cache_wrapper = cache_wrapper or lru_cache() def wrapper(self, *args, **kwargs): # it's the first call, replace the method with a cached, bound method bound_method = types.MethodType(method, self) cached_method = cache_wrapper(bound_method) setattr(self, method.__name__, cached_method) return cached_meth...
def method_cache(method, cache_wrapper=None)
Wrap lru_cache to support storing the cache data in the object instances. Abstracts the common paradigm where the method explicitly saves an underscore-prefixed protected property on first call and returns that subsequently. >>> class MyClass: ... calls = 0 ... ... @method_cache ... def method(sel...
3.340334
4.230921
0.789505