INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Extract the extension from the given line. | def _extensions(self, line):
"""
Extract the extension from the given line.
:param line: The line from the official public suffix repository.
:type line: str
"""
# We strip the parsed line.
line = line.strip()
if not line.startswith("//") and "." in lin... |
Update of the content of the: code: public - suffix. json. | def update(self):
"""
Update of the content of the :code:`public-suffix.json`.
"""
if not PyFunceble.CONFIGURATION["quiet"]:
# The quiet mode is not activated.
# We print a message for the user on screen.
print(
"Update of %s" % PyFun... |
Load the public suffix database into the system. | def load(self):
"""
Load the public suffix database into the system.
"""
if not PyFunceble.INTERN["psl_db"]:
# The public database was not already loaded.
# * We read, convert to dict and return the file content.
# and
# * We fill/create ... |
Implement the standard and alphabetical sorting. | def standard(cls, element):
"""
Implement the standard and alphabetical sorting.
:param element: The element we are currently reading.
:type element: str
:return: The formatted element.
:rtype: str
"""
# We remove all special characters and return the f... |
The idea behind this method is to sort a list of domain hierarchicaly. | def hierarchical(cls, element):
"""
The idea behind this method is to sort a list of domain hierarchicaly.
:param element: The element we are currently reading.
:type element: str
:return: The formatted element.
:rtype: str
.. note::
For a domain li... |
Initiate the IANA database if it is not the case. | def load(self):
"""
Initiate the IANA database if it is not the case.
"""
if "iana_db" not in PyFunceble.INTERN or not PyFunceble.INTERN["iana_db"]:
# The global database is empty, None or does not exist.
# We update it with the database content.
PyF... |
Return the referer for the given extension. | def _referer(self, extension):
"""
Return the referer for the given extension.
:param extension: A valid domain extension.
:type extension: str
:return: The whois server to use to get the WHOIS record.
:rtype: str
"""
# We get the a copy of the page.
... |
Extract the extention from the given block. Plus get its referer. | def _extensions(self):
"""
Extract the extention from the given block.
Plus get its referer.
"""
upstream_lines = (
Download(self.iana_url, return_data=True)
.text()
.split('<span class="domain tld">')
)
# We extract the diffe... |
Update the content of the iana - domains - db file. | def update(self):
"""
Update the content of the `iana-domains-db` file.
"""
if not PyFunceble.CONFIGURATION["quiet"]:
# * The quiet mode is not activated.
# We print on screen what we are doing.
print("Update of iana-domains-db", end=" ")
# ... |
Search for domain or URL related to the original URL or domain. | def mine(self): # pragma: no cover
"""
Search for domain or URL related to the original URL or domain.
:return: The mined domains or URL.
:rtype: dict
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
try:
# ... |
Retrieve the mining informations. | def _retrieve(self):
"""
Retrieve the mining informations.
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
if "mined" not in PyFunceble.INTERN:
PyFunceble.INTERN["mined"] = {}
if PyFunceble.path.isfile(self.file... |
Backup the mined informations. | def _backup(self):
"""
Backup the mined informations.
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
# We backup our mined informations.
Dict(PyFunceble.INTERN["mined"]).to_json(self.file) |
Add the currently mined information to the mined database. | def _add(self, to_add):
"""
Add the currently mined information to the
mined "database".
:param to_add: The element to add.
:type to_add: dict
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
if PyFunceble.INTERN["fi... |
Remove the currently tested element from the mining data. | def remove(self):
"""
Remove the currently tested element from the mining
data.
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
if PyFunceble.INTERN["file_to_test"] in PyFunceble.INTERN["mined"]:
# The currently test... |
Provide the list of mined so they can be added to the list queue. | def list_of_mined(cls):
"""
Provide the list of mined so they can be added to the list
queue.
:return: The list of mined domains or URL.
:rtype: list
"""
# We initiate a variable which will return the result.
result = []
if PyFunceble.CONFIGURAT... |
Process the logic and structuration of the mining database. | def process(self): # pragma: no cover
"""
Process the logic and structuration of the mining database.
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
# We load the mining logic.
mined = self.mine()
if mined:
... |
Get and return the content of the given log file. | def _get_content(cls, file):
"""
Get and return the content of the given log file.
:param file: The file we have to get the content from.
:type file: str
:return The content of the given file.
:rtype: dict
"""
if PyFunceble.path.isfile(file):
... |
Write the content into the given file. | def _write_content(cls, content, file):
"""
Write the content into the given file.
:param content: The dict to write.
:type content: dict
:param file: The file to write.
:type file: str
"""
if not PyFunceble.CONFIGURATION["no_files"]:
if not... |
Logs the WHOIS record if needed. | def whois(self, record):
"""
Logs the WHOIS record if needed.
:param record: The record to log.
:type record: str
"""
if PyFunceble.CONFIGURATION["debug"] and PyFunceble.CONFIGURATION["logs"]:
# The debug and the logs subsystem are activated.
if... |
Logs the extracted expiration date. | def expiration_date(self, extracted):
"""
Logs the extracted expiration date.
:param extracted: The extracted expiration date (from WHOIS record).
:type extracted: str
"""
if PyFunceble.CONFIGURATION["logs"]:
# The logs subsystem is activated.
i... |
Logs the case that the referer was not found. | def referer_not_found(self, extension):
"""
Logs the case that the referer was not found.
:param extension: The extension of the domain we are testing.
:type extension: str
"""
if PyFunceble.CONFIGURATION["logs"]:
# The logs subsystem is activated.
... |
Print informations about PyFunceble and the date of generation of a file into a given path if doesn t exist. | def _before_header(self):
"""
Print informations about PyFunceble and the date of generation of a file
into a given path, if doesn't exist.
"""
if (
not PyFunceble.CONFIGURATION["no_files"]
and self.output
and not PyFunceble.path.isfile(self.o... |
Construct header of the table according to template. | def _header_constructor(
cls, data_to_print, header_separator="-", column_separator=" "
):
"""
Construct header of the table according to template.
:param data_to_print:
The list of data to print into the header of the table.
:type data_to_print: list
:p... |
Management and creation of templates of header. Please consider as header the title of each columns. | def header(
self, do_not_print=False
): # pragma: no cover pylint: disable=too-many-branches
"""
Management and creation of templates of header.
Please consider as "header" the title of each columns.
:param do_not_print:
Tell us if we have to print the header or... |
Construct the table of data according to given size. | def _data_constructor(self, size):
"""
Construct the table of data according to given size.
:param size: The maximal length of each string in the table.
:type size: list
:return:
A dict with all information about the data and how to which what
maximal si... |
Get the size of each columns from the header. | def _size_from_header(cls, header):
"""
Get the size of each columns from the header.
:param header:
The header template we have to get the size from.
:type header: dict
:return: The maximal size of the each data to print.
:rtype: list
"""
#... |
Retun colored string. | def _colorify(self, data):
"""
Retun colored string.
:param data: The string to colorify.
:type data: str
:return: A colored string.
:rtype: str
"""
if self.template in ["Generic", "Less"]:
# The template is in the list of template that need... |
Management of the json template. | def _json_print(self): # pragma: no cover
"""
Management of the json template.
"""
if self.output:
# The given output is not empty.
if PyFunceble.path.isfile(self.output):
# The given output already exist.
# We get the content o... |
Management and input of data to the table. | def data(self): # pragma: no cover pylint: disable=inconsistent-return-statements
"""
Management and input of data to the table.
:raises:
:code:`Exception`
When self.data_to_print is not a list.
"""
if isinstance(self.data_to_print, list):
... |
Save the current time to the file. | def _save(self, last=False): # pragma: no cover
"""
Save the current time to the file.
:param last:
Tell us if we are at the very end of the file testing.
:type last: bool
"""
if (
self._authorization()
and PyFunceble.CONFIGURATION["... |
calculate the difference between starting and ending time. | def _calculate(cls, start=None, end=None):
"""
calculate the difference between starting and ending time.
:param start: A starting time.
:type start: int|str
:param stop: A ending time.
:type stop: int|str
:return:
A dict with following as index.
... |
Format the calculated time into a human readable format. | def format_execution_time(self, start=None, end=None):
"""
Format the calculated time into a human readable format.
:param start: A starting time.
:type start: int|str
:param stop: A ending time.
:type stop: int|str
:return: A human readable date.
:rtyp... |
Return the list of file to delete. | def file_to_delete(cls):
"""
Return the list of file to delete.
"""
# We initiate the directory we have to look for.
directory = PyFunceble.OUTPUT_DIRECTORY + PyFunceble.OUTPUTS["parent_directory"]
if not directory.endswith(PyFunceble.directory_separator): # pragma: no... |
Set the databases files to delete. | def databases_to_delete(cls): # pragma: no cover
"""
Set the databases files to delete.
"""
# We initiate the directory we have to look for.
directory = PyFunceble.CURRENT_DIRECTORY
# We initate the result variable.
result = []
# We append the dir_stru... |
Delete almost all discovered files. | def almost_everything(self, clean_all=False):
"""
Delete almost all discovered files.
:param clean_all:
Tell the subsystem if we have to clean everything instesd
of almost everything.
:type clean_all: bool
"""
# We get the list of file to delete.... |
Get the hash of the given file | def _hash_file(self, algo):
"""Get the hash of the given file
:param algo: The algorithm to use.
:type algo: str
:return: The hexdigest of the data.
:rtype: str
"""
# We het the algorithm function.
hash_data = getattr(hashlib, algo)()
with open... |
Get hash of the given data. | def _hash_data(self, algo):
"""
Get hash of the given data.
:param algo: The algorithm to use.
:type algo: str
"""
# We het the algorithm function.
hash_data = getattr(hashlib, algo)()
# We set the data into our hashlib.
hash_data.update(self.da... |
Return the hash of the given file | def get(self):
"""
Return the hash of the given file
"""
# We initiate a variable which will save the result we are going
# to return.
result = {}
if self.algorithm in self.valid_algorithms:
# * The parsed path exist.
# and
# ... |
Execute the given command. | def execute(self):
"""
Execute the given command.
:return: The output of the command.
:rtype: str
"""
# We initiate a process and parse the command to it.
process = Popen(self.command, stdout=PIPE, stderr=PIPE, shell=True)
# We communicate the command a... |
Run the given command and yield each line ( s ) one by one. | def run(self):
"""
Run the given command and yield each line(s) one by one.
.. note::
The difference between this method and :code:`self.execute()`
is that :code:`self.execute()` wait for the process to end
in order to return its output.
"""
... |
Remove a given key from a given dictionary. | def remove_key(self, key_to_remove):
"""
Remove a given key from a given dictionary.
:param key_to_remove: The key(s) to delete.
:type key_to_remove: list|str
:return: The dict without the given key(s).
:rtype: dict|None
"""
if isinstance(self.main_dict... |
Rename the given keys from the given dictionary. | def rename_key(self, key_to_rename, strict=True):
"""
Rename the given keys from the given dictionary.
:param key_to_rename:
The key(s) to rename.
Expected format: :code:`{old:new}`
:type key_to_rename: dict
:param strict:
Tell us if we have ... |
Merge the content of to_merge into the given main dictionnary. | def merge(self, to_merge, strict=True):
"""
Merge the content of to_merge into the given main dictionnary.
:param to_merge: The dictionnary to merge.
:type to_merge: dict
:param strict:
Tell us if we have to strictly merge lists.
:code:`True`: We follow... |
Save a dictionnary into a JSON file. | def to_json(self, destination):
"""
Save a dictionnary into a JSON file.
:param destination:
A path to a file where we're going to
write the converted dict into a JSON format.
:type destination: str
"""
try:
with open(destination, "w"... |
Save a dictionnary into a YAML file. | def to_yaml(self, destination, flow_style=False):
"""
Save a dictionnary into a YAML file.
:param destination:
A path to a file where we're going to write the
converted dict into a JSON format.
:type destination: str
"""
with open(destination, "w... |
Fix the path of the given path. | def fix_path(self, splited_path=None):
"""
Fix the path of the given path.
:param splited_path: A list to convert to the right path.
:type splited_path: list
:return: The fixed path.
:rtype: str
"""
if not splited_path:
# A splited path is p... |
Write or append data into the given file path. | def write(self, data_to_write, overwrite=False):
"""
Write or append data into the given file path.
:param data_to_write: The data to write.
:type data_to_write: str
:param overwrite:
Tell us if we have to overwrite the
content of the file we are working... |
Read a given file path and return its content. | def read(self):
"""
Read a given file path and return its content.
:return: The content of the given file path.
:rtype: str
"""
try:
with open(self.file, "r", encoding="utf-8") as file:
# We open and read a file.
# We get the... |
Return a well formatted list. Basicaly it s sort a list and remove duplicate. | def format(self):
"""
Return a well formatted list. Basicaly, it's sort a list and remove duplicate.
:return: A sorted, without duplicate, list.
:rtype: list
"""
try:
return sorted(list(set(self.main_list)), key=str.lower)
except TypeError: # pragm... |
Return a well formatted list. With the key_method as a function/ method to format the elements before sorting. | def custom_format(self, key_method, reverse=False):
"""
Return a well formatted list. With the key_method as a function/method to format
the elements before sorting.
:param key_method:
A function or method to use to format the
readed element before sorting.
... |
Merge to_merge into the given main list. | def merge(self, to_merge, strict=True):
"""
Merge to_merge into the given main list.
:param to_merge: The list to merge.
:type to_merge: list
:param strict:
Tell us if we have to respect index (True)
or not (False).
:type strict: bool
:r... |
Return a list of string which don t match the given regex. | def not_matching_list(self):
"""
Return a list of string which don't match the
given regex.
"""
pre_result = comp(self.regex)
return [x for x in self.data if not pre_result.search(str(x))] |
Used to get exploitable result of re. search | def match(self):
"""
Used to get exploitable result of re.search
:return: The data of the match status.
:rtype: mixed
"""
# We initate this variable which gonna contain the returned data
result = []
# We compile the regex string
to_match = comp(... |
Used to replace a matched string with another. | def replace(self):
"""
Used to replace a matched string with another.
:return: The data after replacement.
:rtype: str
"""
if self.replace_with: # pylint: disable=no-member
return substrings(
self.regex,
self.replace_with, #... |
Download the given link and return or save its: code: requests. text at the given destination. | def text(self):
"""
Download the given link and return or save its :code:`requests.text`
at the given destination.
:rtype: mixed
:raises:
:code:`Exception`
If the status code is not :code:`200`.
"""
try:
# We request the ... |
Count the number of domain for each status. | def count(self):
"""
Count the number of domain for each status.
"""
if self.status:
# The status is parsed.
# We increase the number of tested.
PyFunceble.INTERN["counter"]["number"]["tested"] += 1
if (
self.status.lower... |
Calculate the percentage of each status. | def _calculate(cls):
"""
Calculate the percentage of each status.
"""
# We map the current state/counters of the different status.
percentages = {
"up": PyFunceble.INTERN["counter"]["number"]["up"],
"down": PyFunceble.INTERN["counter"]["number"]["down"],
... |
Print on screen and on file the percentages for each status. | def log(self):
"""
Print on screen and on file the percentages for each status.
"""
if (
PyFunceble.CONFIGURATION["show_percentage"]
and PyFunceble.INTERN["counter"]["number"]["tested"] > 0
):
# * We are allowed to show the percentage on scree... |
Check if the given URL is valid. | def is_url_valid(self, url=None, return_base=False, return_formatted=False):
"""
Check if the given URL is valid.
:param url: The url to validate.
:type url: str
:param return_base:
Allow us the return of the url base (if URL formatted correctly).
:type retu... |
Check if the given domain is a valid. | def is_domain_valid(
self, domain=None, subdomain_check=False
): # pylint:disable=too-many-return-statements, too-many-branches
"""
Check if the given domain is a valid.
:param domain: The domain to validate.
:type domain: str
:param subdomain_check:
Ac... |
Check if the given subdomain is a subdomain. | def is_subdomain(self, domain=None):
"""
Check if the given subdomain is a subdomain.
:param domain: The domain to validate.
:type domain: str
:return: The validity of the subdomain.
:rtype: bool
"""
if domain:
# A domain is given.
... |
Check if the given IP is a valid IPv4. | def is_ip_valid(self, ip_to_check=None):
"""
Check if the given IP is a valid IPv4.
:param ip_to_check: The IP to test.
:type ip_to_check: str
:return: The validity of the IP.
:rtype: bool
.. note::
We only test IPv4 because for now we only them for... |
Check if the given IP is a valid IPv4. | def is_ip_range(self, ip_to_check=None):
"""
Check if the given IP is a valid IPv4.
:param ip_to_check: The IP to test.
:type ip_to_check: str
:return: The validity of the IP.
:rtype: bool
.. note::
We only test IPv4 because for now we only them for... |
Execute the logic behind the Syntax handling. | def get(cls):
"""
Execute the logic behind the Syntax handling.
:return: The syntax status.
:rtype: str
"""
if PyFunceble.INTERN["to_test_type"] == "domain":
# We are testing for domain or ip.
if Check().is_domain_valid() or Check().is_ip_valid(... |
Format the old format so it can be merged into the newer format. | def _reformat_historical_formating_error(self): # pragma: no cover
"""
Format the old format so it can be merged into the newer format.
"""
if PyFunceble.CONFIGURATION["inactive_database"]:
# The database subsystem is activated.
# We construct the possible path... |
Merge the real database with the older one which has already been set into: code: PyFunceble. INTERN [ inactive_db ] | def _merge(self):
"""
Merge the real database with the older one which
has already been set into :code:`PyFunceble.INTERN["inactive_db"]`
"""
if PyFunceble.CONFIGURATION["inactive_database"]:
# The database subsystem is activated.
# We get the content of... |
Return the current content of the inactive - db. json file. | def _retrieve(self):
"""
Return the current content of the inactive-db.json file.
"""
if PyFunceble.CONFIGURATION["inactive_database"]:
# The database subsystem is activated.
# We get, format and initiate the historical database file.
self._reformat_... |
Save the current database into the inactive - db. json file. | def _backup(self):
"""
Save the current database into the inactive-db.json file.
"""
if PyFunceble.CONFIGURATION["inactive_database"]:
# The database subsystem is activated.
# We save the current database state into the database file.
Dict(PyFunceble... |
Get the timestamp where we are going to save our current list. | def _timestamp(self):
"""
Get the timestamp where we are going to save our current list.
:return: The timestamp to append with the currently tested element.
:rtype: int|str
"""
if PyFunceble.CONFIGURATION["inactive_database"]:
# The database subsystem is act... |
Save the current: code. PyFunceble. CONFIGURATION [ to_test ] into the current timestamp. | def add(self):
"""
Save the current :code.`PyFunceble.CONFIGURATION['to_test']`
into the current timestamp.
"""
if PyFunceble.CONFIGURATION["inactive_database"]:
# The database subsystem is activated.
# We get the timestamp to use as index.
t... |
Remove all occurence of: code: PyFunceble. CONFIGURATION [ to_test ] from the database. | def remove(self):
"""
Remove all occurence of :code:`PyFunceble.CONFIGURATION['to_test']`
from the database.
"""
if PyFunceble.CONFIGURATION["inactive_database"]:
# The database subsystem is activated.
if PyFunceble.INTERN["file_to_test"] in PyFunceble.I... |
Get the content of the database. | def content(cls):
"""
Get the content of the database.
:return: The content of the database.
:rtype: list
"""
# We initiate a variable which will save what we are going to return.
result = []
if (
PyFunceble.CONFIGURATION["inactive_database"... |
Check if the currently tested element is into the database. | def is_present(cls):
"""
Check if the currently tested element is into the database.
"""
if PyFunceble.CONFIGURATION["inactive_database"]:
# The database subsystem is activated.
if PyFunceble.INTERN["to_test"] in PyFunceble.INTERN[
"flatten_inact... |
Retrieve the data from the database. | def _retrieve(self):
"""
Retrieve the data from the database.
"""
if self._authorization() and "whois_db" not in PyFunceble.INTERN:
# The usage of the whois database is activated.
if PyFunceble.path.isfile(self.whois_db_path):
# The database file... |
Backup the database into its file. | def _backup(self):
"""
Backup the database into its file.
"""
if self._authorization():
# We are authorized to work.
# We backup the current state of the datbase.
Dict(PyFunceble.INTERN["whois_db"]).to_json(self.whois_db_path) |
Check if the element is into the database. | def is_in_database(self):
"""
Check if the element is into the database.
"""
if (
self._authorization()
and PyFunceble.INTERN["file_to_test"] in PyFunceble.INTERN["whois_db"]
and PyFunceble.INTERN["to_test"]
in PyFunceble.INTERN["whois_db"... |
Check if the current time is older than the one in the database. | def is_time_older(self):
"""
Check if the current time is older than the one in the database.
"""
if (
self._authorization()
and self.is_in_database()
and int(
PyFunceble.INTERN["whois_db"][PyFunceble.INTERN["file_to_test"]][
... |
Get the expiration date from the database. | def get_expiration_date(self):
"""
Get the expiration date from the database.
:return: The expiration date from the database.
:rtype: str|None
"""
if self._authorization() and self.is_in_database() and not self.is_time_older():
# * We are authorized to work.... |
Add the currently tested element into the database. | def add(self):
"""
Add the currently tested element into the database.
"""
if self._authorization():
# We are authorized to work.
if self.epoch < int(PyFunceble.time()):
state = "past"
else:
state = "future"
... |
Set permissions in order to avoid issues before commiting. | def travis_permissions(cls):
"""
Set permissions in order to avoid issues before commiting.
"""
if PyFunceble.CONFIGURATION["travis"]:
try:
build_dir = PyFunceble.environ["TRAVIS_BUILD_DIR"]
commands = [
"sudo chown -R trav... |
Logic behind autosave under Travis CI. | def _travis(self):
"""
Logic behind autosave under Travis CI.
"""
if PyFunceble.CONFIGURATION["travis"]:
try:
_ = PyFunceble.environ["TRAVIS_BUILD_DIR"]
time_autorisation = False
try:
time_autorisation = in... |
Implementation of UNIX nslookup. | def nslookup(cls):
"""
Implementation of UNIX nslookup.
"""
try:
# We try to get the addresse information of the given domain or IP.
if "current_test_data" in PyFunceble.INTERN: # pragma: no cover
# The end-user want more information whith his t... |
Implementation of UNIX whois. | def whois(cls, whois_server, domain=None, timeout=None): # pragma: no cover
"""
Implementation of UNIX whois.
:param whois_server: The WHOIS server to use to get the record.
:type whois_server: str
:param domain: The domain to get the whois record from.
:type domain: s... |
Execute the logic behind the URL handling. | def get(cls): # pragma: no cover
"""
Execute the logic behind the URL handling.
:return: The status of the URL.
:rtype: str
"""
if Check().is_url_valid() or PyFunceble.CONFIGURATION["local"]:
# * The url is valid.
# or
# * We are tes... |
This function will extract the version from PyFunceble/ __init__. py | def _get_version():
"""
This function will extract the version from PyFunceble/__init__.py
"""
to_match = comp(r'VERSION\s=\s"(.*)"\n')
extracted = to_match.findall(
open("PyFunceble/__init__.py", encoding="utf-8").read()
)[0]
return ".".join([x for x in extracted.split(".") if x.i... |
Return the referer aka the WHOIS server of the current domain extension. | def get(self):
"""
Return the referer aka the WHOIS server of the current domain extension.
"""
if not PyFunceble.CONFIGURATION["local"]:
# We are not running a test in a local network.
if self.domain_extension not in self.ignored_extension:
# Th... |
register serviser | def _register_servicer(self, servicer):
"""register serviser
:param servicer: servicer
"""
name = servicer.__name__
if name in self._servicers:
raise exceptions.ConfigException(
'servicer duplicated: {}'.format(name))
add_func = self._get_serv... |
register extension | def _register_extension(self, name, ext):
"""register extension
:param name: extension name
:param ext: extension object
"""
ext.init_app(self)
if name in self._extensions:
raise exceptions.ConfigException(
'extension duplicated: {}'.format(na... |
Get current object. This is useful if you want the real object behind the proxy at a time for performance reasons or because you want to pass the object into a different context. | def _get_current_object(self):
"""Get current object.
This is useful if you want the real
object behind the proxy at a time for performance reasons or because
you want to pass the object into a different context.
"""
loc = object.__getattribute__(self, '_Proxy__local')
... |
Yield paths to standard modules. | def standard_paths():
"""Yield paths to standard modules."""
for is_plat_spec in [True, False]:
path = distutils.sysconfig.get_python_lib(standard_lib=True,
plat_specific=is_plat_spec)
for name in os.listdir(path):
yield name
... |
Yield standard module names. | def standard_package_names():
"""Yield standard module names."""
for name in standard_paths():
if name.startswith('_') or '-' in name:
continue
if '.' in name and name.rsplit('.')[-1] not in ['so', 'py', 'pyc']:
continue
yield name.split('.')[0] |
Yield line numbers of unused imports. | def unused_import_line_numbers(messages):
"""Yield line numbers of unused imports."""
for message in messages:
if isinstance(message, pyflakes.messages.UnusedImport):
yield message.lineno |
Yield line number and module name of unused imports. | def unused_import_module_name(messages):
"""Yield line number and module name of unused imports."""
pattern = r'\'(.+?)\''
for message in messages:
if isinstance(message, pyflakes.messages.UnusedImport):
module_name = re.search(pattern, str(message))
module_name = module_name... |
Yield line number of star import usage. | def star_import_used_line_numbers(messages):
"""Yield line number of star import usage."""
for message in messages:
if isinstance(message, pyflakes.messages.ImportStarUsed):
yield message.lineno |
Yield line number undefined name and its possible origin module. | def star_import_usage_undefined_name(messages):
"""Yield line number, undefined name, and its possible origin module."""
for message in messages:
if isinstance(message, pyflakes.messages.ImportStarUsage):
undefined_name = message.message_args[0]
module_name = message.message_args... |
Yield line numbers of unused variables. | def unused_variable_line_numbers(messages):
"""Yield line numbers of unused variables."""
for message in messages:
if isinstance(message, pyflakes.messages.UnusedVariable):
yield message.lineno |
Yield line numbers of duplicate keys. | def duplicate_key_line_numbers(messages, source):
"""Yield line numbers of duplicate keys."""
messages = [
message for message in messages
if isinstance(message, pyflakes.messages.MultiValueRepeatedKeyLiteral)]
if messages:
# Filter out complex cases. We don't want to bother trying ... |
Return dict mapping the key to list of messages. | def create_key_to_messages_dict(messages):
"""Return dict mapping the key to list of messages."""
dictionary = collections.defaultdict(lambda: [])
for message in messages:
dictionary[message.message_args[0]].append(message)
return dictionary |
Return messages from pyflakes. | def check(source):
"""Return messages from pyflakes."""
if sys.version_info[0] == 2 and isinstance(source, unicode):
# Convert back to original byte string encoding, otherwise pyflakes
# call to compile() will complain. See PEP 263. This only affects
# Python 2.
try:
... |
Return package name in import statement. | def extract_package_name(line):
"""Return package name in import statement."""
assert '\\' not in line
assert '(' not in line
assert ')' not in line
assert ';' not in line
if line.lstrip().startswith(('import', 'from')):
word = line.split()[1]
else:
# Ignore doctests.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.