_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q277900
PDFFont._set_style
test
def _set_style(self, style=None): """ Style should be a string, containing the letters 'B' for bold, 'U' for underline, or 'I' for italic, or should be '', for no style. Symbol will not be underlined. The underline style can further be modified by specifying the underline thickness and position. """ if style is None: self.style = '' self.underline = False # No syling for symbol
python
{ "resource": "" }
q277901
HASC.rotatePoint
test
def rotatePoint(self, pointX, pointY): """ Rotates a point relative to the mesh origin by the angle specified in the angle property. Uses the angle formed between the segment linking the point of interest to the origin and the parallel intersecting the origin. This angle is called beta in the code. """ if(self.angle == 0 or self.angle == None): return(pointX, pointY) # 1. Compute the segment length length = math.sqrt((pointX - self.xll) ** 2 + (pointY - self.yll) ** 2)
python
{ "resource": "" }
q277902
PDFLite.set_information
test
def set_information(self, title=None, subject=None, author=None, keywords=None, creator=None): """ Convenience function to add property info, can set any attribute and leave the others blank, it won't over-write previously set items. """ info_dict = {"title": title, "subject": subject, "author": author, "keywords": keywords, "creator": creator} for att,
python
{ "resource": "" }
q277903
PDFLite.set_display_mode
test
def set_display_mode(self, zoom='fullpage', layout='continuous'): """ Set the default viewing options. """ self.zoom_options = ["fullpage", "fullwidth", "real", "default"] self.layout_options = ["single", "continuous", "two", "default"] if zoom in self.zoom_options or (isinstance(zoom, int) and 0 < zoom <= 100): self.zoom_mode =
python
{ "resource": "" }
q277904
PDFLite.close
test
def close(self): """ Prompt the objects to output pdf code, and save to file. """ self.document._set_page_numbers() # Places header, pages, page content first. self._put_header() self._put_pages() self._put_resources() # Information object self._put_information()
python
{ "resource": "" }
q277905
PDFLite._put_header
test
def _put_header(self): """ Standard first line in a PDF. """ self.session._out('%%PDF-%s' % self.pdf_version) if self.session.compression:
python
{ "resource": "" }
q277906
PDFLite._put_pages
test
def _put_pages(self): """ First, the Document object does the heavy-lifting for the individual page objects and content. Then, the overall "Pages" object is generated. """ self.document._get_orientation_changes() self.document._output_pages() # Pages Object, provides reference to page objects (Kids list). self.session._add_object(1) self.session._out('<</Type /Pages') kids = '/Kids [' for i in xrange(0, len(self.document.pages)): kids += str(3 + 2 * i) + ' 0 R ' self.session._out(kids + ']')
python
{ "resource": "" }
q277907
PDFLite._put_resource_dict
test
def _put_resource_dict(self): """ Creates PDF reference to resource objects. """ self.session._add_object(2) self.session._out('<<') self.session._out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]') self.session._out('/Font <<') for font in self.document.fonts:
python
{ "resource": "" }
q277908
PDFLite._put_information
test
def _put_information(self): """PDF Information object.""" self.session._add_object() self.session._out('<<') self.session._out('/Producer ' + self._text_to_string( 'PDFLite, https://github.com/katerina7479')) if self.title: self.session._out('/Title ' + self._text_to_string(self.title)) if self.subject: self.session._out('/Subject ' + self._text_to_string(self.subject)) if self.author: self.session._out('/Author ' + self._text_to_string(self.author)) if self.keywords: self.session._out('/Keywords ' +
python
{ "resource": "" }
q277909
PDFLite._put_catalog
test
def _put_catalog(self): """Catalog object.""" self.session._add_object() self.session._out('<<') self.session._out('/Type /Catalog') self.session._out('/Pages 1 0 R') if self.zoom_mode == 'fullpage': self.session._out('/OpenAction [3 0 R /Fit]') elif self.zoom_mode == 'fullwidth': self.session._out('/OpenAction [3 0 R /FitH null]') elif self.zoom_mode == 'real': self.session._out('/OpenAction [3 0 R /XYZ null null 1]') elif not isinstance(self.zoom_mode, basestring): self.session._out( '/OpenAction [3 0 R /XYZ null null ' +
python
{ "resource": "" }
q277910
PDFLite._put_trailer
test
def _put_trailer(self): """ Final Trailer calculations, and end-of-file reference. """ startxref = len(self.session.buffer) self._put_cross_reference() md5 = hashlib.md5() md5.update(datetime.now().strftime('%Y%m%d%H%M%S')) try: md5.update(self.filepath) except TypeError: pass if self.title: md5.update(self.title) if self.subject:
python
{ "resource": "" }
q277911
floyd
test
def floyd(seqs, f=None, start=None, key=lambda x: x): """Floyd's Cycle Detector. See help(cycle_detector) for more context. Args: *args: Two iterators issueing the exact same sequence: -or- f, start: Function and starting state for finite state machine Yields: Values yielded by sequence_a if it terminates, undefined if a cycle is found. Raises: CycleFound if exception is found; if called with f and `start`, the parametres `first` and `period` will be defined indicating the offset of start of the cycle and the cycle's period. """ tortise, hare = seqs yield hare.next() tortise_value = tortise.next() hare_value = hare.next() while hare_value != tortise_value: yield hare_value
python
{ "resource": "" }
q277912
naive
test
def naive(seqs, f=None, start=None, key=lambda x: x): """Naive cycle detector See help(cycle_detector) for more context. Args: sequence: A sequence to detect cyles in. f, start: Function and starting state for finite state machine Yields: Values yielded by sequence_a if it terminates, undefined if a cycle is found. Raises: CycleFound if exception is found. Will always generate a first and period value no matter which of the `seqs` or `f` interface is used. """ history =
python
{ "resource": "" }
q277913
gosper
test
def gosper(seqs, f=None, start=None, key=lambda x: x): """Gosper's cycle detector See help(cycle_detector) for more context. Args: sequence: A sequence to detect cyles in. f, start: Function and starting state for finite state machine Yields: Values yielded by sequence_a if it terminates, undefined if a cycle is found. Raises: CycleFound if exception is found. Unlike Floyd and Brent's, Gosper's can only detect period of a cycle. It cannot compute the first position """ tab = [] for c, value in enumerate(seqs[0], start=1):
python
{ "resource": "" }
q277914
brent
test
def brent(seqs, f=None, start=None, key=lambda x: x): """Brent's Cycle Detector. See help(cycle_detector) for more context. Args: *args: Two iterators issueing the exact same sequence: -or- f, start: Function and starting state for finite state machine Yields: Values yielded by sequence_a if it terminates, undefined if a cycle is found. Raises: CycleFound if exception is found; if called with f and `start`, the parametres `first` and `period` will be defined indicating the offset of start of the cycle and the cycle's period. """ power = period = 1 tortise, hare = seqs yield hare.next() tortise_value = tortise.next() hare_value = hare.next() while key(tortise_value) != key(hare_value): yield hare_value if power == period: power *= 2 period = 0 if f: tortise = f_generator(f, hare_value) tortise_value = tortise.next()
python
{ "resource": "" }
q277915
PDFCursor.x_fit
test
def x_fit(self, test_length): """ Test to see if the line can has enough space for the
python
{ "resource": "" }
q277916
PDFCursor.y_fit
test
def y_fit(self, test_length): """ Test to see if the page has enough space for the given
python
{ "resource": "" }
q277917
PDFCursor.x_is_greater_than
test
def x_is_greater_than(self, test_ordinate): """ Comparison for x coordinate""" self._is_coordinate(test_ordinate)
python
{ "resource": "" }
q277918
PDFCursor.y_is_greater_than
test
def y_is_greater_than(self, test_ordinate): """Comparison for y coordinate""" self._is_coordinate(test_ordinate)
python
{ "resource": "" }
q277919
PDFCursor.copy
test
def copy(self): """ Create a copy, and return it.""" new_cursor = self.__class__(self.x, self.y) new_cursor.set_bounds(self.xmin,
python
{ "resource": "" }
q277920
PDFCursor.x_plus
test
def x_plus(self, dx=None): """ Mutable x addition. Defaults to set delta value. """ if dx is None:
python
{ "resource": "" }
q277921
PDFCursor.y_plus
test
def y_plus(self, dy=None): """ Mutable y addition. Defaults to set delta value. """ if dy is None:
python
{ "resource": "" }
q277922
PDFTable._draw
test
def _draw(self): """ Don't use this, use document.draw_table """ self._compile() self.rows[0]._advance_first_row() self._set_borders() self._draw_fill()
python
{ "resource": "" }
q277923
Labels.create
test
def create(self, name, description=None, color=None): """ Creates a new label and returns the response :param name: The label name :type name: str :param description: An optional description for the label. The name is used if no description is provided. :type description: str :param color: The hex color for the label (ex: 'ff0000' for red). If no color is provided, a random one will be assigned.
python
{ "resource": "" }
q277924
Labels.list
test
def list(self): """ Get all current labels :return: The Logentries API response :rtype: list of dict :raises: This will raise a
python
{ "resource": "" }
q277925
Labels.get
test
def get(self, name): """ Get labels by name :param name: The label name, it must be an exact match. :type name: str :return: A list of matching labels. An empty list is returned if there are not any matches :rtype: list of dict :raises: This will raise a
python
{ "resource": "" }
q277926
Labels.update
test
def update(self, label): """ Update a Label :param label: The data to update. Must include keys: * id (str) * appearance (dict) * description (str) * name (str) * title (str) :type label: dict Example: .. code-block:: python Labels().update( label={ 'id': 'd9d4596e-49e4-4135-b3b3-847f9e7c1f43', 'appearance': {'color': '278abe'}, 'name': 'My Sandbox', 'description': 'My Sandbox', 'title': 'My Sandbox', } ) :return: :rtype: dict
python
{ "resource": "" }
q277927
Labels.delete
test
def delete(self, id): """ Delete the specified label :param id: the label's ID :type id: str :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """
python
{ "resource": "" }
q277928
Tags.create
test
def create(self, label_id): """ Create a new tag :param label_id: The Label ID (the 'sn' key of the create label response) :type label_id: str :returns: The response of your post :rtype: dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """ data = { 'type': 'tagit', 'rate_count': 0, 'rate_range': 'day', 'limit_count': 0, 'limit_range': 'day', 'schedule': [], 'enabled': True, 'args': { 'sn': label_id,
python
{ "resource": "" }
q277929
Tags.list
test
def list(self): """ Get all current tags :return: All tags :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """ return list( filter( lambda x: x.get('type') == 'tagit', # pragma: no cover
python
{ "resource": "" }
q277930
Tags.get
test
def get(self, label_sn): """ Get tags by a label's sn key :param label_sn: A corresponding label's ``sn`` key. :type label_sn: str or int :return: A list of matching tags. An empty list is returned if there are not any matches :rtype: list of dict :raises: This will raise a
python
{ "resource": "" }
q277931
Hooks.create
test
def create(self, name, regexes, tag_ids, logs=None): """ Create a hook :param name: The hook's name (should be the same as the tag) :type name: str :param regexes: The list of regular expressions that Logentries expects. Ex: `['user_agent = /curl\/[\d.]*/']` Would match where the user-agent is curl. :type regexes: list of str :param tag_id: The ids of the tags to associate the hook with. (The 'id' key of the create tag response) :type tag_id: list of str :param logs: The logs to add the hook to. Comes from the 'key' key in the log dict. :type logs: list of str
python
{ "resource": "" }
q277932
Hooks.list
test
def list(self): """ Get all current hooks :return: All hooks :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>`
python
{ "resource": "" }
q277933
Hooks.update
test
def update(self, hook): """ Update a hook :param hook: The data to update. Must include keys: * id (str) * name (str) * triggers (list of str) * sources (list of str) * groups (list of str) * actions (list of str) :type hook: dict Example: .. code-block:: python Hooks().update( hook={ 'id': 'd9d4596e-49e4-4135-b3b3-847f9e7c1f43', 'name': 'My Sandbox', 'triggers': [
python
{ "resource": "" }
q277934
Alerts.create
test
def create(self, alert_config, occurrence_frequency_count=None, occurrence_frequency_unit=None, alert_frequency_count=None, alert_frequency_unit=None): """ Create a new alert :param alert_config: A list of AlertConfig classes (Ex: ``[EmailAlertConfig('[email protected]')]``) :type alert_config: list of :class:`PagerDutyAlertConfig<logentries_api.alerts.PagerDutyAlertConfig>`, :class:`WebHookAlertConfig<logentries_api.alerts.WebHookAlertConfig>`, :class:`EmailAlertConfig<logentries_api.alerts.EmailAlertConfig>`, :class:`SlackAlertConfig<logentries_api.alerts.SlackAlertConfig>`, or :class:`HipChatAlertConfig<logentries_api.alerts.HipChatAlertConfig>` :param occurrence_frequency_count: How many times per ``alert_frequency_unit`` for a match before issuing an alert. Defaults to 1 :type occurrence_frequency_count: int :param occurrence_frequency_unit: The time period to monitor for sending an alert. Must be 'day', or 'hour'. Defaults to 'hour' :type occurrence_frequency_unit: str :param alert_frequency_count: How many times per ``alert_frequency_unit`` to issue an alert. Defaults to 1 :type alert_frequency_count: int :param alert_frequency_unit: How often to regulate sending alerts. Must be 'day', or 'hour'. Defaults to
python
{ "resource": "" }
q277935
Alerts.get
test
def get(self, alert_type, alert_args=None): """ Get alerts that match the alert type and args. :param alert_type: The type of the alert. Must be one of 'pagerduty', 'mailto', 'webhook', 'slack', or 'hipchat' :type alert_type: str :param alert_args: The args for the alert. The provided args must be a subset of the actual alert args. If no args are provided, all alerts matching the ``alert_type`` are returned. For example: ``.get('mailto', alert_args={'direct': '[email protected]'})`` or ``.get('slack', {'url': 'https://hooks.slack.com/services...'})`` :return: A list of matching alerts. An empty list is returned if there are not any matches
python
{ "resource": "" }
q277936
Alerts.update
test
def update(self, alert): """ Update an alert :param alert: The data to update. Must include keys: * id (str) * rate_count (int) * rate_range (str): 'day' or 'hour' * limit_count (int) * limit_range (str): 'day' or 'hour' * type (str) * schedule (list) * args (dict) :type alert: dict Example: .. code-block:: python Alert().update( alert={ 'id': 'd9d4596e-49e4-4135-b3b3-847f9e7c1f43', 'args': {'direct': '[email protected]'},
python
{ "resource": "" }
q277937
setup
test
def setup(app): """ Initialize this Sphinx extension """ app.setup_extension('sphinx.ext.todo') app.setup_extension('sphinx.ext.mathjax') app.setup_extension("sphinx.ext.intersphinx") app.config.intersphinx_mapping.update({ 'https://docs.python.org/': None }) app.config.intersphinx_mapping.update({ sage_doc_url + doc + "/": None for doc in sage_documents }) app.config.intersphinx_mapping.update({ sage_doc_url + "reference/" + module: None for module in sage_modules }) app.setup_extension("sphinx.ext.extlinks") app.config.extlinks.update({ 'python': ('https://docs.python.org/release/'+pythonversion+'/%s', ''), # Sage trac ticket shortcuts. For example, :trac:`7549` . 'trac': ('https://trac.sagemath.org/%s', 'trac ticket #'),
python
{ "resource": "" }
q277938
themes_path
test
def themes_path(): """ Retrieve the location of the themes directory from the location of this package This is taken from Sphinx's theme documentation """
python
{ "resource": "" }
q277939
Resource._post
test
def _post(self, request, uri, params=None): """ A wrapper for posting things. :param request: The request type. Must be one of the :class:`ApiActions<logentries_api.base.ApiActions>` :type request: str :param uri: The API endpoint to hit. Must be one of :class:`ApiUri<logentries_api.base.ApiUri>` :type uri: str :param params: A dictionary of supplemental kw args :type params: dict :returns: The response of your post
python
{ "resource": "" }
q277940
LogSets.list
test
def list(self): """ Get all log sets :return: Returns a dictionary where the key is the hostname or log set, and the value is a list of the log keys :rtype: dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """ response = requests.get(self.base_url) if not response.ok: raise ServerException(
python
{ "resource": "" }
q277941
LogSets.get
test
def get(self, log_set): """ Get a specific log or log set :param log_set: The log set or log to get. Ex: `.get(log_set='app')` or `.get(log_set='app/log')` :type log_set: str :returns: The response of your log set or log :rtype: dict
python
{ "resource": "" }
q277942
find_attacker_slider
test
def find_attacker_slider(dest_list, occ_bb, piece_bb, target_bb, pos, domain): """ Find a slider attacker Parameters ---------- dest_list : list To store the results. occ_bb : int, bitboard Occupancy bitboard. piece_bb : int, bitboard Bitboard with the position of the attacker piece. target_bb : int, bitboard Occupancy bitboard without any of the sliders in question. pos : int Target position. pos_map : function Mapping between a board position and its position in a single rotated/translated rank produced with domain_trans. domain_trans : function Transformation from a rank/file/diagonal/anti-diagonal containing pos
python
{ "resource": "" }
q277943
TRANSIT.duration
test
def duration(self): ''' The approximate transit duration for the general case of an eccentric orbit ''' ecc = self.ecc if not np.isnan(self.ecc) else np.sqrt(self.ecw**2 + self.esw**2) esw = self.esw if not np.isnan(self.esw) else ecc * np.sin(self.w)
python
{ "resource": "" }
q277944
Transit.update
test
def update(self, **kwargs): ''' Update the transit keyword arguments ''' if kwargs.get('verify_kwargs', True): valid = [y[0] for x in [TRANSIT, LIMBDARK, SETTINGS] for y in x._fields_] # List of valid kwargs valid += ['b', 'times'] # These are special!
python
{ "resource": "" }
q277945
Transit.Compute
test
def Compute(self): ''' Computes the light curve model ''' err = _Compute(self.transit, self.limbdark,
python
{ "resource": "" }
q277946
Transit.Bin
test
def Bin(self): ''' Bins the light curve model to the provided time array ''' err = _Bin(self.transit,
python
{ "resource": "" }
q277947
Transit.Free
test
def Free(self): ''' Frees the memory used by all of the dynamically allocated C arrays. ''' if self.arrays._calloc: _dbl_free(self.arrays._time) _dbl_free(self.arrays._flux) _dbl_free(self.arrays._bflx) _dbl_free(self.arrays._M) _dbl_free(self.arrays._E) _dbl_free(self.arrays._f) _dbl_free(self.arrays._r) _dbl_free(self.arrays._x) _dbl_free(self.arrays._y)
python
{ "resource": "" }
q277948
BaseNNTPClient.__recv
test
def __recv(self, size=4096): """Reads data from the socket. Raises: NNTPError: When connection times out or read from socket fails. """ data = self.socket.recv(size) if not
python
{ "resource": "" }
q277949
BaseNNTPClient.__line_gen
test
def __line_gen(self): """Generator that reads a line of data from the server. It first attempts to read from the internal buffer. If there is not enough data to read a line it then requests more data from the server and adds it to the buffer. This process repeats until a line of data can be read from the internal buffer.
python
{ "resource": "" }
q277950
BaseNNTPClient.__buf_gen
test
def __buf_gen(self, length=0): """Generator that reads a block of data from the server. It first attempts to read from the internal buffer. If there is not enough data in the internal buffer it then requests more data from the server and adds it to the buffer. Args: length: An optional amount of data to retrieve. A length of 0 (the default) will retrieve a least one buffer of data. Yields: A block of data when enough data becomes available. Note: If a length of 0
python
{ "resource": "" }
q277951
BaseNNTPClient.status
test
def status(self): """Reads a command response status. If there is no response message then the returned status message will be an empty string. Raises: NNTPError: If data is required to be read from the socket and fails. NNTPProtocolError: If the status line can't be parsed. NNTPTemporaryError: For status code 400-499 NNTPPermanentError: For status code 500-599 Returns: A tuple of status code (as an integer) and status message. """ line = next(self.__line_gen()).rstrip() parts = line.split(None, 1)
python
{ "resource": "" }
q277952
BaseNNTPClient.info_gen
test
def info_gen(self, code, message, compressed=False): """Dispatcher for the info generators. Determines which __info_*_gen() should be used based on the supplied parameters. Args: code: The status code for the command response.
python
{ "resource": "" }
q277953
BaseNNTPClient.info
test
def info(self, code, message, compressed=False): """The complete content of an info response. This should only used for commands that return small or known amounts of data. Returns:
python
{ "resource": "" }
q277954
BaseNNTPClient.command
test
def command(self, verb, args=None): """Call a command on the server. If the user has not authenticated then authentication will be done as part of calling the command on the server. For commands that don't return a status message the status message will default to an empty string. Args: verb: The verb of the command to call. args: The arguments of the command as a string (default None). Returns: A tuple of status code (as an integer) and status message. Note: You can run raw commands by supplying the full command (including args) in the verb. Note: Although it is possible you shouldn't issue more than one command at a time by adding newlines to the verb as it will most likely lead to undesirable results. """ if self.__generating: raise NNTPSyncError("Command issued while a generator is active") cmd = verb if args:
python
{ "resource": "" }
q277955
NNTPClient.capabilities
test
def capabilities(self, keyword=None): """CAPABILITIES command. Determines the capabilities of the server. Although RFC3977 states that this is a required command for servers to implement not all servers do, so expect that NNTPPermanentError may be raised when this command is issued. See <http://tools.ietf.org/html/rfc3977#section-5.2> Args: keyword: Passed directly to the server, however, this is unused by the server according to RFC3977. Returns:
python
{ "resource": "" }
q277956
NNTPClient.mode_reader
test
def mode_reader(self): """MODE READER command. Instructs a mode-switching server to switch modes. See <http://tools.ietf.org/html/rfc3977#section-5.3> Returns: Boolean value indicating whether posting is allowed or not.
python
{ "resource": "" }
q277957
NNTPClient.quit
test
def quit(self): """QUIT command. Tells the server to close the connection. After the server acknowledges the request to quit the connection is closed both at the server and client. Only useful for graceful shutdown. If you are in a generator use close() instead. Once this method has been called, no other methods of the NNTPClient
python
{ "resource": "" }
q277958
NNTPClient.date
test
def date(self): """DATE command. Coordinated Universal time from the perspective of the usenet server. It can be used to provide information that might be useful when using the NEWNEWS command. See <http://tools.ietf.org/html/rfc3977#section-7.1>
python
{ "resource": "" }
q277959
NNTPClient.help
test
def help(self): """HELP command. Provides a short summary of commands that are understood by the usenet server. See <http://tools.ietf.org/html/rfc3977#section-7.2> Returns: The help text from the server.
python
{ "resource": "" }
q277960
NNTPClient.newgroups_gen
test
def newgroups_gen(self, timestamp): """Generator for the NEWGROUPS command. Generates a list of newsgroups created on the server since the specified timestamp. See <http://tools.ietf.org/html/rfc3977#section-7.3> Args: timestamp: Datetime object giving 'created since' datetime. Yields: A tuple containing the name, low water mark, high water mark, and status for the newsgroup. Note: If the datetime object supplied as the timestamp is naive (tzinfo is None) then it is assumed to be given as GMT. """
python
{ "resource": "" }
q277961
NNTPClient.newnews_gen
test
def newnews_gen(self, pattern, timestamp): """Generator for the NEWNEWS command. Generates a list of message-ids for articles created since the specified timestamp for newsgroups with names that match the given pattern. See <http://tools.ietf.org/html/rfc3977#section-7.4> Args: pattern: Glob matching newsgroups of intrest. timestamp: Datetime object giving 'created since' datetime. Yields: A message-id as string. Note: If the datetime object supplied as the timestamp is naive (tzinfo is None) then it is assumed to be given as GMT. If tzinfo is set
python
{ "resource": "" }
q277962
NNTPClient.newnews
test
def newnews(self, pattern, timestamp): """NEWNEWS command. Retrieves a list of message-ids for articles created since the specified timestamp for newsgroups with names that match the given pattern. See newnews_gen() for more details. See <http://tools.ietf.org/html/rfc3977#section-7.4> Args: pattern:
python
{ "resource": "" }
q277963
NNTPClient.list_active_gen
test
def list_active_gen(self, pattern=None): """Generator for the LIST ACTIVE command. Generates a list of active newsgroups that match the specified pattern. If no pattern is specfied then all active groups are generated. See <http://tools.ietf.org/html/rfc3977#section-7.6.3> Args: pattern: Glob matching newsgroups of intrest. Yields: A tuple containing the name, low water mark, high water mark, and status for the newsgroup. """ args =
python
{ "resource": "" }
q277964
NNTPClient.list_active_times_gen
test
def list_active_times_gen(self): """Generator for the LIST ACTIVE.TIMES command. Generates a list of newsgroups including the creation time and who created them. See <http://tools.ietf.org/html/rfc3977#section-7.6.4> Yields: A tuple containing the name, creation date as a datetime object and creator as a string for the newsgroup. """ code, message = self.command("LIST ACTIVE.TIMES") if code != 215: raise NNTPReplyError(code, message) for line in self.info_gen(code, message):
python
{ "resource": "" }
q277965
NNTPClient.list_newsgroups_gen
test
def list_newsgroups_gen(self, pattern=None): """Generator for the LIST NEWSGROUPS command. Generates a list of newsgroups including the name and a short description. See <http://tools.ietf.org/html/rfc3977#section-7.6.6> Args: pattern: Glob matching newsgroups of intrest. Yields: A tuple containing the name, and description for the newsgroup. """ args = pattern code, message = self.command("LIST NEWSGROUPS", args) if code != 215:
python
{ "resource": "" }
q277966
NNTPClient.list_overview_fmt_gen
test
def list_overview_fmt_gen(self): """Generator for the LIST OVERVIEW.FMT See list_overview_fmt() for more information. Yields: An element in the list returned by list_overview_fmt(). """ code, message = self.command("LIST OVERVIEW.FMT") if code != 215: raise NNTPReplyError(code, message) for line in self.info_gen(code, message): try: name, suffix = line.rstrip().split(":") except ValueError:
python
{ "resource": "" }
q277967
NNTPClient.list_extensions_gen
test
def list_extensions_gen(self): """Generator for the LIST EXTENSIONS command. """ code, message = self.command("LIST EXTENSIONS") if code != 202:
python
{ "resource": "" }
q277968
NNTPClient.list_gen
test
def list_gen(self, keyword=None, arg=None): """Generator for LIST command. See list() for more information. Yields: An element in the list returned by list(). """ if keyword: keyword = keyword.upper() if keyword is None or keyword == "ACTIVE": return self.list_active_gen(arg) if keyword == "ACTIVE.TIMES": return self.list_active_times_gen() if keyword == "DISTRIB.PATS": return self.list_distrib_pats_gen() if keyword == "HEADERS":
python
{ "resource": "" }
q277969
NNTPClient.list
test
def list(self, keyword=None, arg=None): """LIST command. A wrapper for all of the other list commands. The output of this command depends on the keyword specified. The output format for each keyword can be found in the list function that corresponds to the keyword. Args: keyword: Information requested. arg: Pattern or keyword specific argument. Note: Keywords supported by this function are include ACTIVE,
python
{ "resource": "" }
q277970
NNTPClient.group
test
def group(self, name): """GROUP command. """ args = name code, message = self.command("GROUP", args) if code != 211: raise NNTPReplyError(code, message) parts = message.split(None, 4)
python
{ "resource": "" }
q277971
NNTPClient.next
test
def next(self): """NEXT command. """ code, message = self.command("NEXT") if code != 223: raise NNTPReplyError(code, message) parts = message.split(None, 3) try: article =
python
{ "resource": "" }
q277972
NNTPClient.article
test
def article(self, msgid_article=None, decode=None): """ARTICLE command. """ args = None if msgid_article is not None: args = utils.unparse_msgid_article(msgid_article) code, message = self.command("ARTICLE", args) if code != 220: raise NNTPReplyError(code, message) parts = message.split(None, 1) try: articleno = int(parts[0]) except ValueError: raise NNTPProtocolError(message) # headers headers = utils.parse_headers(self.info_gen(code, message)) # decoding setup decode = "yEnc" in headers.get("subject", "")
python
{ "resource": "" }
q277973
NNTPClient.head
test
def head(self, msgid_article=None): """HEAD command. """ args = None if msgid_article is not None: args = utils.unparse_msgid_article(msgid_article) code, message = self.command("HEAD", args)
python
{ "resource": "" }
q277974
NNTPClient.body
test
def body(self, msgid_article=None, decode=False): """BODY command. """ args = None if msgid_article is not None: args = utils.unparse_msgid_article(msgid_article) code, message = self.command("BODY", args) if code != 222: raise NNTPReplyError(code, message) escape = 0 crc32 = 0 body = [] for line in self.info_gen(code, message): # decode body
python
{ "resource": "" }
q277975
NNTPClient.xgtitle
test
def xgtitle(self, pattern=None): """XGTITLE command. """ args = pattern code, message = self.command("XGTITLE", args) if code != 282:
python
{ "resource": "" }
q277976
NNTPClient.xhdr
test
def xhdr(self, header, msgid_range=None): """XHDR command. """ args = header if range is not None: args += " " + utils.unparse_msgid_range(msgid_range) code, message = self.command("XHDR",
python
{ "resource": "" }
q277977
NNTPClient.xzhdr
test
def xzhdr(self, header, msgid_range=None): """XZHDR command. Args: msgid_range: A message-id as a string, or an article number as an integer, or a tuple of specifying a range of article numbers in the form (first, [last]) - if last is omitted then all articles after first are included. A msgid_range of None (the default) uses the current article. """ args = header
python
{ "resource": "" }
q277978
NNTPClient.xover_gen
test
def xover_gen(self, range=None): """Generator for the XOVER command. The XOVER command returns information from the overview database for the article(s) specified. <http://tools.ietf.org/html/rfc2980#section-2.8> Args: range: An article number as an integer, or a tuple of specifying a range of article numbers in the form (first, [last]). If last is omitted then all articles after first are included. A range of None (the default) uses the current article.
python
{ "resource": "" }
q277979
NNTPClient.xpat_gen
test
def xpat_gen(self, header, msgid_range, *pattern): """Generator for the XPAT command. """ args = " ".join( [header, utils.unparse_msgid_range(msgid_range)] + list(pattern) ) code, message = self.command("XPAT", args) if code !=
python
{ "resource": "" }
q277980
NNTPClient.xpat
test
def xpat(self, header, id_range, *pattern): """XPAT command. """ return
python
{ "resource": "" }
q277981
NNTPClient.xfeature_compress_gzip
test
def xfeature_compress_gzip(self, terminator=False): """XFEATURE COMPRESS GZIP command. """ args = "TERMINATOR" if terminator else None code, message = self.command("XFEATURE COMPRESS
python
{ "resource": "" }
q277982
NNTPClient.post
test
def post(self, headers={}, body=""): """POST command. Args: headers: A dictionary of headers. body: A string or file like object containing the post content. Raises: NNTPDataError: If binary characters are detected in the message body. Returns: A value that evaluates to true if posting the message succeeded. (See note for further details) Note: '\\n' line terminators are converted to '\\r\\n' Note: Though not part of any specification it is common for usenet servers to return the message-id for a successfully posted message. If a message-id is identified in the response from the server then that message-id will be returned by the function, otherwise True will be returned. Note: Due to protocol issues if illegal characters are found in the body the message will still be posted but will be truncated as soon as an illegal character is detected. No illegal characters will be sent
python
{ "resource": "" }
q277983
_offset
test
def _offset(value): """Parse timezone to offset in seconds. Args: value: A timezone in the '+0000' format. An integer would also work. Returns: The timezone offset from GMT in seconds as an integer. """ o
python
{ "resource": "" }
q277984
timestamp
test
def timestamp(value, fmt=None): """Parse a datetime to a unix timestamp. Uses fast custom parsing for common datetime formats or the slow dateutil parser for other formats. This is a trade off between ease of use and speed and is very useful for fast parsing of timestamp strings whose format may standard but varied or unknown prior to parsing. Common formats include: 1 Feb 2010 12:00:00 GMT Mon, 1 Feb 2010 22:00:00 +1000 20100201120000 1383470155 (seconds since epoch) See the other timestamp_*() functions for more details. Args: value: A string representing a datetime. fmt: A timestamp format string like for time.strptime(). Returns: The time in seconds since epoch as and integer for the value specified. """ if fmt: return _timestamp_formats.get(fmt, lambda v: timestamp_fmt(v, fmt) )(value) l = len(value) if 19 <= l <= 24 and value[3] == " ": # '%d %b %Y %H:%M:%Sxxxx' try: return timestamp_d_b_Y_H_M_S(value)
python
{ "resource": "" }
q277985
datetimeobj
test
def datetimeobj(value, fmt=None): """Parse a datetime to a datetime object. Uses fast custom parsing for common datetime formats or the slow dateutil parser for other formats. This is a trade off between ease of use and speed and is very useful for fast parsing of timestamp strings whose format may standard but varied or unknown prior to parsing. Common formats include: 1 Feb 2010 12:00:00 GMT Mon, 1 Feb 2010 22:00:00 +1000 20100201120000 1383470155 (seconds since epoch) See the other datetimeobj_*() functions for more details. Args: value: A string representing a datetime. Returns: A datetime object. """ if fmt: return _datetimeobj_formats.get(fmt, lambda v: datetimeobj_fmt(v, fmt) )(value) l = len(value) if 19 <= l <= 24 and value[3] == " ": # '%d %b %Y %H:%M:%Sxxxx' try: return datetimeobj_d_b_Y_H_M_S(value) except (KeyError, ValueError):
python
{ "resource": "" }
q277986
SpecialAlertBase._api_post
test
def _api_post(self, url, **kwargs): """ Convenience method for posting """ response = self.session.post( url=url, headers=self._get_api_headers(),
python
{ "resource": "" }
q277987
SpecialAlertBase._api_delete
test
def _api_delete(self, url, **kwargs): """ Convenience method for deleting """ response = self.session.delete( url=url, headers=self._get_api_headers(),
python
{ "resource": "" }
q277988
SpecialAlertBase._api_get
test
def _api_get(self, url, **kwargs): """ Convenience method for getting """ response = self.session.get( url=url, headers=self._get_api_headers(),
python
{ "resource": "" }
q277989
SpecialAlertBase.list_scheduled_queries
test
def list_scheduled_queries(self): """ List all scheduled_queries :return: A list of all scheduled query dicts :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """
python
{ "resource": "" }
q277990
SpecialAlertBase.list_tags
test
def list_tags(self): """ List all tags for the account. The response differs from ``Hooks().list()``, in that tag dicts for anomaly alerts include a 'scheduled_query_id' key with the value being the UUID for the associated scheduled query
python
{ "resource": "" }
q277991
SpecialAlertBase.get
test
def get(self, name_or_id): """ Get alert by name or id :param name_or_id: The alert's name or id :type name_or_id: str :return: A list of matching tags. An empty list is returned if there are not any matches :rtype: list of dict :raises: This will raise a
python
{ "resource": "" }
q277992
InactivityAlert.create
test
def create(self, name, patterns, logs, trigger_config, alert_reports): """ Create an inactivity alert :param name: A name for the inactivity alert :type name: str :param patterns: A list of regexes to match :type patterns: list of str :param logs: A list of log UUID's. (The 'key' key of a log) :type logs: list of str :param trigger_config: A AlertTriggerConfig describing how far back to look for inactivity. :type trigger_config: :class:`AlertTriggerConfig<logentries_api.special_alerts.AlertTriggerConfig>` :param alert_reports: A list of AlertReportConfigs to send alerts to :type alert_reports: list of :class:`AlertReportConfig<logentries_api.special_alerts.AlertReportConfig>` :return: The API response :rtype: dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries """ data = { 'tag': { 'actions': [
python
{ "resource": "" }
q277993
InactivityAlert.delete
test
def delete(self, tag_id): """ Delete the specified InactivityAlert :param tag_id: The tag ID to delete :type tag_id: str :raises: This will raise a :class:`ServerException <logentries_api.exceptions.ServerException>` if there is an error from Logentries """
python
{ "resource": "" }
q277994
AnomalyAlert._create_scheduled_query
test
def _create_scheduled_query(self, query, change, scope_unit, scope_count): """ Create the scheduled query """ query_data = { 'scheduled_query': { 'name': 'ForAnomalyReport', 'query': query, 'threshold_type': '%', 'threshold_value': change, 'time_period': scope_unit.title(), 'time_value': scope_count, }
python
{ "resource": "" }
q277995
AnomalyAlert.create
test
def create(self, name, query, scope_count, scope_unit, increase_positive, percentage_change, trigger_config, logs, alert_reports): """ Create an anomaly alert. This call makes 2 requests, one to create a "scheduled_query", and another to create the alert. :param name: The name for the alert :type name: str :param query: The `LEQL`_ query to use for detecting anomalies. Must result in a numerical value, so it should look something like ``where(...) calculate(COUNT)`` :type query: str :param scope_count: How many ``scope_unit`` s to inspect for detecting an anomaly :type scope_count: int :param scope_unit: How far to look back in detecting an anomaly. Must be one of "hour", "day", or "week" :type scope_unit: str :param increase_positive: Detect a positive increase for the anomaly. A value of ``False`` results in detecting a decrease for the anomaly. :type increase_positive: bool :param percentage_change: The percentage of change to detect. Must be a number between 0 and 100 (inclusive). :type percentage_change: int :param trigger_config: A AlertTriggerConfig describing how far back to
python
{ "resource": "" }
q277996
AnomalyAlert.delete
test
def delete(self, tag_id): """ Delete a specified anomaly alert tag and its scheduled query This method makes 3 requests: * One to get the associated scheduled_query_id * One to delete the alert * One to delete get scheduled query :param tag_id: The tag ID to delete :type tag_id: str :raises: This will raise a :class:`ServerException <logentries_api.exceptions.ServerException>` if there is an error from Logentries """ this_alert = [tag for tag in self.list_tags() if tag.get('id') == tag_id] if len(this_alert) < 1: return query_id = this_alert[0].get('scheduled_query_id')
python
{ "resource": "" }
q277997
unparse_range
test
def unparse_range(obj): """Unparse a range argument. Args: obj: An article range. There are a number of valid formats; an integer specifying a single article or a tuple specifying an article range. If the range doesn't give a start article then all articles up to the specified last article are included. If the range doesn't specify a last article then all articles from the first specified article up to the current last article for the group are included. Returns: The range as a string that can be used by an NNTP command. Note: Sample valid formats.
python
{ "resource": "" }
q277998
parse_newsgroup
test
def parse_newsgroup(line): """Parse a newsgroup info line to python types. Args: line: An info response line containing newsgroup info. Returns: A tuple of group name, low-water as integer, high-water as integer and posting status. Raises: ValueError: If the newsgroup info cannot be parsed. Note: Posting status is a character is one of (but not limited to): "y" posting allowed "n" posting not allowed "m"
python
{ "resource": "" }
q277999
parse_header
test
def parse_header(line): """Parse a header line. Args: line: A header line as a string. Returns: None if end of headers is found. A string giving the continuation line if a continuation is found. A tuple of name, value when a header line is found. Raises: ValueError: If the
python
{ "resource": "" }