_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q270400 | Percentage.count | test | 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() in PyFunceble.STATUS["list"]["up"]
or self.status.lower() in PyFunceble.STATUS["list"]["valid"]
| python | {
"resource": ""
} |
q270401 | Percentage._calculate | test | 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"],
"invalid": PyFunceble.INTERN["counter"]["number"]["invalid"],
}
for percentage in percentages:
# We loop through our map index.
# We calculate the percentage.
calculation = | python | {
"resource": ""
} |
q270402 | Percentage.log | test | 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 screen.
# and
# * The number of tested is greater than 0.
# We initiate the output file.
output = (
PyFunceble.OUTPUT_DIRECTORY
+ PyFunceble.OUTPUTS["parent_directory"]
+ PyFunceble.OUTPUTS["logs"]["directories"]["parent"]
+ PyFunceble.OUTPUTS["logs"]["directories"]["percentage"]
+ PyFunceble.OUTPUTS["logs"]["filenames"]["percentage"]
)
# We delete the output file if it does exist.
File(output).delete()
# We calculate the percentage of each statuses.
self._calculate()
if not PyFunceble.CONFIGURATION["quiet"]:
# The quiet mode is activated.
# We print a new line.
print("\n")
# We print the percentage header on file and screen.
Prints(None, "Percentage", output).header()
# We construct the different lines/data to print on screen and file.
lines_to_print = [
[
PyFunceble.STATUS["official"]["up"],
str(PyFunceble.INTERN["counter"]["percentage"]["up"]) + "%",
PyFunceble.INTERN["counter"]["number"]["up"],
],
[
PyFunceble.STATUS["official"]["down"],
str(PyFunceble.INTERN["counter"]["percentage"]["down"]) + "%",
PyFunceble.INTERN["counter"]["number"]["down"],
],
[
| python | {
"resource": ""
} |
q270403 | Check.is_url_valid | test | 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 return_formatted: bool
:param return_formatted:
Allow us to get the URL converted to IDNA if the conversion
is activated.
:type return_formatted: bool
:return: The validity of the URL or its base.
:rtype: bool|str
"""
# We initiate a variable which will save the initial base in case
# we have to convert the base to IDNA.
initial_base = None
if url:
# The given url is not empty.
# We initiate the element to test.
to_test = url
elif self.element:
# The globaly given url is not empty.
# We initiate the element to test.
to_test = self.element
else:
# The given url is empty.
# We initiate the element to test from the globaly URl to test.
to_test = PyFunceble.INTERN["to_test"]
if to_test.startswith("http"):
# The element to test starts with http.
try:
# We initiate a regex which will match the domain or the url base.
regex = r"(^(http:\/\/|https:\/\/)(.+?(?=\/)|.+?$))"
# We extract the url base with the help of the initiated regex.
initial_base = base = Regex(
| python | {
"resource": ""
} |
q270404 | Check.is_domain_valid | test | 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:
Activate the subdomain checking.
:type subdomain_check: bool
:return: The validity of the sub-domain.
:rtype: bool
"""
# We initate our regex which will match for valid domains.
regex_valid_domains = r"^(?=.{0,253}$)(([a-z0-9][a-z0-9-]{0,61}[a-z0-9]|[a-z0-9])\.)+((?=.*[^0-9])([a-z0-9][a-z0-9-]{0,61}[a-z0-9](?:\.)?|[a-z0-9](?:\.)?))$" # pylint: disable=line-too-long
# We initiate our regex which will match for valid subdomains.
regex_valid_subdomains = r"^(?=.{0,253}$)(([a-z0-9_][a-z0-9-_]{0,61}[a-z0-9_-]|[a-z0-9])\.)+((?=.*[^0-9])([a-z0-9][a-z0-9-]{0,61}[a-z0-9]|[a-z0-9]))$" # pylint: disable=line-too-long
if domain:
# A domain is given.
# We set the element to test as the parsed domain.
to_test = domain
elif self.element:
# A domain is globally given.
# We set the globally parsed domain.
to_test = self.element
else:
# A domain is not given.
# We set the element to test as the currently tested element.
to_test = PyFunceble.INTERN["to_test"]
try:
# We get the position of the last point.
last_point_index = to_test.rindex(".")
# And with the help of the position of the last point, we get the domain extension.
extension = to_test[last_point_index + 1 :]
if not extension and to_test.endswith("."):
try:
extension = [x for x in to_test.split(".") if x][-1]
except IndexError:
pass
if not extension or extension not in PyFunceble.INTERN["iana_db"]:
# * The extension is not found.
# or
# * The extension is not into the IANA database.
# We return false.
return False
if (
Regex(to_test, regex_valid_domains, return_data=False).match()
and not subdomain_check
):
# * The element pass the domain validation.
# and
# * We are not checking if it is a subdomain.
# We return True. The domain is valid.
return True
# The element did not pass the domain validation. That means that
# it has invalid character or the position of - or _ are not right.
if extension in PyFunceble.INTERN["psl_db"]:
# The extension is into the psl database.
for suffix in PyFunceble.INTERN["psl_db"][extension]:
# We loop through the element of the extension into the psl database.
try:
# We try to get the position of the currently read suffix
# in the element ot test.
suffix_index = to_test.rindex("." + suffix)
# We get the element to check.
# The idea here is to delete the suffix, then retest with our
# subdomains regex.
to_check = to_test[:suffix_index]
if "." not in to_check and subdomain_check:
# * There is no point into the new element to check.
# and
| python | {
"resource": ""
} |
q270405 | Check.is_subdomain | test | 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.
# We set the element to test as the parsed domain.
to_test = domain
elif self.element:
# A domain is globally given.
# We set the globally parsed domain.
| python | {
"resource": ""
} |
q270406 | Syntax.get | test | 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():
# * The domain is valid.
# or
# * The IP is valid.
# We handle and return the valid status.
return SyntaxStatus(PyFunceble.STATUS["official"]["valid"]).handle()
elif PyFunceble.INTERN["to_test_type"] == "url":
# We are testing for URL.
| python | {
"resource": ""
} |
q270407 | Inactive._reformat_historical_formating_error | test | 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 to an older version of the database.
historical_formating_error = (
PyFunceble.CURRENT_DIRECTORY + "inactive-db.json"
)
if PyFunceble.path.isfile(historical_formating_error):
# The histortical file already exists.
# We get its content.
data = Dict().from_json(File(historical_formating_error).read())
# We initiate a variable which will save the data that is going
# to be merged.
data_to_parse = {}
# We get the database keybase.
top_keys = data.keys()
for top_key in top_keys:
# We loop through the list of upper keys.
# We get the lowest keys.
low_keys = data[top_key].keys()
# We initiate the data to parse.
data_to_parse[top_key] = {}
for low_key in low_keys:
# We loop through the list of | python | {
"resource": ""
} |
q270408 | Inactive._retrieve | test | 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_historical_formating_error()
| python | {
"resource": ""
} |
q270409 | Inactive._backup | test | 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 | python | {
"resource": ""
} |
q270410 | Inactive._timestamp | test | 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 activated.
if (
"inactive_db" in PyFunceble.INTERN
and PyFunceble.INTERN["file_to_test"]
in PyFunceble.INTERN["inactive_db"]
and PyFunceble.INTERN["inactive_db"][PyFunceble.INTERN["file_to_test"]]
):
# The file we are testing is into the database and its content
# is not empty.
# We get the indexes of the current file (in the dabase).
database_keys = [
x
for x in PyFunceble.INTERN["inactive_db"][
PyFunceble.INTERN["file_to_test"]
].keys()
if x.isdigit()
]
if database_keys:
# The list of keys is not empty.
# We get the most recent date.
recent_date = max(database_keys)
else: # pragma: no cover
# The list of keys is empty.
# We return the current time.
return int(PyFunceble.time())
| python | {
"resource": ""
} |
q270411 | Inactive.content | test | 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"]
and PyFunceble.INTERN["inactive_db"]
):
# * The database subsystem is activated.
# and
# * The database is not empty.
for key in PyFunceble.INTERN["inactive_db"][
PyFunceble.INTERN["file_to_test"]
]:
# We loop through the index of the current file database.
if key == "to_test":
# The current key is `to_test`.
# We continue | python | {
"resource": ""
} |
q270412 | Inactive.is_present | test | 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_inactive_db"
] or (
| python | {
"resource": ""
} |
q270413 | Whois._retrieve | test | 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 exist.
# We merge our current database into already initiated one.
PyFunceble.INTERN["whois_db"] = Dict().from_json(
| python | {
"resource": ""
} |
q270414 | Whois._backup | test | def _backup(self):
"""
Backup the database into its file.
"""
if self._authorization():
# We are authorized to work.
# We backup the current | python | {
"resource": ""
} |
q270415 | Whois.is_in_database | test | 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"][PyFunceble.INTERN["file_to_test"]]
):
# * We are authorized to work.
# and
| python | {
"resource": ""
} |
q270416 | Whois.is_time_older | test | 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"]][
PyFunceble.INTERN["to_test"]
| python | {
"resource": ""
} |
q270417 | Whois.get_expiration_date | test | 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.
# and
# * The element we are testing is in the database.
# and
# * The expiration date is in the future.
# We get the expiration date from the database.
result = PyFunceble.INTERN["whois_db"][PyFunceble.INTERN["file_to_test"]][ | python | {
"resource": ""
} |
q270418 | Whois.add | test | 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"
if self.is_in_database():
# The element we are working with is in the database.
if (
str(self.epoch)
!= PyFunceble.INTERN["whois_db"][PyFunceble.INTERN["file_to_test"]][
PyFunceble.INTERN["to_test"]
]["epoch"]
):
# The given epoch is diffent from the one saved.
# We update it.
PyFunceble.INTERN["whois_db"][PyFunceble.INTERN["file_to_test"]][
PyFunceble.INTERN["to_test"]
].update(
{
"epoch": str(self.epoch),
"state": state,
"expiration_date": self.expiration_date,
}
)
elif self.is_time_older():
# The expiration date from the database is in the past.
if (
PyFunceble.INTERN["whois_db"][
PyFunceble.INTERN["file_to_test"]
][PyFunceble.INTERN["to_test"]]["state"]
!= "past" | python | {
"resource": ""
} |
q270419 | AutoSave.travis_permissions | test | 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 travis:travis %s" % (build_dir),
"sudo chgrp -R travis %s" % (build_dir),
| python | {
"resource": ""
} |
q270420 | AutoSave._travis | test | 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 = int(PyFunceble.time()) >= int(
PyFunceble.INTERN["start"]
) + (int(PyFunceble.CONFIGURATION["travis_autosave_minutes"]) * 60)
except KeyError:
if self.last and not self.bypass:
raise Exception(
"Please review the way `ExecutionTime()` is called."
)
if self.last or time_autorisation or self.bypass:
Percentage().log()
self.travis_permissions()
command = 'git add --all && git commit -a -m "%s"'
if self.last or self.bypass:
if PyFunceble.CONFIGURATION["command_before_end"]:
for line in Command(
PyFunceble.CONFIGURATION["command_before_end"]
).run():
sys_stdout.write("{}\n".format(line))
self.travis_permissions()
message = (
PyFunceble.CONFIGURATION["travis_autosave_final_commit"]
+ " [ci skip]"
| python | {
"resource": ""
} |
q270421 | Lookup.nslookup | test | 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 test.
if not Check().is_ip_valid():
# The element we are testing is not an IP.
# We request the address informations.
request = PyFunceble.socket.getaddrinfo(
PyFunceble.INTERN["to_test"],
80,
0,
0,
PyFunceble.socket.IPPROTO_TCP,
)
for sequence in request:
# We loop through the sequence returned by the request.
# We append the NS informations into the nslookup index.
PyFunceble.INTERN["current_test_data"]["nslookup"].append(
sequence[-1][0]
)
else:
# The element we are testing is an IP.
request = PyFunceble.socket.gethostbyaddr(
PyFunceble.INTERN["to_test"]
)
# We append the NS informations into the nslookup index.
PyFunceble.INTERN["current_test_data"]["nslookup"][
"hostname"
] = request[0]
PyFunceble.INTERN["current_test_data"]["nslookup"][
"aliases"
] = request[1]
| python | {
"resource": ""
} |
q270422 | Lookup.whois | test | 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: str
:param timeout: The timeout to apply to the request.
:type timeout: int
:return: The whois record from the given whois server, if exist.
:rtype: str|None
"""
if domain is None:
# The domain is not given (localy).
# We consider the domain as the domain or IP we are currently testing.
domain = PyFunceble.INTERN["to_test"]
if timeout is None:
# The time is not given (localy).
# We consider the timeout from the configuration as the timeout to use.
timeout = PyFunceble.CONFIGURATION["seconds_before_http_timeout"]
if whois_server:
# A whois server is given.
# We initiate a PyFunceble.socket.
req = PyFunceble.socket.socket(
PyFunceble.socket.AF_INET, PyFunceble.socket.SOCK_STREAM
)
if timeout % 3 == 0:
# The timeout is modulo 3.
# We report the timeout to our initiated PyFunceble.socket.
req.settimeout(timeout)
else:
# The timeout is not modulo 3.
# We report 3 seconds as the timeout to our initiated PyFunceble.socket.
req.settimeout(3)
try:
# We try to connect to the whois server at the port 43.
req.connect((whois_server, 43))
except PyFunceble.socket.error:
# We got an error.
# We return None.
return None
# We send end encode the domain we want the data from.
req.send((domain + "\r\n").encode())
# We initiate a bytes variable which will save the response
# from the server.
| python | {
"resource": ""
} |
q270423 | URL.get | test | 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 testing in/for a local or private network.
if "current_test_data" in PyFunceble.INTERN:
PyFunceble.INTERN["current_test_data"]["url_syntax_validation"] = True
# We initiate the HTTP status code.
PyFunceble.INTERN.update({"http_code": HTTPCode().get()})
# We initiate the list of active status code.
active_list = []
active_list.extend(PyFunceble.HTTP_CODE["list"]["potentially_up"])
active_list.extend(PyFunceble.HTTP_CODE["list"]["up"])
# We initiate the list of inactive status code.
inactive_list = []
inactive_list.extend(PyFunceble.HTTP_CODE["list"]["potentially_down"])
inactive_list.append("*" * 3)
if PyFunceble.INTERN["http_code"] in active_list:
# The extracted HTTP status code is in the list of active list.
# We handle and return the up status.
| python | {
"resource": ""
} |
q270424 | Referer.get | test | 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:
# The extension of the domain we are testing is not into
# the list of ignored extensions.
# We set the referer to None as we do not have any.
referer = None
if self.domain_extension in PyFunceble.INTERN["iana_db"]:
# The domain extension is in the iana database.
if not PyFunceble.CONFIGURATION["no_whois"]:
# We are authorized to use WHOIS for the test result.
# We get the referer from the database.
referer = PyFunceble.INTERN["iana_db"][self.domain_extension]
if not referer:
# The referer is not filled.
# We log the case of the current extension.
Logs().referer_not_found(self.domain_extension)
# And we handle and return None status.
return None
# The referer is into the database.
# We return the extracted referer. | python | {
"resource": ""
} |
q270425 | Proxy._get_current_object | test | 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')
if not hasattr(loc, '__release_local__'):
return loc(*self.__args, **self.__kwargs)
| python | {
"resource": ""
} |
q270426 | standard_paths | test | 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
try:
| python | {
"resource": ""
} |
q270427 | standard_package_names | test | def standard_package_names():
"""Yield standard module names."""
for name in standard_paths():
if name.startswith('_') or '-' | python | {
"resource": ""
} |
q270428 | unused_import_line_numbers | test | def unused_import_line_numbers(messages):
"""Yield line numbers of unused imports."""
for message in messages:
if isinstance(message, | python | {
"resource": ""
} |
q270429 | unused_import_module_name | test | 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 | python | {
"resource": ""
} |
q270430 | star_import_used_line_numbers | test | def star_import_used_line_numbers(messages):
"""Yield line number of star import usage."""
for message in messages:
if isinstance(message, | python | {
"resource": ""
} |
q270431 | star_import_usage_undefined_name | test | 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):
| python | {
"resource": ""
} |
q270432 | unused_variable_line_numbers | test | def unused_variable_line_numbers(messages):
"""Yield line numbers of unused variables."""
for message in messages:
if isinstance(message, | python | {
"resource": ""
} |
q270433 | duplicate_key_line_numbers | test | 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 to parse
# this stuff and get it right. We can do it on a key-by-key basis.
key_to_messages = create_key_to_messages_dict(messages)
lines = source.split('\n')
for (key, messages) in key_to_messages.items():
good = True
| python | {
"resource": ""
} |
q270434 | create_key_to_messages_dict | test | def create_key_to_messages_dict(messages):
"""Return dict mapping the key to list of messages."""
dictionary = collections.defaultdict(lambda: [])
for message | python | {
"resource": ""
} |
q270435 | check | test | 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:
source = source.encode('utf-8')
except UnicodeError: # pragma: no cover
return []
reporter = | python | {
"resource": ""
} |
q270436 | extract_package_name | test | 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:
| python | {
"resource": ""
} |
q270437 | multiline_import | test | def multiline_import(line, previous_line=''):
"""Return True if import is spans multiples lines."""
for symbol in '()':
if symbol in line:
return True
# Ignore doctests.
| python | {
"resource": ""
} |
q270438 | multiline_statement | test | def multiline_statement(line, previous_line=''):
"""Return True if this is part of a multiline statement."""
for symbol in '\\:;':
if symbol in line:
return True
sio = io.StringIO(line)
try:
list(tokenize.generate_tokens(sio.readline)) | python | {
"resource": ""
} |
q270439 | filter_from_import | test | def filter_from_import(line, unused_module):
"""Parse and filter ``from something import a, b, c``.
Return line without unused import modules, or `pass` if all of the
module in import is unused.
"""
(indentation, imports) = re.split(pattern=r'\bimport\b',
string=line, maxsplit=1)
base_module = re.search(pattern=r'\bfrom\s+([^ ]+)',
string=indentation).group(1)
# Create an imported module list with base module name
# ex ``from a import b, c as d`` -> ``['a.b', 'a.c as d']``
imports = re.split(pattern=r',', string=imports.strip())
imports = [base_module + '.' + x.strip() for x in imports]
# We compare full module name (``a.module`` not `module`) to
# guarantee the exact same module as detected from pyflakes.
| python | {
"resource": ""
} |
q270440 | break_up_import | test | def break_up_import(line):
"""Return line with imports on separate lines."""
assert '\\' not in line
assert '(' not in line
assert ')' not in line
assert ';' not in line
assert '#' not in line
assert not line.lstrip().startswith('from')
| python | {
"resource": ""
} |
q270441 | filter_code | test | def filter_code(source, additional_imports=None,
expand_star_imports=False,
remove_all_unused_imports=False,
remove_duplicate_keys=False,
remove_unused_variables=False,
ignore_init_module_imports=False,
):
"""Yield code with unused imports removed."""
imports = SAFE_IMPORTS
if additional_imports:
imports |= frozenset(additional_imports)
del additional_imports
messages = check(source)
if ignore_init_module_imports:
marked_import_line_numbers = frozenset()
else:
marked_import_line_numbers = frozenset(
unused_import_line_numbers(messages))
marked_unused_module = collections.defaultdict(lambda: [])
for line_number, module_name in unused_import_module_name(messages):
marked_unused_module[line_number].append(module_name)
if expand_star_imports and not (
# See explanations in #18.
re.search(r'\b__all__\b', source) or
re.search(r'\bdel\b', source)
):
marked_star_import_line_numbers = frozenset(
star_import_used_line_numbers(messages))
if len(marked_star_import_line_numbers) > 1:
# Auto expanding only possible for single star import
marked_star_import_line_numbers = frozenset() | python | {
"resource": ""
} |
q270442 | get_messages_by_line | test | def get_messages_by_line(messages):
"""Return dictionary that maps line number to message."""
line_messages = {}
for message in messages:
| python | {
"resource": ""
} |
q270443 | filter_star_import | test | def filter_star_import(line, marked_star_import_undefined_name):
"""Return line with the star | python | {
"resource": ""
} |
q270444 | filter_duplicate_key | test | def filter_duplicate_key(line, message, line_number, marked_line_numbers,
source, previous_line=''):
"""Return '' if first occurrence of the key otherwise return `line`."""
| python | {
"resource": ""
} |
q270445 | dict_entry_has_key | test | def dict_entry_has_key(line, key):
"""Return True if `line` is a dict entry that uses `key`.
Return False for multiline cases where the line should not be removed by
itself.
"""
if '#' in line:
return False
result = re.match(r'\s*(.*)\s*:\s*(.*),\s*$', line)
if not result:
return False
try:
| python | {
"resource": ""
} |
q270446 | is_literal_or_name | test | def is_literal_or_name(value):
"""Return True if value is a literal or a name."""
try:
ast.literal_eval(value)
return True
except (SyntaxError, ValueError):
pass
if value.strip() in ['dict()', 'list()', 'set()']:
return True
# | python | {
"resource": ""
} |
q270447 | useless_pass_line_numbers | test | def useless_pass_line_numbers(source):
"""Yield line numbers of unneeded "pass" statements."""
sio = io.StringIO(source)
previous_token_type = None
last_pass_row = None
last_pass_indentation = None
previous_line = ''
for token in tokenize.generate_tokens(sio.readline):
token_type = token[0]
start_row = token[2][0]
line = token[4]
is_pass = (token_type == tokenize.NAME and line.strip() == 'pass')
| python | {
"resource": ""
} |
q270448 | filter_useless_pass | test | def filter_useless_pass(source):
"""Yield code with useless "pass" lines removed."""
try:
marked_lines = frozenset(useless_pass_line_numbers(source))
| python | {
"resource": ""
} |
q270449 | get_indentation | test | def get_indentation(line):
"""Return leading whitespace."""
if line.strip():
| python | {
"resource": ""
} |
q270450 | get_line_ending | test | def get_line_ending(line):
"""Return line ending."""
non_whitespace_index = len(line.rstrip()) - len(line)
if not non_whitespace_index: | python | {
"resource": ""
} |
q270451 | fix_code | test | def fix_code(source, additional_imports=None, expand_star_imports=False,
remove_all_unused_imports=False, remove_duplicate_keys=False,
remove_unused_variables=False, ignore_init_module_imports=False):
"""Return code with all filtering run on it."""
if not source:
return source
# pyflakes does not handle "nonlocal" correctly.
if 'nonlocal' in source:
remove_unused_variables = False
filtered_source = None
while True:
| python | {
"resource": ""
} |
q270452 | _split_comma_separated | test | def _split_comma_separated(string):
"""Return a set of | python | {
"resource": ""
} |
q270453 | is_python_file | test | def is_python_file(filename):
"""Return True if filename is Python file."""
if filename.endswith('.py'):
return True
try:
with open_with_encoding(
filename,
None,
limit_byte_check=MAX_PYTHON_FILE_DETECTION_BYTES) as f:
text = f.read(MAX_PYTHON_FILE_DETECTION_BYTES)
if not text:
| python | {
"resource": ""
} |
q270454 | is_exclude_file | test | def is_exclude_file(filename, exclude):
"""Return True if file matches exclude pattern."""
base_name = os.path.basename(filename)
if base_name.startswith('.'):
return True
for pattern in | python | {
"resource": ""
} |
q270455 | find_files | test | def find_files(filenames, recursive, exclude):
"""Yield filenames."""
while filenames:
name = filenames.pop(0)
if recursive and os.path.isdir(name):
for root, directories, children in os.walk(name):
filenames += [os.path.join(root, f) for f in children
if match_file(os.path.join(root, f),
| python | {
"resource": ""
} |
q270456 | _main | test | def _main(argv, standard_out, standard_error):
"""Return exit status.
0 means no error.
"""
import argparse
parser = argparse.ArgumentParser(description=__doc__, prog='autoflake')
parser.add_argument('-c', '--check', action='store_true',
help='return error code if changes are needed')
parser.add_argument('-i', '--in-place', action='store_true',
help='make changes to files instead of printing diffs')
parser.add_argument('-r', '--recursive', action='store_true',
help='drill down directories recursively')
parser.add_argument('--exclude', metavar='globs',
help='exclude file/directory names that match these '
'comma-separated globs')
parser.add_argument('--imports',
help='by default, only unused standard library '
'imports are removed; specify a comma-separated '
'list of additional modules/packages')
parser.add_argument('--expand-star-imports', action='store_true',
help='expand wildcard star imports with undefined '
'names; this only triggers if there is only '
'one star import in the file; this is skipped if '
'there are any uses of `__all__` or `del` in the '
'file')
parser.add_argument('--remove-all-unused-imports', action='store_true',
help='remove all unused imports (not just those from '
'the standard library)')
parser.add_argument('--ignore-init-module-imports', action='store_true',
help='exclude __init__.py when removing unused '
'imports')
parser.add_argument('--remove-duplicate-keys', action='store_true',
| python | {
"resource": ""
} |
q270457 | ObtainLeaseResponsePayload.read | test | def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the ObtainLease response payload and decode it
into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be decoded. Optional,
defaults to KMIP 1.0.
Raises:
ValueError: Raised if the data attribute is missing from the
encoded payload.
"""
super(ObtainLeaseResponsePayload, self).read(
input_stream,
kmip_version=kmip_version
)
local_stream = utils.BytearrayStream(input_stream.read(self.length))
if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream):
self._unique_identifier = primitives.TextString(
tag=enums.Tags.UNIQUE_IDENTIFIER
)
self._unique_identifier.read(
local_stream,
| python | {
"resource": ""
} |
q270458 | ObtainLeaseResponsePayload.write | test | def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the ObtainLease response payload to a stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0.
Raises:
ValueError: Raised if the data attribute is not defined.
"""
local_stream = utils.BytearrayStream()
if self._unique_identifier:
self._unique_identifier.write(
local_stream,
kmip_version=kmip_version
)
if self._lease_time:
self._lease_time.write(
| python | {
"resource": ""
} |
q270459 | CancelRequestPayload.write | test | def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the Cancel request payload to a stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0.
Raises:
ValueError: Raised if the data attribute is not defined.
"""
| python | {
"resource": ""
} |
q270460 | CancelResponsePayload.read | test | def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the Cancel response payload and decode it into
its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be decoded. Optional,
defaults to KMIP 1.0.
Raises:
ValueError: Raised if the data attribute is missing from the
encoded payload.
"""
super(CancelResponsePayload, self).read(
input_stream,
kmip_version=kmip_version
)
local_stream = utils.BytearrayStream(input_stream.read(self.length))
if self.is_tag_next(
enums.Tags.ASYNCHRONOUS_CORRELATION_VALUE,
local_stream
):
self._asynchronous_correlation_value = primitives.ByteString(
tag=enums.Tags.ASYNCHRONOUS_CORRELATION_VALUE
| python | {
"resource": ""
} |
q270461 | Name.create | test | def create(cls, name_value, name_type):
'''
Returns a Name object, populated with the given value and type
'''
if isinstance(name_value, Name.NameValue):
value = name_value
elif isinstance(name_value, str):
value = cls.NameValue(name_value)
else:
name = 'Name'
msg = exceptions.ErrorStrings.BAD_EXP_RECV
member = 'name_value'
raise TypeError(msg.format('{0}.{1}'.format(name, member),
'name_value', type(Name.NameValue),
type(name_value)))
if isinstance(name_type, Name.NameType):
n_type = name_type
elif isinstance(name_type, Enum):
n_type = cls.NameType(name_type)
else:
| python | {
"resource": ""
} |
q270462 | Digest.read | test | def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the Digest object and decode it into its
constituent parts.
Args:
istream (Stream): A data stream containing encoded object data,
supporting a read method; usually a BytearrayStream object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be decoded. Optional,
defaults to KMIP 1.0.
"""
super(Digest, self).read(istream, kmip_version=kmip_version)
| python | {
"resource": ""
} |
q270463 | Digest.write | test | def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the Digest object to a stream.
Args:
ostream (Stream): A data stream in which to encode object data,
supporting a write method; usually a BytearrayStream object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0.
"""
tstream = BytearrayStream()
| python | {
"resource": ""
} |
q270464 | Digest.create | test | def create(cls,
hashing_algorithm=HashingAlgorithmEnum.SHA_256,
digest_value=b'',
key_format_type=KeyFormatTypeEnum.RAW):
"""
Construct a Digest object from provided digest values.
Args:
hashing_algorithm (HashingAlgorithm): An enumeration representing
the hash algorithm used to compute the digest. Optional,
defaults to HashingAlgorithm.SHA_256.
digest_value (byte string): The bytes of the digest hash. Optional,
defaults to the empty byte string.
key_format_type (KeyFormatType): An enumeration representing the
format of the key corresponding to the digest. Optional,
defaults to KeyFormatType.RAW.
Returns:
Digest: The newly created Digest.
Example:
>>> x = Digest.create(HashingAlgorithm.MD5, b'\x00',
... KeyFormatType.RAW)
>>> x.hashing_algorithm
HashingAlgorithm(value=HashingAlgorithm.MD5)
| python | {
"resource": ""
} |
q270465 | ApplicationSpecificInformation.read | test | def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the ApplicationSpecificInformation object and
decode it into its constituent parts.
Args:
istream (Stream): A data stream containing encoded object data,
supporting a read method; usually a BytearrayStream object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be decoded. Optional,
defaults to KMIP 1.0.
"""
super(ApplicationSpecificInformation, self).read(
| python | {
"resource": ""
} |
q270466 | ApplicationSpecificInformation.write | test | def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the ApplicationSpecificInformation object to a
stream.
Args:
ostream (Stream): A data stream in which to encode object data,
supporting a write method; usually a BytearrayStream object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0.
"""
tstream = BytearrayStream()
| python | {
"resource": ""
} |
q270467 | ApplicationSpecificInformation.create | test | def create(cls, application_namespace, application_data):
"""
Construct an ApplicationSpecificInformation object from provided data
and namespace values.
Args:
application_namespace (str): The name of the application namespace.
application_data (str): Application data related to the namespace.
Returns:
ApplicationSpecificInformation: The newly created set of
application information.
Example:
>>> x = ApplicationSpecificInformation.create('namespace', 'data')
>>> x.application_namespace.value
| python | {
"resource": ""
} |
q270468 | DerivationParameters.read | test | def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the DerivationParameters struct and decode it
into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be decoded. Optional,
defaults to KMIP 1.0.
"""
super(DerivationParameters, self).read(
input_stream,
kmip_version=kmip_version
)
local_stream = BytearrayStream(input_stream.read(self.length))
if self.is_tag_next(
enums.Tags.CRYPTOGRAPHIC_PARAMETERS,
local_stream
):
self._cryptographic_parameters = CryptographicParameters()
self._cryptographic_parameters.read(
local_stream,
kmip_version=kmip_version
)
if self.is_tag_next(enums.Tags.INITIALIZATION_VECTOR, local_stream):
self._initialization_vector = ByteString(
tag=enums.Tags.INITIALIZATION_VECTOR
| python | {
"resource": ""
} |
q270469 | DerivationParameters.write | test | def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the DerivationParameters struct to a stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0.
"""
local_stream = BytearrayStream()
if self._cryptographic_parameters:
self._cryptographic_parameters.write(
local_stream,
kmip_version=kmip_version
)
if self._initialization_vector:
self._initialization_vector.write(
local_stream,
kmip_version=kmip_version
)
if self._derivation_data:
self._derivation_data.write(
| python | {
"resource": ""
} |
q270470 | GetRequestPayload.read | test | def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the Get request payload and decode it into its
constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be decoded. Optional,
defaults to KMIP 1.0.
"""
super(GetRequestPayload, self).read(
input_stream,
kmip_version=kmip_version
)
local_stream = utils.BytearrayStream(input_stream.read(self.length))
if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream):
self._unique_identifier = primitives.TextString(
tag=enums.Tags.UNIQUE_IDENTIFIER
)
self._unique_identifier.read(
local_stream,
kmip_version=kmip_version
)
if self.is_tag_next(enums.Tags.KEY_FORMAT_TYPE, local_stream):
self._key_format_type = primitives.Enumeration(
enum=enums.KeyFormatType,
| python | {
"resource": ""
} |
q270471 | GetRequestPayload.write | test | def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the Get request payload to a stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0.
"""
local_stream = utils.BytearrayStream()
if self._unique_identifier is not None:
self._unique_identifier.write(
local_stream,
kmip_version=kmip_version
)
if self._key_format_type is not None:
self._key_format_type.write(
local_stream,
kmip_version=kmip_version
)
if self._key_compression_type | python | {
"resource": ""
} |
q270472 | GetResponsePayload.read | test | def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the Get response payload and decode it
into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be decoded. Optional,
defaults to KMIP 1.0.
Raises:
ValueError: Raised if the object type, unique identifier, or
secret attributes are missing from the encoded payload.
"""
super(GetResponsePayload, self).read(
input_stream,
kmip_version=kmip_version
)
local_stream = utils.BytearrayStream(input_stream.read(self.length))
if self.is_tag_next(enums.Tags.OBJECT_TYPE, local_stream):
self._object_type = primitives.Enumeration(
enum=enums.ObjectType,
tag=enums.Tags.OBJECT_TYPE
)
self._object_type.read(local_stream, kmip_version=kmip_version)
else:
raise ValueError(
"Parsed payload encoding is missing the object type field."
| python | {
"resource": ""
} |
q270473 | GetResponsePayload.write | test | def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the Get response payload to a stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0.
Raises:
ValueError: Raised if the object type, unique identifier, or
secret attributes are missing from the payload struct.
"""
local_stream = utils.BytearrayStream()
if self.object_type:
self._object_type.write(local_stream, kmip_version=kmip_version)
else:
raise ValueError("Payload is missing the object type field.")
if self.unique_identifier:
self._unique_identifier.write(
local_stream,
kmip_version=kmip_version
| python | {
"resource": ""
} |
q270474 | SignatureVerifyRequestPayload.read | test | def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the SignatureVerify request payload and decode
it into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be decoded. Optional,
defaults to KMIP 1.0.
Raises:
ValueError: Raised if the data attribute is missing from the
encoded payload.
"""
super(SignatureVerifyRequestPayload, self).read(
input_stream,
kmip_version=kmip_version
)
local_stream = utils.BytearrayStream(input_stream.read(self.length))
if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream):
self._unique_identifier = primitives.TextString(
tag=enums.Tags.UNIQUE_IDENTIFIER
)
self._unique_identifier.read(
local_stream,
kmip_version=kmip_version
)
if self.is_tag_next(enums.Tags.CRYPTOGRAPHIC_PARAMETERS, local_stream):
self._cryptographic_parameters = \ | python | {
"resource": ""
} |
q270475 | SignatureVerifyRequestPayload.write | test | def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the SignatureVerify request payload to a
stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0.
Raises:
ValueError: Raised if the data attribute is not defined.
"""
local_stream = utils.BytearrayStream()
if self._unique_identifier:
self._unique_identifier.write(
local_stream,
kmip_version=kmip_version
)
if self._cryptographic_parameters:
self._cryptographic_parameters.write(
local_stream,
kmip_version=kmip_version
)
if self._data:
self._data.write(local_stream, kmip_version=kmip_version)
if self._digested_data:
self._digested_data.write(local_stream, kmip_version=kmip_version)
if self._signature_data:
| python | {
"resource": ""
} |
q270476 | SignatureVerifyResponsePayload.read | test | def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the SignatureVerify response payload and decode
it into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be decoded. Optional,
defaults to KMIP 1.0.
Raises:
ValueError: Raised if the data attribute is missing from the
encoded payload.
"""
super(SignatureVerifyResponsePayload, self).read(
input_stream,
kmip_version=kmip_version
)
local_stream = utils.BytearrayStream(input_stream.read(self.length))
if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream):
self._unique_identifier = primitives.TextString(
tag=enums.Tags.UNIQUE_IDENTIFIER
)
self._unique_identifier.read(
local_stream,
kmip_version=kmip_version
)
else:
raise ValueError(
"Parsed payload encoding is missing the unique identifier "
"field."
)
if self.is_tag_next(enums.Tags.VALIDITY_INDICATOR, local_stream):
self._validity_indicator = primitives.Enumeration(
enums.ValidityIndicator,
tag=enums.Tags.VALIDITY_INDICATOR
)
self._validity_indicator.read(
local_stream,
| python | {
"resource": ""
} |
q270477 | KmipEngine.process_request | test | def process_request(self, request, credential=None):
"""
Process a KMIP request message.
This routine is the main driver of the KmipEngine. It breaks apart and
processes the request header, handles any message errors that may
result, and then passes the set of request batch items on for
processing. This routine is thread-safe, allowing multiple client
connections to use the same KmipEngine.
Args:
request (RequestMessage): The request message containing the batch
items to be processed.
credential (string): Identifying information about the client
obtained from the client certificate. Optional, defaults to
None.
Returns:
ResponseMessage: The response containing all of the results from
the request batch items.
"""
self._client_identity = [None, None]
header = request.request_header
# Process the protocol version
self._set_protocol_version(header.protocol_version)
# Process the maximum response size
max_response_size = None
if header.maximum_response_size:
max_response_size = header.maximum_response_size.value
# Process the time stamp
now = int(time.time())
if header.time_stamp:
then = header.time_stamp.value
if (now >= then) and ((now - then) < 60):
self._logger.info("Received request at time: {0}".format(
time.strftime(
"%Y-%m-%d %H:%M:%S",
time.gmtime(then)
)
))
else:
if now < then:
self._logger.warning(
"Received request with future timestamp. Received "
"timestamp: {0}, Current timestamp: {1}".format(
then,
now
)
)
raise exceptions.InvalidMessage(
"Future request rejected by server."
)
else:
self._logger.warning(
"Received request with old timestamp. Possible "
"replay attack. Received timestamp: {0}, Current "
"timestamp: {1}".format(then, now)
)
raise exceptions.InvalidMessage(
"Stale request rejected by server."
)
else:
self._logger.info("Received request at time: {0}".format(
time.strftime(
"%Y-%m-%d %H:%M:%S",
time.gmtime(now)
)
))
# Process the asynchronous indicator
self.is_asynchronous = False
if header.asynchronous_indicator is | python | {
"resource": ""
} |
q270478 | KmipEngine.build_error_response | test | def build_error_response(self, version, reason, message):
"""
Build a simple ResponseMessage with a single error result.
Args:
version (ProtocolVersion): The protocol version the response
should be addressed with.
reason (ResultReason): An enumeration classifying the type of
error occurred.
message (str): A string providing additional information about
the error.
Returns:
ResponseMessage: The simple ResponseMessage containing a
single error result. | python | {
"resource": ""
} |
q270479 | KmipEngine._process_template_attribute | test | def _process_template_attribute(self, template_attribute):
"""
Given a kmip.core TemplateAttribute object, extract the attribute
value data into a usable dictionary format.
"""
attributes = {}
if len(template_attribute.names) > 0:
raise exceptions.ItemNotFound(
"Attribute templates are not supported."
)
for attribute in template_attribute.attributes:
name = attribute.attribute_name.value
if not self._attribute_policy.is_attribute_supported(name):
raise exceptions.InvalidField(
"The {0} attribute is unsupported.".format(name)
)
if self._attribute_policy.is_attribute_multivalued(name):
values = attributes.get(name, list())
if (not attribute.attribute_index) and len(values) > 0:
raise exceptions.InvalidField(
"Attribute index missing from multivalued attribute."
)
values.append(attribute.attribute_value)
| python | {
"resource": ""
} |
q270480 | KmipEngine._get_attributes_from_managed_object | test | def _get_attributes_from_managed_object(self, managed_object, attr_names):
"""
Given a kmip.pie object and a list of attribute names, attempt to get
all of the existing attribute values from the object.
"""
attr_factory = attribute_factory.AttributeFactory()
retrieved_attributes = list()
if not attr_names:
attr_names = self._attribute_policy.get_all_attribute_names()
for attribute_name in attr_names:
object_type = managed_object._object_type
if not self._attribute_policy.is_attribute_supported(
attribute_name
):
continue
if self._attribute_policy.is_attribute_applicable_to_object_type(
attribute_name,
object_type
):
try:
attribute_value = self._get_attribute_from_managed_object(
managed_object,
attribute_name
)
except Exception:
attribute_value = None
if attribute_value is not None:
if self._attribute_policy.is_attribute_multivalued(
attribute_name
):
for count, value in enumerate(attribute_value):
| python | {
"resource": ""
} |
q270481 | KmipEngine._get_attribute_from_managed_object | test | def _get_attribute_from_managed_object(self, managed_object, attr_name):
"""
Get the attribute value from the kmip.pie managed object.
"""
if attr_name == 'Unique Identifier':
return str(managed_object.unique_identifier)
elif attr_name == 'Name':
names = list()
for name in managed_object.names:
name = attributes.Name(
attributes.Name.NameValue(name),
attributes.Name.NameType(
enums.NameType.UNINTERPRETED_TEXT_STRING
)
)
names.append(name)
return names
elif attr_name == 'Object Type':
return managed_object._object_type
elif attr_name == 'Cryptographic Algorithm':
return managed_object.cryptographic_algorithm
elif attr_name == 'Cryptographic Length':
return managed_object.cryptographic_length
elif attr_name == 'Cryptographic Parameters':
return None
elif attr_name == 'Cryptographic Domain Parameters':
return None
elif attr_name == 'Certificate Type':
return managed_object.certificate_type
elif attr_name == 'Certificate Length':
return None
elif attr_name == 'X.509 Certificate Identifier':
return None
elif attr_name == 'X.509 Certificate Subject':
return None
elif attr_name == 'X.509 Certificate Issuer':
return None
elif attr_name == 'Certificate Identifier':
return None
elif attr_name == 'Certificate Subject':
return None
elif attr_name == 'Certificate Issuer':
return None
elif attr_name == 'Digital Signature Algorithm':
return None
elif attr_name == 'Digest':
return None
elif attr_name == 'Operation Policy Name':
return managed_object.operation_policy_name
elif attr_name == 'Cryptographic Usage Mask':
return managed_object.cryptographic_usage_masks
elif attr_name == 'Lease Time':
return None
elif attr_name == 'Usage Limits':
return None
elif attr_name == 'State':
| python | {
"resource": ""
} |
q270482 | KmipEngine._set_attributes_on_managed_object | test | def _set_attributes_on_managed_object(self, managed_object, attributes):
"""
Given a kmip.pie object and a dictionary of attributes, attempt to set
the attribute values on the object.
"""
for attribute_name, attribute_value in six.iteritems(attributes):
object_type = managed_object._object_type
if self._attribute_policy.is_attribute_applicable_to_object_type(
attribute_name,
object_type):
self._set_attribute_on_managed_object(
managed_object,
(attribute_name, attribute_value)
)
else:
| python | {
"resource": ""
} |
q270483 | KmipEngine._set_attribute_on_managed_object | test | def _set_attribute_on_managed_object(self, managed_object, attribute):
"""
Set the attribute value on the kmip.pie managed object.
"""
attribute_name = attribute[0]
attribute_value = attribute[1]
if self._attribute_policy.is_attribute_multivalued(attribute_name):
if attribute_name == 'Name':
managed_object.names.extend(
[x.name_value.value for x in attribute_value]
)
for name in managed_object.names:
if managed_object.names.count(name) > 1:
raise exceptions.InvalidField(
"Cannot set duplicate name values."
)
else:
# TODO (peterhamilton) Remove when all attributes are supported
raise exceptions.InvalidField(
"The {0} attribute is unsupported.".format(attribute_name)
)
else:
field = None
value = attribute_value.value
if attribute_name == 'Cryptographic Algorithm':
field = 'cryptographic_algorithm'
elif attribute_name == 'Cryptographic Length':
field = 'cryptographic_length'
elif attribute_name == 'Cryptographic Usage Mask':
field = 'cryptographic_usage_masks'
value = list()
for e in enums.CryptographicUsageMask:
if e.value & attribute_value.value:
value.append(e)
elif attribute_name == 'Operation Policy Name':
field = 'operation_policy_name'
| python | {
"resource": ""
} |
q270484 | KmipEngine.is_allowed | test | def is_allowed(
self,
policy_name,
session_user,
session_group,
object_owner,
object_type,
operation
):
"""
Determine if object access is allowed for the provided policy and
session settings.
"""
policy_section = self.get_relevant_policy_section(
policy_name,
session_group
)
if policy_section is None:
return False
object_policy = policy_section.get(object_type)
if not object_policy:
self._logger.warning(
"The '{0}' policy does not apply to {1} objects.".format(
policy_name,
self._get_enum_string(object_type)
)
)
return False
operation_object_policy = object_policy.get(operation)
if not operation_object_policy:
self._logger.warning(
"The '{0}' policy does not apply to {1} | python | {
"resource": ""
} |
q270485 | DecryptRequestPayload.write | test | def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the Decrypt request payload to a stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0.
Raises:
ValueError: Raised if the data attribute is not defined.
"""
local_stream = utils.BytearrayStream()
if self._unique_identifier:
self._unique_identifier.write(
local_stream,
kmip_version=kmip_version
)
if self._cryptographic_parameters:
self._cryptographic_parameters.write(
local_stream,
kmip_version=kmip_version
| python | {
"resource": ""
} |
q270486 | SecretFactory.create | test | def create(self, secret_type, value=None):
"""
Create a secret object of the specified type with the given value.
Args:
secret_type (ObjectType): An ObjectType enumeration specifying the
type of secret to create.
value (dict): A dictionary containing secret data. Optional,
defaults to None.
Returns:
secret: The newly constructed secret object.
Raises:
TypeError: If the provided secret type is unrecognized.
Example:
>>> factory.create(ObjectType.SYMMETRIC_KEY)
SymmetricKey(...)
"""
if secret_type is ObjectType.CERTIFICATE:
return self._create_certificate(value)
elif secret_type is ObjectType.SYMMETRIC_KEY:
return self._create_symmetric_key(value)
elif secret_type is ObjectType.PUBLIC_KEY: | python | {
"resource": ""
} |
q270487 | KmipServerConfig.set_setting | test | def set_setting(self, setting, value):
"""
Set a specific setting value.
This will overwrite the current setting value for the specified
setting.
Args:
setting (string): The name of the setting to set (e.g.,
'certificate_path', 'hostname'). Required.
value (misc): The value of the setting to set. Type varies based
on setting. Required.
Raises:
ConfigurationError: Raised if the setting is not supported or if
the setting value is invalid.
"""
if setting not in self._expected_settings + self._optional_settings:
raise exceptions.ConfigurationError(
"Setting '{0}' is not supported.".format(setting)
)
if setting == 'hostname':
self._set_hostname(value)
elif setting == 'port':
self._set_port(value)
elif setting == 'certificate_path':
self._set_certificate_path(value)
elif setting == 'key_path':
| python | {
"resource": ""
} |
q270488 | KmipServerConfig.load_settings | test | def load_settings(self, path):
"""
Load configuration settings from the file pointed to by path.
This will overwrite all current setting values.
Args:
path (string): The path to the configuration file containing
the settings to load. Required.
Raises:
ConfigurationError: Raised if the path does not point to an
existing file or if a setting value is invalid.
"""
if not os.path.exists(path):
raise exceptions.ConfigurationError(
| python | {
"resource": ""
} |
q270489 | UsageMaskType.process_bind_param | test | def process_bind_param(self, value, dialect):
"""
Returns the integer value of the usage mask bitmask. This value is
stored in the database.
Args:
value(list<enums.CryptographicUsageMask>): list of enums in the
usage mask
| python | {
"resource": ""
} |
q270490 | UsageMaskType.process_result_value | test | def process_result_value(self, value, dialect):
"""
Returns a new list of enums.CryptographicUsageMask Enums. This converts
the integer value into the list of enums.
Args:
value(int): The integer value stored in the database that is used
to create the list of enums.CryptographicUsageMask Enums.
| python | {
"resource": ""
} |
q270491 | LongInteger.read | test | def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the encoding of the LongInteger from the input stream.
Args:
istream (stream): A buffer containing the encoded bytes of a
LongInteger. Usually a BytearrayStream object. Required.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be decoded. Optional,
defaults to KMIP 1.0.
Raises:
InvalidPrimitiveLength: if the long integer encoding read in has
an invalid encoded | python | {
"resource": ""
} |
q270492 | LongInteger.write | test | def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the encoding of the LongInteger to the output stream.
Args:
ostream (stream): A buffer to contain the encoded bytes of a
LongInteger. Usually a BytearrayStream object. Required.
kmip_version (KMIPVersion): An enumeration defining the KMIP
| python | {
"resource": ""
} |
q270493 | LongInteger.validate | test | def validate(self):
"""
Verify that the value of the LongInteger is valid.
Raises:
TypeError: if the value is not of type int or long
ValueError: if the value cannot be represented by a signed 64-bit
integer
"""
if self.value is not None:
if not isinstance(self.value, six.integer_types):
raise TypeError('expected (one of): {0}, observed: {1}'.format(
six.integer_types, type(self.value)))
else:
| python | {
"resource": ""
} |
q270494 | BigInteger.read | test | def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the encoding of the BigInteger from the input stream.
Args:
istream (stream): A buffer containing the encoded bytes of the
value of a BigInteger. Usually a BytearrayStream object.
Required.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be decoded. Optional,
defaults to KMIP 1.0.
Raises:
InvalidPrimitiveLength: if the big integer encoding read in has
an invalid encoded length.
"""
super(BigInteger, self).read(istream, kmip_version=kmip_version)
# Check for a valid length before even trying to parse the value.
if self.length % 8:
raise exceptions.InvalidPrimitiveLength(
"invalid big integer length read; "
"expected: multiple of 8, observed: {0}".format(self.length))
sign = 1
binary = ''
# Read the value byte by byte and convert it into binary, padding each
# byte as needed.
for _ | python | {
"resource": ""
} |
q270495 | BigInteger.write | test | def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the encoding of the BigInteger to the output stream.
Args:
ostream (Stream): A buffer to contain the encoded bytes of a
BigInteger object. Usually a BytearrayStream object.
Required.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0.
"""
# Convert the value to binary and pad it as needed.
| python | {
"resource": ""
} |
q270496 | BigInteger.validate | test | def validate(self):
"""
Verify that the value of the BigInteger is valid.
Raises:
TypeError: if the value is not of type int or long
"""
if self.value is not None:
if not | python | {
"resource": ""
} |
q270497 | Enumeration.validate | test | def validate(self):
"""
Verify that the value of the Enumeration is valid.
Raises:
TypeError: if the enum is not of type Enum
ValueError: if the value is not of the expected Enum subtype or if
the value cannot be represented by an unsigned 32-bit integer
"""
if not isinstance(self.enum, enumeration.EnumMeta):
raise TypeError(
'enumeration type {0} must be of type EnumMeta'.format(
self.enum))
if self.value is not None:
if not isinstance(self.value, self.enum):
raise TypeError(
'enumeration {0} must be of type {1}'.format(
self.value, self.enum))
if type(self.value.value) not in six.integer_types:
| python | {
"resource": ""
} |
q270498 | Boolean.read_value | test | def read_value(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the value of the Boolean object from the input stream.
Args:
istream (Stream): A buffer containing the encoded bytes of the
value of a Boolean object. Usually a BytearrayStream object.
Required.
kmip_version (KMIPVersion): An enumeration defining the KMIP
| python | {
"resource": ""
} |
q270499 | Boolean.write_value | test | def write_value(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the value of the Boolean object to the output stream.
Args:
ostream (Stream): A buffer to contain the encoded bytes of the
value of a Boolean object. Usually a BytearrayStream object.
Required.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.