signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def get_timezone(): | return dates.get_timezone(_get_tz())<EOL> | Build a ``babel.Timezone`` based on tz factory
:return: ``babel.Timezone`` | f15820:m5 |
def find_package_data(<EOL>where="<STR_LIT:.>",<EOL>package="<STR_LIT>",<EOL>exclude=standard_exclude,<EOL>exclude_directories=standard_exclude_directories,<EOL>only_in_packages=True,<EOL>show_ignored=False): | out = {}<EOL>stack = [(convert_path(where), "<STR_LIT>", package, only_in_packages)]<EOL>while stack:<EOL><INDENT>where, prefix, package, only_in_packages = stack.pop(<NUM_LIT:0>)<EOL>for name in os.listdir(where):<EOL><INDENT>fn = os.path.join(where, name)<EOL>if os.path.isdir(fn):<EOL><INDENT>bad_name = False<EOL>for pattern in exclude_directories:<EOL><INDENT>if (fnmatchcase(name, pattern)<EOL>or fn.lower() == pattern.lower()):<EOL><INDENT>bad_name = True<EOL>if show_ignored:<EOL><INDENT>print >> sys.stderr, (<EOL>"<STR_LIT>"<EOL>% (fn, pattern))<EOL><DEDENT>break<EOL><DEDENT><DEDENT>if bad_name:<EOL><INDENT>continue<EOL><DEDENT>if (os.path.isfile(os.path.join(fn, "<STR_LIT>"))<EOL>and not prefix):<EOL><INDENT>if not package:<EOL><INDENT>new_package = name<EOL><DEDENT>else:<EOL><INDENT>new_package = package + "<STR_LIT:.>" + name<EOL><DEDENT>stack.append((fn, "<STR_LIT>", new_package, False))<EOL><DEDENT>else:<EOL><INDENT>stack.append((fn, prefix + name + "<STR_LIT:/>", package, only_in_packages))<EOL><DEDENT><DEDENT>elif package or not only_in_packages:<EOL><INDENT>bad_name = False<EOL>for pattern in exclude:<EOL><INDENT>if (fnmatchcase(name, pattern)<EOL>or fn.lower() == pattern.lower()):<EOL><INDENT>bad_name = True<EOL>if show_ignored:<EOL><INDENT>print >> sys.stderr, (<EOL>"<STR_LIT>"<EOL>% (fn, pattern))<EOL><DEDENT>break<EOL><DEDENT><DEDENT>if bad_name:<EOL><INDENT>continue<EOL><DEDENT>out.setdefault(package, []).append(prefix + name)<EOL><DEDENT><DEDENT><DEDENT>return out<EOL> | Return a dictionary suitable for use in ``package_data``
in a distutils ``setup.py`` file.
The dictionary looks like::
{"package": [files]}
Where ``files`` is a list of all the files in that package that
don"t match anything in ``exclude``.
If ``only_in_packages`` is true, then top-level directories that
are not packages won"t be included (but directories under packages
will).
Directories matching any pattern in ``exclude_directories`` will
be ignored; by default directories with leading ``.``, ``CVS``,
and ``_darcs`` will be ignored.
If ``show_ignored`` is true, then all the files that aren"t
included in package data are shown on stderr (for debugging
purposes).
Note patterns use wildcards, or can be exact paths (including
leading ``./``), and all searching is case-insensitive. | f15823:m1 |
def get_perm_model(): | try:<EOL><INDENT>return django_apps.get_model(settings.PERM_MODEL, require_ready=False)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ImproperlyConfigured("<STR_LIT>")<EOL><DEDENT>except LookupError:<EOL><INDENT>raise ImproperlyConfigured(<EOL>"<STR_LIT>".format(settings.PERM_MODEL)<EOL>)<EOL><DEDENT> | Returns the Perm model that is active in this project. | f15832:m0 |
def get_version(*file_paths): | filename = os.path.join(os.path.dirname(__file__), *file_paths)<EOL>version_file = open(filename).read()<EOL>version_match = re.search(r"<STR_LIT>",<EOL>version_file, re.M)<EOL>if version_match:<EOL><INDENT>return version_match.group(<NUM_LIT:1>)<EOL><DEDENT>raise RuntimeError('<STR_LIT>')<EOL> | Retrieves the version from fperms/__init__.py | f15853:m0 |
def count_words(file): | c = Counter()<EOL>with open(file, '<STR_LIT:r>') as f:<EOL><INDENT>for l in f:<EOL><INDENT>words = l.strip().split()<EOL>c.update(words)<EOL><DEDENT><DEDENT>return c<EOL> | Counts the word frequences in a list of sentences.
Note:
This is a helper function for parallel execution of `Vocabulary.from_text`
method. | f15861:m0 |
def grouper(n, iterable, padvalue=None): | return zip_longest(*[iter(iterable)]*n, fillvalue=padvalue)<EOL> | grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x') | f15863:m3 |
def order(self): | return len(self)<EOL> | Returns the number of nodes in the graph | f15863:c0:m10 |
def number_of_edges(self): | return sum([self.degree(x) for x in self.keys()])/<NUM_LIT:2><EOL> | Returns the number of nodes in the graph | f15863:c0:m11 |
def number_of_nodes(self): | return self.order()<EOL> | Returns the number of nodes in the graph | f15863:c0:m12 |
def random_walk(self, path_length, alpha=<NUM_LIT:0>, rand=random.Random(), start=None): | G = self<EOL>if start:<EOL><INDENT>path = [start]<EOL><DEDENT>else:<EOL><INDENT>path = [rand.choice(list(G.keys()))]<EOL><DEDENT>while len(path) < path_length:<EOL><INDENT>cur = path[-<NUM_LIT:1>]<EOL>if len(G[cur]) > <NUM_LIT:0>:<EOL><INDENT>if rand.random() >= alpha:<EOL><INDENT>path.append(rand.choice(G[cur]))<EOL><DEDENT>else:<EOL><INDENT>path.append(path[<NUM_LIT:0>])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return [str(node) for node in path]<EOL> | Returns a truncated random walk.
path_length: Length of the random walk.
alpha: probability of restarts.
start: the start node of the random walk. | f15863:c0:m13 |
def __init__(self, har_data=None): | if not har_data or not isinstance(har_data, dict):<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>self.har_data = har_data['<STR_LIT>']<EOL> | :param har_data: a ``dict`` representing the JSON of a HAR file
(i.e. - you need to load the HAR data into a string using json.loads or
requests.json() if you are pulling the data via HTTP. | f15871:c0:m0 |
def match_headers(self, entry, header_type, header, value, regex=True): | if header_type not in entry:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>for h in entry[header_type]['<STR_LIT>']:<EOL><INDENT>if h['<STR_LIT:name>'].lower() == header.lower() and h['<STR_LIT:value>'] is not None:<EOL><INDENT>if regex and re.search(value, h['<STR_LIT:value>'], flags=re.IGNORECASE):<EOL><INDENT>return True<EOL><DEDENT>elif value == h['<STR_LIT:value>']:<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT>return False<EOL> | Function to match headers.
Since the output of headers might use different case, like:
'content-type' vs 'Content-Type'
This function is case-insensitive
:param entry: entry object
:param header_type: ``str`` of header type. Valid values:
* 'request'
* 'response'
:param header: ``str`` of the header to search for
:param value: ``str`` of value to search for
:param regex: ``bool`` indicating whether to use regex or exact match
:returns: a ``bool`` indicating whether a match was found | f15871:c0:m1 |
@staticmethod<EOL><INDENT>def match_content_type(entry, content_type, regex=True):<DEDENT> | mimeType = entry['<STR_LIT>']['<STR_LIT:content>']['<STR_LIT>']<EOL>if regex and re.search(content_type, mimeType, flags=re.IGNORECASE):<EOL><INDENT>return True<EOL><DEDENT>elif content_type == mimeType:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL> | Matches the content type of a request using the mimeType metadata.
:param entry: ``dict`` of a single entry from a HarPage
:param content_type: ``str`` of regex to use for finding content type
:param regex: ``bool`` indicating whether to use regex or exact match. | f15871:c0:m2 |
def match_request_type(self, entry, request_type, regex=True): | if regex:<EOL><INDENT>return re.search(request_type, entry['<STR_LIT>']['<STR_LIT>'],<EOL>flags=re.IGNORECASE) is not None<EOL><DEDENT>else:<EOL><INDENT>return entry['<STR_LIT>']['<STR_LIT>'] == request_type<EOL><DEDENT> | Helper function that returns entries with a request type
matching the given `request_type` argument.
:param entry: entry object to analyze
:param request_type: ``str`` of request type to match
:param regex: ``bool`` indicating whether to use a regex or string match | f15871:c0:m3 |
@staticmethod<EOL><INDENT>def match_http_version(entry, http_version, regex=True):<DEDENT> | response_version = entry['<STR_LIT>']['<STR_LIT>']<EOL>if regex:<EOL><INDENT>return re.search(http_version, response_version,<EOL>flags=re.IGNORECASE) is not None<EOL><DEDENT>else:<EOL><INDENT>return response_version == http_version<EOL><DEDENT> | Helper function that returns entries with a request type
matching the given `request_type` argument.
:param entry: entry object to analyze
:param request_type: ``str`` of request type to match
:param regex: ``bool`` indicating whether to use a regex or string match | f15871:c0:m4 |
def match_status_code(self, entry, status_code, regex=True): | if regex:<EOL><INDENT>return re.search(status_code,<EOL>str(entry['<STR_LIT>']['<STR_LIT:status>'])) is not None<EOL><DEDENT>else:<EOL><INDENT>return str(entry['<STR_LIT>']['<STR_LIT:status>']) == status_code<EOL><DEDENT> | Helper function that returns entries with a status code matching
then given `status_code` argument.
NOTE: This is doing a STRING comparison NOT NUMERICAL
:param entry: entry object to analyze
:param status_code: ``str`` of status code to search for
:param request_type: ``regex`` of request type to match | f15871:c0:m5 |
def create_asset_timeline(self, asset_list): | results = dict()<EOL>for asset in asset_list:<EOL><INDENT>time_key = dateutil.parser.parse(asset['<STR_LIT>'])<EOL>load_time = int(asset['<STR_LIT:time>'])<EOL>if time_key in results:<EOL><INDENT>results[time_key].append(asset)<EOL><DEDENT>else:<EOL><INDENT>results[time_key] = [asset]<EOL><DEDENT>for _ in range(<NUM_LIT:1>, load_time):<EOL><INDENT>time_key = time_key + datetime.timedelta(milliseconds=<NUM_LIT:1>)<EOL>if time_key in results:<EOL><INDENT>results[time_key].append(asset)<EOL><DEDENT>else:<EOL><INDENT>results[time_key] = [asset]<EOL><DEDENT><DEDENT><DEDENT>return results<EOL> | Returns a ``dict`` of the timeline for the requested assets. The key is
a datetime object (down to the millisecond) of ANY time where at least
one of the requested assets was loaded. The value is a ``list`` of ALL
assets that were loading at that time.
:param asset_list: ``list`` of the assets to create a timeline for. | f15871:c0:m6 |
@property<EOL><INDENT>def pages(self):<DEDENT> | <EOL>pages = []<EOL>if any('<STR_LIT>' not in entry for entry in self.har_data['<STR_LIT>']):<EOL><INDENT>pages.append(HarPage('<STR_LIT>', har_parser=self))<EOL><DEDENT>for har_page in self.har_data['<STR_LIT>']:<EOL><INDENT>page = HarPage(har_page['<STR_LIT:id>'], har_parser=self)<EOL>pages.append(page)<EOL><DEDENT>return pages<EOL> | This is a list of HarPage objects, each of which represents a page
from the HAR file. | f15871:c0:m7 |
def __init__(self, page_id, har_parser=None, har_data=None): | self.page_id = page_id<EOL>if har_parser is None and har_data is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if har_parser:<EOL><INDENT>self.parser = har_parser<EOL><DEDENT>else:<EOL><INDENT>self.parser = HarParser(har_data=har_data)<EOL><DEDENT>self.asset_types = {'<STR_LIT:image>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:text>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:html>': '<STR_LIT:html>',<EOL>}<EOL>raw_data = self.parser.har_data<EOL>valid = False<EOL>if self.page_id == '<STR_LIT>':<EOL><INDENT>valid = True<EOL><DEDENT>for page in raw_data['<STR_LIT>']:<EOL><INDENT>if page['<STR_LIT:id>'] == self.page_id:<EOL><INDENT>valid = True<EOL>self.title = page['<STR_LIT:title>']<EOL>self.startedDateTime = page['<STR_LIT>']<EOL>self.pageTimings = page['<STR_LIT>']<EOL><DEDENT><DEDENT>if not valid:<EOL><INDENT>page_ids = [page['<STR_LIT:id>'] for page in raw_data['<STR_LIT>']]<EOL>raise PageNotFoundError(<EOL>'<STR_LIT>'.format(<EOL>self.page_id, page_ids)<EOL>)<EOL><DEDENT> | :param page_id: ``str`` of the page ID
:param parser: a HarParser object
:param har_data: ``dict`` of a file HAR file | f15871:c1:m0 |
def _get_asset_files(self, asset_type): | return self.filter_entries(content_type=self.asset_types[asset_type])<EOL> | Returns a list of all files of a certain type. | f15871:c1:m2 |
def _get_asset_size_trans(self, asset_type): | if asset_type == '<STR_LIT>':<EOL><INDENT>assets = self.entries<EOL><DEDENT>else:<EOL><INDENT>assets = getattr(self, '<STR_LIT>'.format(asset_type), None)<EOL><DEDENT>return self.get_total_size_trans(assets)<EOL> | Helper function to dynamically create *_size properties. | f15871:c1:m3 |
def _get_asset_size(self, asset_type): | if asset_type == '<STR_LIT>':<EOL><INDENT>assets = self.entries<EOL><DEDENT>else:<EOL><INDENT>assets = getattr(self, '<STR_LIT>'.format(asset_type), None)<EOL><DEDENT>return self.get_total_size(assets)<EOL> | Helper function to dynamically create *_size properties. | f15871:c1:m4 |
def _get_asset_load(self, asset_type): | if asset_type == '<STR_LIT>':<EOL><INDENT>return self.actual_page['<STR_LIT:time>']<EOL><DEDENT>elif asset_type == '<STR_LIT:content>':<EOL><INDENT>return self.pageTimings['<STR_LIT>']<EOL><DEDENT>elif asset_type == '<STR_LIT>':<EOL><INDENT>if self.page_id == '<STR_LIT>':<EOL><INDENT>return None<EOL><DEDENT>return self.pageTimings['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>return self.get_load_time(<EOL>content_type=self.asset_types[asset_type]<EOL>)<EOL><DEDENT> | Helper function to dynamically create *_load_time properties. Return
value is in ms. | f15871:c1:m5 |
def filter_entries(self, request_type=None, content_type=None,<EOL>status_code=None, http_version=None, regex=True): | results = []<EOL>for entry in self.entries:<EOL><INDENT>"""<STR_LIT>"""<EOL>valid_entry = True<EOL>p = self.parser<EOL>if request_type is not None and not p.match_request_type(<EOL>entry, request_type, regex=regex):<EOL><INDENT>valid_entry = False<EOL><DEDENT>if content_type is not None:<EOL><INDENT>if not self.parser.match_content_type(entry, content_type,<EOL>regex=regex):<EOL><INDENT>valid_entry = False<EOL><DEDENT><DEDENT>if status_code is not None and not p.match_status_code(<EOL>entry, status_code, regex=regex):<EOL><INDENT>valid_entry = False<EOL><DEDENT>if http_version is not None and not p.match_http_version(<EOL>entry, http_version, regex=regex):<EOL><INDENT>valid_entry = False<EOL><DEDENT>if valid_entry:<EOL><INDENT>results.append(entry)<EOL><DEDENT><DEDENT>return results<EOL> | Returns a ``list`` of entry objects based on the filter criteria.
:param request_type: ``str`` of request type (i.e. - GET or POST)
:param content_type: ``str`` of regex to use for finding content type
:param status_code: ``int`` of the desired status code
:param http_version: ``str`` of HTTP version of request
:param regex: ``bool`` indicating whether to use regex or exact match. | f15871:c1:m6 |
def get_load_time(self, request_type=None, content_type=None,<EOL>status_code=None, asynchronous=True, **kwargs): | entries = self.filter_entries(<EOL>request_type=request_type, content_type=content_type,<EOL>status_code=status_code<EOL>)<EOL>if "<STR_LIT>" in kwargs:<EOL><INDENT>asynchronous = kwargs['<STR_LIT>']<EOL><DEDENT>if not asynchronous:<EOL><INDENT>time = <NUM_LIT:0><EOL>for entry in entries:<EOL><INDENT>time += entry['<STR_LIT:time>']<EOL><DEDENT>return time<EOL><DEDENT>else:<EOL><INDENT>return len(self.parser.create_asset_timeline(entries))<EOL><DEDENT> | This method can return the TOTAL load time for the assets or the ACTUAL
load time, the difference being that the actual load time takes
asynchronous transactions into account. So, if you want the total load
time, set asynchronous=False.
EXAMPLE:
I want to know the load time for images on a page that has two images,
each of which took 2 seconds to download, but the browser downloaded
them at the same time.
self.get_load_time(content_types=['image']) (returns 2)
self.get_load_time(content_types=['image'], asynchronous=False) (returns 4) | f15871:c1:m7 |
def get_total_size(self, entries): | size = <NUM_LIT:0><EOL>for entry in entries:<EOL><INDENT>if entry['<STR_LIT>']['<STR_LIT>'] > <NUM_LIT:0>:<EOL><INDENT>size += entry['<STR_LIT>']['<STR_LIT>']<EOL><DEDENT><DEDENT>return size<EOL> | Returns the total size of a collection of entries.
:param entries: ``list`` of entries to calculate the total size of. | f15871:c1:m8 |
def get_total_size_trans(self, entries): | size = <NUM_LIT:0><EOL>for entry in entries:<EOL><INDENT>if entry['<STR_LIT>']['<STR_LIT>'] > <NUM_LIT:0>:<EOL><INDENT>size += entry['<STR_LIT>']['<STR_LIT>']<EOL><DEDENT><DEDENT>return size<EOL> | Returns the total size of a collection of entries - transferred.
NOTE: use with har file generated with chrome-har-capturer
:param entries: ``list`` of entries to calculate the total size of. | f15871:c1:m9 |
@cached_property<EOL><INDENT>def hostname(self):<DEDENT> | for header in self.entries[<NUM_LIT:0>]['<STR_LIT>']['<STR_LIT>']:<EOL><INDENT>if header['<STR_LIT:name>'] == '<STR_LIT>':<EOL><INDENT>return header['<STR_LIT:value>']<EOL><DEDENT><DEDENT> | Hostname of the initial request | f15871:c1:m10 |
@cached_property<EOL><INDENT>def url(self):<DEDENT> | if '<STR_LIT>' in self.entries[<NUM_LIT:0>] and '<STR_LIT:url>' in self.entries[<NUM_LIT:0>]['<STR_LIT>']:<EOL><INDENT>return self.entries[<NUM_LIT:0>]['<STR_LIT>']['<STR_LIT:url>']<EOL><DEDENT>return None<EOL> | The absolute URL of the initial request. | f15871:c1:m11 |
@cached_property<EOL><INDENT>def time_to_first_byte(self):<DEDENT> | <EOL>if self.page_id == '<STR_LIT>':<EOL><INDENT>return None<EOL><DEDENT>ttfb = <NUM_LIT:0><EOL>for entry in self.entries:<EOL><INDENT>if entry['<STR_LIT>']['<STR_LIT:status>'] == <NUM_LIT:200>:<EOL><INDENT>for k, v in iteritems(entry['<STR_LIT>']):<EOL><INDENT>if k != '<STR_LIT>':<EOL><INDENT>if v > <NUM_LIT:0>:<EOL><INDENT>ttfb += v<EOL><DEDENT><DEDENT><DEDENT>break<EOL><DEDENT>else:<EOL><INDENT>ttfb += entry['<STR_LIT:time>']<EOL><DEDENT><DEDENT>return ttfb<EOL> | Time to first byte of the page request in ms | f15871:c1:m13 |
@cached_property<EOL><INDENT>def get_requests(self):<DEDENT> | return self.filter_entries(request_type='<STR_LIT>')<EOL> | Returns a list of GET requests, each of which is an 'entry' data object | f15871:c1:m14 |
@cached_property<EOL><INDENT>def post_requests(self):<DEDENT> | return self.filter_entries(request_type='<STR_LIT>')<EOL> | Returns a list of POST requests, each of which is an 'entry' data object | f15871:c1:m15 |
@cached_property<EOL><INDENT>def actual_page(self):<DEDENT> | for entry in self.entries:<EOL><INDENT>if not (entry['<STR_LIT>']['<STR_LIT:status>'] >= <NUM_LIT> and<EOL>entry['<STR_LIT>']['<STR_LIT:status>'] <= <NUM_LIT>):<EOL><INDENT>return entry<EOL><DEDENT><DEDENT> | Returns the first entry object that does not have a redirect status,
indicating that it is the actual page we care about (after redirects). | f15871:c1:m16 |
def __init__(self, har_data, page_id=None,<EOL>decimal_precision=DECIMAL_PRECISION): | self.har_data = har_data<EOL>self.page_id = page_id<EOL>self.decimal_precision = decimal_precision<EOL> | :param har_data: A ``list`` of ``dict`` representing the JSON
of a HAR file. See the docstring of HarParser.__init__ for more detail.
:param page_id: IF a ``str`` of the page ID is provided, the
multiparser will return aggregate results for this specific page. If
not, it will assume that there is only one page in the run (this was
written specifically for that use case).
:param decimal_precision: ``int`` representing the precision of the
return values for the means and standard deviations provided by this
class. | f15873:c0:m0 |
def get_load_times(self, asset_type): | load_times = []<EOL>search_str = '<STR_LIT>'.format(asset_type)<EOL>for har_page in self.pages:<EOL><INDENT>val = getattr(har_page, search_str, None)<EOL>if val is not None:<EOL><INDENT>load_times.append(val)<EOL><DEDENT><DEDENT>return load_times<EOL> | Just a ``list`` of the load times of a certain asset type for each page
:param asset_type: ``str`` of the asset type to return load times for | f15873:c0:m1 |
def get_stdev(self, asset_type): | load_times = []<EOL>if asset_type == '<STR_LIT>':<EOL><INDENT>for page in self.pages:<EOL><INDENT>if page.time_to_first_byte is not None:<EOL><INDENT>load_times.append(page.time_to_first_byte)<EOL><DEDENT><DEDENT><DEDENT>elif asset_type not in self.asset_types and asset_type != '<STR_LIT>':<EOL><INDENT>raise ValueError('<STR_LIT>'.format(<EOL>'<STR_LIT:\n>'.join(self.asset_types)))<EOL><DEDENT>else:<EOL><INDENT>load_times = self.get_load_times(asset_type)<EOL><DEDENT>if not load_times or not sum(load_times):<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>return round(stdev(load_times),<EOL>self.decimal_precision)<EOL> | Returns the standard deviation for a set of a certain asset type.
:param asset_type: ``str`` of the asset type to calculate standard
deviation for.
:returns: A ``int`` or ``float`` of standard deviation, depending on
the self.decimal_precision | f15873:c0:m2 |
@property<EOL><INDENT>def pages(self):<DEDENT> | pages = []<EOL>for har_dict in self.har_data:<EOL><INDENT>har_parser = HarParser(har_data=har_dict)<EOL>if self.page_id:<EOL><INDENT>for page in har_parser.pages:<EOL><INDENT>if page.page_id == self.page_id:<EOL><INDENT>pages.append(page)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>pages = pages + har_parser.pages<EOL><DEDENT><DEDENT>return pages<EOL> | The aggregate pages of all the parser objects. | f15873:c0:m3 |
@cached_property<EOL><INDENT>def asset_types(self):<DEDENT> | return self.pages[<NUM_LIT:0>].asset_types<EOL> | Mimic the asset types stored in HarPage | f15873:c0:m4 |
@cached_property<EOL><INDENT>def time_to_first_byte(self):<DEDENT> | ttfb = []<EOL>for page in self.pages:<EOL><INDENT>if page.time_to_first_byte is not None:<EOL><INDENT>ttfb.append(page.time_to_first_byte)<EOL><DEDENT><DEDENT>return round(mean(ttfb), self.decimal_precision)<EOL> | The aggregate time to first byte for all pages. | f15873:c0:m5 |
@cached_property<EOL><INDENT>def page_load_time(self):<DEDENT> | load_times = self.get_load_times('<STR_LIT>')<EOL>return round(mean(load_times), self.decimal_precision)<EOL> | The average total load time for all runs (not weighted). | f15873:c0:m6 |
@cached_property<EOL><INDENT>def js_load_time(self):<DEDENT> | load_times = self.get_load_times('<STR_LIT>')<EOL>return round(mean(load_times), self.decimal_precision)<EOL> | Returns aggregate javascript load time. | f15873:c0:m7 |
@cached_property<EOL><INDENT>def css_load_time(self):<DEDENT> | load_times = self.get_load_times('<STR_LIT>')<EOL>return round(mean(load_times), self.decimal_precision)<EOL> | Returns aggregate css load time for all pages. | f15873:c0:m8 |
@cached_property<EOL><INDENT>def image_load_time(self):<DEDENT> | load_times = self.get_load_times('<STR_LIT:image>')<EOL>return round(mean(load_times), self.decimal_precision)<EOL> | Returns aggregate image load time for all pages. | f15873:c0:m9 |
@cached_property<EOL><INDENT>def html_load_time(self):<DEDENT> | load_times = self.get_load_times('<STR_LIT:html>')<EOL>return round(mean(load_times), self.decimal_precision)<EOL> | Returns aggregate html load time for all pages. | f15873:c0:m10 |
@cached_property<EOL><INDENT>def audio_load_time(self):<DEDENT> | load_times = self.get_load_times('<STR_LIT>')<EOL>return round(mean(load_times), self.decimal_precision)<EOL> | Returns aggregate audio load time for all pages. | f15873:c0:m11 |
@cached_property<EOL><INDENT>def video_load_time(self):<DEDENT> | load_times = self.get_load_times('<STR_LIT>')<EOL>return round(mean(load_times), self.decimal_precision)<EOL> | Returns aggregate video load time for all pages. | f15873:c0:m12 |
def database_healthcheck(): | from django.db import connection<EOL>connection.cursor()<EOL>return True<EOL> | Healthcheck for connecting to the default Django database | f15884:m0 |
def __init__(self, name, url, method='<STR_LIT>',<EOL>data=None, headers=None, auth=None,<EOL>status_code=<NUM_LIT:200>, timeout=<NUM_LIT:5>, allow_redirects=False,<EOL>text_in_response=None, value_at_json_path=None): | self.name = name<EOL>self.url = url<EOL>self.method = method<EOL>self.data = data<EOL>self.headers = headers<EOL>self.auth = auth<EOL>self.status_code = status_code<EOL>self.timeout = timeout<EOL>self.allow_redirects = allow_redirects<EOL>self.text_in_response = text_in_response<EOL>self.value_at_json_path = value_at_json_path<EOL> | :param name: the name of this check
:param url: url to request
:param method: HTTP method to use
:param data: optional data to send
:param headers: additional headers
:param auth: optional authentication
:param status_code: expected response status
:param timeout: max time to try loading
:param allow_redirects: whether redirects should be followed
:param text_in_response: expected text in response
:param value_at_json_path: expected value at path in json response,
tuple of (value, dotted path)
:type value_at_json_path: tuple | f15884:c1:m0 |
def load_healthchecks(self): | self.load_default_healthchecks()<EOL>if getattr(settings, '<STR_LIT>', True):<EOL><INDENT>self.autodiscover_healthchecks()<EOL><DEDENT>self._registry_loaded = True<EOL> | Loads healthchecks. | f15884:c3:m2 |
def load_default_healthchecks(self): | default_healthchecks = getattr(settings, '<STR_LIT>', DEFAULT_HEALTHCHECKS)<EOL>for healthcheck in default_healthchecks:<EOL><INDENT>healthcheck = import_string(healthcheck)<EOL>self.register_healthcheck(healthcheck)<EOL><DEDENT> | Loads healthchecks specified in settings.HEALTHCHECKS as dotted import
paths to the classes. Defaults are listed in `DEFAULT_HEALTHCHECKS`. | f15884:c3:m3 |
def autodiscover_healthchecks(self): | autodiscover_modules('<STR_LIT>', register_to=self)<EOL> | Loads healthchecks.py in all installed apps. Register healthchecks
in your healthchecks.py by calling `registry.register_healthcheck` | f15884:c3:m4 |
def register_healthcheck(self, healthcheck): | self._registry.append(healthcheck)<EOL> | Register a healthcheck. Call this method from your apps'
healthchecks.py and use autodiscovery for loading.
:param healthcheck: callable or callable class | f15884:c3:m5 |
def run_healthchecks(self): | if not self._registry_loaded:<EOL><INDENT>self.load_healthchecks()<EOL><DEDENT>def get_healthcheck_name(hc):<EOL><INDENT>if hasattr(hc, '<STR_LIT:name>'):<EOL><INDENT>return hc.name<EOL><DEDENT>return hc.__name__<EOL><DEDENT>responses = []<EOL>for healthcheck in self._registry:<EOL><INDENT>try:<EOL><INDENT>if inspect.isclass(healthcheck):<EOL><INDENT>healthcheck = healthcheck()<EOL><DEDENT>response = healthcheck()<EOL>if isinstance(response, bool):<EOL><INDENT>response = HealthcheckResponse(<EOL>name=get_healthcheck_name(healthcheck),<EOL>status=response,<EOL>)<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>response = HealthcheckResponse(<EOL>name=get_healthcheck_name(healthcheck),<EOL>status=False,<EOL>exception=str(e),<EOL>exception_class=e.__class__.__name__,<EOL>)<EOL><DEDENT>responses.append(response)<EOL><DEDENT>return responses<EOL> | Runs all registered healthchecks and returns a list of
HealthcheckResponse. | f15884:c3:m6 |
def template(template_name): | globals = None<EOL>if template_name.startswith('<STR_LIT>'):<EOL><INDENT>globals = dict()<EOL>globals['<STR_LIT>'] = var_type[template_name.split('<STR_LIT:_>')[<NUM_LIT:1>].upper()]<EOL><DEDENT>return jinja2_env.get_template(templates[template_name], globals=globals)<EOL> | Return a jinja template ready for rendering. If needed, global variables are initialized.
Parameters
----------
template_name: str, the name of the template as defined in the templates mapping
Returns
-------
The Jinja template ready for rendering | f15887:m0 |
def _plot_histogram(series, bins=<NUM_LIT:10>, figsize=(<NUM_LIT:6>, <NUM_LIT:4>), facecolor='<STR_LIT>'): | if base.get_vartype(series) == base.TYPE_DATE:<EOL><INDENT>fig = plt.figure(figsize=figsize)<EOL>plot = fig.add_subplot(<NUM_LIT>)<EOL>plot.set_ylabel('<STR_LIT>')<EOL>try:<EOL><INDENT>plot.hist(series.dropna().values, facecolor=facecolor, bins=bins)<EOL><DEDENT>except TypeError: <EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>plot = series.plot(kind='<STR_LIT>', figsize=figsize,<EOL>facecolor=facecolor,<EOL>bins=bins) <EOL><DEDENT>return plot<EOL> | Plot an histogram from the data and return the AxesSubplot object.
Parameters
----------
series : Series
The data to plot
figsize : tuple
The size of the figure (width, height) in inches, default (6,4)
facecolor : str
The color code.
Returns
-------
matplotlib.AxesSubplot
The plot. | f15888:m0 |
def histogram(series, **kwargs): | imgdata = BytesIO()<EOL>plot = _plot_histogram(series, **kwargs)<EOL>plot.figure.subplots_adjust(left=<NUM_LIT>, right=<NUM_LIT>, top=<NUM_LIT>, bottom=<NUM_LIT:0.1>, wspace=<NUM_LIT:0>, hspace=<NUM_LIT:0>)<EOL>plot.figure.savefig(imgdata)<EOL>imgdata.seek(<NUM_LIT:0>)<EOL>result_string = '<STR_LIT>' + quote(base64.b64encode(imgdata.getvalue()))<EOL>plt.close(plot.figure)<EOL>return result_string<EOL> | Plot an histogram of the data.
Parameters
----------
series: Series
The data to plot.
Returns
-------
str
The resulting image encoded as a string. | f15888:m1 |
def mini_histogram(series, **kwargs): | imgdata = BytesIO()<EOL>plot = _plot_histogram(series, figsize=(<NUM_LIT:2>, <NUM_LIT>), **kwargs)<EOL>plot.axes.get_yaxis().set_visible(False)<EOL>if LooseVersion(matplotlib.__version__) <= '<STR_LIT>':<EOL><INDENT>plot.set_axis_bgcolor("<STR_LIT:w>")<EOL><DEDENT>else:<EOL><INDENT>plot.set_facecolor("<STR_LIT:w>")<EOL><DEDENT>xticks = plot.xaxis.get_major_ticks()<EOL>for tick in xticks[<NUM_LIT:1>:-<NUM_LIT:1>]:<EOL><INDENT>tick.set_visible(False)<EOL>tick.label.set_visible(False)<EOL><DEDENT>for tick in (xticks[<NUM_LIT:0>], xticks[-<NUM_LIT:1>]):<EOL><INDENT>tick.label.set_fontsize(<NUM_LIT:8>)<EOL><DEDENT>plot.figure.subplots_adjust(left=<NUM_LIT>, right=<NUM_LIT>, top=<NUM_LIT:1>, bottom=<NUM_LIT>, wspace=<NUM_LIT:0>, hspace=<NUM_LIT:0>)<EOL>plot.figure.savefig(imgdata)<EOL>imgdata.seek(<NUM_LIT:0>)<EOL>result_string = '<STR_LIT>' + quote(base64.b64encode(imgdata.getvalue()))<EOL>plt.close(plot.figure)<EOL>return result_string<EOL> | Plot a small (mini) histogram of the data.
Parameters
----------
series: Series
The data to plot.
Returns
-------
str
The resulting image encoded as a string. | f15888:m2 |
def correlation_matrix(corrdf, title, **kwargs): | imgdata = BytesIO()<EOL>fig_cor, axes_cor = plt.subplots(<NUM_LIT:1>, <NUM_LIT:1>)<EOL>labels = corrdf.columns<EOL>matrix_image = axes_cor.imshow(corrdf, vmin=-<NUM_LIT:1>, vmax=<NUM_LIT:1>, interpolation="<STR_LIT>", cmap='<STR_LIT>')<EOL>plt.title(title, size=<NUM_LIT>)<EOL>plt.colorbar(matrix_image)<EOL>axes_cor.set_xticks(np.arange(<NUM_LIT:0>, corrdf.shape[<NUM_LIT:0>], corrdf.shape[<NUM_LIT:0>] * <NUM_LIT:1.0> / len(labels)))<EOL>axes_cor.set_yticks(np.arange(<NUM_LIT:0>, corrdf.shape[<NUM_LIT:1>], corrdf.shape[<NUM_LIT:1>] * <NUM_LIT:1.0> / len(labels)))<EOL>axes_cor.set_xticklabels(labels, rotation=<NUM_LIT>)<EOL>axes_cor.set_yticklabels(labels)<EOL>matrix_image.figure.savefig(imgdata, bbox_inches='<STR_LIT>')<EOL>imgdata.seek(<NUM_LIT:0>)<EOL>result_string = '<STR_LIT>' + quote(base64.b64encode(imgdata.getvalue()))<EOL>plt.close(matrix_image.figure)<EOL>return result_string<EOL> | Plot image of a matrix correlation.
Parameters
----------
corrdf: DataFrame
The matrix correlation to plot.
title: str
The matrix title
Returns
-------
str, The resulting image encoded as a string. | f15888:m3 |
def get_groupby_statistic(data): | if data.name is not None and data.name in _VALUE_COUNTS_MEMO:<EOL><INDENT>return _VALUE_COUNTS_MEMO[data.name]<EOL><DEDENT>value_counts_with_nan = data.value_counts(dropna=False)<EOL>value_counts_without_nan = value_counts_with_nan.reset_index().dropna().set_index('<STR_LIT:index>').iloc[:,<NUM_LIT:0>]<EOL>distinct_count_with_nan = value_counts_with_nan.count()<EOL>if value_counts_without_nan.index.inferred_type == "<STR_LIT>":<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>result = [value_counts_without_nan, distinct_count_with_nan]<EOL>if data.name is not None:<EOL><INDENT>_VALUE_COUNTS_MEMO[data.name] = result<EOL><DEDENT>return result<EOL> | Calculate value counts and distinct count of a variable (technically a Series).
The result is cached by column name in a global variable to avoid recomputing.
Parameters
----------
data : Series
The data type of the Series.
Returns
-------
list
value count and distinct count | f15889:m0 |
def get_vartype(data): | if data.name is not None and data.name in _MEMO:<EOL><INDENT>return _MEMO[data.name]<EOL><DEDENT>vartype = None<EOL>try:<EOL><INDENT>distinct_count = get_groupby_statistic(data)[<NUM_LIT:1>]<EOL>leng = len(data)<EOL>if distinct_count <= <NUM_LIT:1>:<EOL><INDENT>vartype = S_TYPE_CONST<EOL><DEDENT>elif pd.api.types.is_bool_dtype(data) or (distinct_count == <NUM_LIT:2> and pd.api.types.is_numeric_dtype(data)):<EOL><INDENT>vartype = TYPE_BOOL<EOL><DEDENT>elif pd.api.types.is_numeric_dtype(data):<EOL><INDENT>vartype = TYPE_NUM<EOL><DEDENT>elif pd.api.types.is_datetime64_dtype(data):<EOL><INDENT>vartype = TYPE_DATE<EOL><DEDENT>elif distinct_count == leng:<EOL><INDENT>vartype = S_TYPE_UNIQUE<EOL><DEDENT>else:<EOL><INDENT>vartype = TYPE_CAT<EOL><DEDENT><DEDENT>except:<EOL><INDENT>vartype = S_TYPE_UNSUPPORTED<EOL><DEDENT>if data.name is not None:<EOL><INDENT>_MEMO[data.name] = vartype<EOL><DEDENT>return vartype<EOL> | Infer the type of a variable (technically a Series).
The types supported are split in standard types and special types.
Standard types:
* Categorical (`TYPE_CAT`): the default type if no other one can be determined
* Numerical (`TYPE_NUM`): if it contains numbers
* Boolean (`TYPE_BOOL`): at this time only detected if it contains boolean values, see todo
* Date (`TYPE_DATE`): if it contains datetime
Special types:
* Constant (`S_TYPE_CONST`): if all values in the variable are equal
* Unique (`S_TYPE_UNIQUE`): if all values in the variable are different
* Unsupported (`S_TYPE_UNSUPPORTED`): if the variable is unsupported
The result is cached by column name in a global variable to avoid recomputing.
Parameters
----------
data : Series
The data type of the Series.
Returns
-------
str
The data type of the Series.
Notes
----
* Should improve verification when a categorical or numeric field has 3 values, it could be a categorical field
or just a boolean with NaN values
* #72: Numeric with low Distinct count should be treated as "Categorical" | f15889:m1 |
def clear_cache(): | global _MEMO, _VALUE_COUNTS_MEMO<EOL>_MEMO = {}<EOL>_VALUE_COUNTS_MEMO = {}<EOL> | Clear the cache stored as global variables | f15889:m2 |
def __init__(self, df, **kwargs): | sample = kwargs.get('<STR_LIT>', df.head())<EOL>description_set = describe_df(df, **kwargs)<EOL>self.html = to_html(sample,<EOL>description_set)<EOL>self.description_set = description_set<EOL> | Constructor see class documentation | f15890:c0:m0 |
def get_description(self): | return self.description_set<EOL> | Return the description (a raw statistical summary) of the dataset.
Returns
-------
dict
Containing the following keys:
* table: general statistics on the dataset
* variables: summary statistics for each variable
* freq: frequency table | f15890:c0:m1 |
def get_rejected_variables(self, threshold=<NUM_LIT>): | variable_profile = self.description_set['<STR_LIT>']<EOL>result = []<EOL>if hasattr(variable_profile, '<STR_LIT>'):<EOL><INDENT>result = variable_profile.index[variable_profile.correlation > threshold].tolist()<EOL><DEDENT>return result<EOL> | Return a list of variable names being rejected for high
correlation with one of remaining variables.
Parameters:
----------
threshold : float
Correlation value which is above the threshold are rejected
Returns
-------
list
The list of rejected variables or an empty list if the correlation has not been computed. | f15890:c0:m2 |
def to_file(self, outputfile=DEFAULT_OUTPUTFILE): | if outputfile != NO_OUTPUTFILE:<EOL><INDENT>if outputfile == DEFAULT_OUTPUTFILE:<EOL><INDENT>outputfile = '<STR_LIT>' + str(hash(self)) + "<STR_LIT>"<EOL><DEDENT>with codecs.open(outputfile, '<STR_LIT>', encoding='<STR_LIT:utf8>') as self.file:<EOL><INDENT>self.file.write(templates.template('<STR_LIT>').render(content=self.html))<EOL><DEDENT><DEDENT> | Write the report to a file.
By default a name is generated.
Parameters:
----------
outputfile : str
The name or the path of the file to generale including the extension (.html). | f15890:c0:m3 |
def to_html(self): | return templates.template('<STR_LIT>').render(content=self.html)<EOL> | Generate and return complete template as lengthy string
for using with frameworks.
Returns
-------
str
The HTML output. | f15890:c0:m4 |
def _repr_html_(self): | return self.html<EOL> | Used to output the HTML representation to a Jupyter notebook
Returns
-------
str
The HTML internal representation. | f15890:c0:m5 |
def __str__(self): | return "<STR_LIT>" + str(self.file.name)<EOL> | Overwrite of the str method.
Returns
-------
str
A string representation of the object. | f15890:c0:m6 |
def to_html(sample, stats_object): | n_obs = stats_object['<STR_LIT>']['<STR_LIT:n>']<EOL>value_formatters = formatters.value_formatters<EOL>row_formatters = formatters.row_formatters<EOL>if not isinstance(sample, pd.DataFrame):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if not isinstance(stats_object, dict):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if not set({'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'}).issubset(set(stats_object.keys())):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>")<EOL><DEDENT>def fmt(value, name):<EOL><INDENT>if pd.isnull(value):<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>if name in value_formatters:<EOL><INDENT>return value_formatters[name](value)<EOL><DEDENT>elif isinstance(value, float):<EOL><INDENT>return value_formatters[formatters.DEFAULT_FLOAT_FORMATTER](value)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>return unicode(value) <EOL><DEDENT>except NameError:<EOL><INDENT>return str(value) <EOL><DEDENT><DEDENT><DEDENT>def _format_row(freq, label, max_freq, row_template, n, extra_class='<STR_LIT>'):<EOL><INDENT>if max_freq != <NUM_LIT:0>:<EOL><INDENT>width = int(freq / max_freq * <NUM_LIT>) + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>width = <NUM_LIT:1><EOL><DEDENT>if width > <NUM_LIT:20>:<EOL><INDENT>label_in_bar = freq<EOL>label_after_bar = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>label_in_bar = "<STR_LIT>"<EOL>label_after_bar = freq<EOL><DEDENT>return row_template.render(label=label,<EOL>width=width,<EOL>count=freq,<EOL>percentage='<STR_LIT>'.format(freq / n * <NUM_LIT:100>),<EOL>extra_class=extra_class,<EOL>label_in_bar=label_in_bar,<EOL>label_after_bar=label_after_bar)<EOL><DEDENT>def freq_table(freqtable, n, table_template, row_template, max_number_to_print, nb_col=<NUM_LIT:6>):<EOL><INDENT>freq_rows_html = u'<STR_LIT>'<EOL>if max_number_to_print > n:<EOL><INDENT>max_number_to_print=n<EOL><DEDENT>if max_number_to_print < len(freqtable):<EOL><INDENT>freq_other = sum(freqtable.iloc[max_number_to_print:])<EOL>min_freq = freqtable.values[max_number_to_print]<EOL><DEDENT>else:<EOL><INDENT>freq_other = <NUM_LIT:0><EOL>min_freq = <NUM_LIT:0><EOL><DEDENT>freq_missing = n - sum(freqtable)<EOL>max_freq = max(freqtable.values[<NUM_LIT:0>], freq_other, freq_missing)<EOL>for label, freq in six.iteritems(freqtable.iloc[<NUM_LIT:0>:max_number_to_print]):<EOL><INDENT>freq_rows_html += _format_row(freq, label, max_freq, row_template, n)<EOL><DEDENT>if freq_other > min_freq:<EOL><INDENT>freq_rows_html += _format_row(freq_other,<EOL>"<STR_LIT>" % (freqtable.count() - max_number_to_print), max_freq, row_template, n,<EOL>extra_class='<STR_LIT>')<EOL><DEDENT>if freq_missing > min_freq:<EOL><INDENT>freq_rows_html += _format_row(freq_missing, "<STR_LIT>", max_freq, row_template, n, extra_class='<STR_LIT>')<EOL><DEDENT>return table_template.render(rows=freq_rows_html, varid=hash(idx), nb_col=nb_col)<EOL><DEDENT>def extreme_obs_table(freqtable, table_template, row_template, number_to_print, n, ascending = True):<EOL><INDENT>if "<STR_LIT>" in freqtable.index.inferred_type:<EOL><INDENT>freqtable.index = freqtable.index.astype(str)<EOL><DEDENT>sorted_freqTable = freqtable.sort_index()<EOL>if ascending:<EOL><INDENT>obs_to_print = sorted_freqTable.iloc[:number_to_print]<EOL><DEDENT>else:<EOL><INDENT>obs_to_print = sorted_freqTable.iloc[-number_to_print:]<EOL><DEDENT>freq_rows_html = '<STR_LIT>'<EOL>max_freq = max(obs_to_print.values)<EOL>for label, freq in six.iteritems(obs_to_print):<EOL><INDENT>freq_rows_html += _format_row(freq, label, max_freq, row_template, n)<EOL><DEDENT>return table_template.render(rows=freq_rows_html)<EOL><DEDENT>rows_html = u"<STR_LIT>"<EOL>messages = []<EOL>render_htmls = {}<EOL>for idx, row in stats_object['<STR_LIT>'].iterrows():<EOL><INDENT>formatted_values = {'<STR_LIT>': idx, '<STR_LIT>': hash(idx)}<EOL>row_classes = {}<EOL>for col, value in six.iteritems(row):<EOL><INDENT>formatted_values[col] = fmt(value, col)<EOL><DEDENT>for col in set(row.index) & six.viewkeys(row_formatters):<EOL><INDENT>row_classes[col] = row_formatters[col](row[col])<EOL>if row_classes[col] == "<STR_LIT>" and col in templates.messages:<EOL><INDENT>messages.append(templates.messages[col].format(formatted_values, varname = idx))<EOL><DEDENT><DEDENT>if row['<STR_LIT:type>'] in {'<STR_LIT>', '<STR_LIT>'}:<EOL><INDENT>formatted_values['<STR_LIT>'] = freq_table(stats_object['<STR_LIT>'][idx], n_obs,<EOL>templates.template('<STR_LIT>'), <EOL>templates.template('<STR_LIT>'), <EOL><NUM_LIT:3>, <EOL>templates.mini_freq_table_nb_col[row['<STR_LIT:type>']])<EOL>if row['<STR_LIT>'] > <NUM_LIT:50>:<EOL><INDENT>messages.append(templates.messages['<STR_LIT>'].format(formatted_values, varname = idx))<EOL>row_classes['<STR_LIT>'] = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>row_classes['<STR_LIT>'] = "<STR_LIT>"<EOL><DEDENT><DEDENT>if row['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>obs = stats_object['<STR_LIT>'][idx].index<EOL>formatted_values['<STR_LIT>'] = pd.DataFrame(obs[<NUM_LIT:0>:<NUM_LIT:3>], columns=["<STR_LIT>"]).to_html(classes="<STR_LIT>", index=False)<EOL>formatted_values['<STR_LIT>'] = pd.DataFrame(obs[-<NUM_LIT:3>:], columns=["<STR_LIT>"]).to_html(classes="<STR_LIT>", index=False)<EOL><DEDENT>if row['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>formatted_values['<STR_LIT>'] = idx<EOL>messages.append(templates.messages[row['<STR_LIT:type>']].format(formatted_values))<EOL><DEDENT>elif row['<STR_LIT:type>'] in {'<STR_LIT>', '<STR_LIT>', '<STR_LIT>'}:<EOL><INDENT>formatted_values['<STR_LIT>'] = idx<EOL>messages.append(templates.messages[row['<STR_LIT:type>']].format(formatted_values))<EOL><DEDENT>else:<EOL><INDENT>formatted_values['<STR_LIT>'] = freq_table(stats_object['<STR_LIT>'][idx], n_obs,<EOL>templates.template('<STR_LIT>'), templates.template('<STR_LIT>'), <NUM_LIT:10>)<EOL>formatted_values['<STR_LIT>'] = extreme_obs_table(stats_object['<STR_LIT>'][idx], templates.template('<STR_LIT>'), templates.template('<STR_LIT>'), <NUM_LIT:5>, n_obs, ascending = True)<EOL>formatted_values['<STR_LIT>'] = extreme_obs_table(stats_object['<STR_LIT>'][idx], templates.template('<STR_LIT>'), templates.template('<STR_LIT>'), <NUM_LIT:5>, n_obs, ascending = False)<EOL><DEDENT>rows_html += templates.row_templates_dict[row['<STR_LIT:type>']].render(values=formatted_values, row_classes=row_classes)<EOL><DEDENT>render_htmls['<STR_LIT>'] = rows_html<EOL>formatted_values = {k: fmt(v, k) for k, v in six.iteritems(stats_object['<STR_LIT>'])}<EOL>row_classes={}<EOL>for col in six.viewkeys(stats_object['<STR_LIT>']) & six.viewkeys(row_formatters):<EOL><INDENT>row_classes[col] = row_formatters[col](stats_object['<STR_LIT>'][col])<EOL>if row_classes[col] == "<STR_LIT>" and col in templates.messages:<EOL><INDENT>messages.append(templates.messages[col].format(formatted_values, varname = idx))<EOL><DEDENT><DEDENT>messages_html = u'<STR_LIT>'<EOL>for msg in messages:<EOL><INDENT>messages_html += templates.message_row.format(message=msg)<EOL><DEDENT>overview_html = templates.template('<STR_LIT>').render(values=formatted_values, row_classes = row_classes, messages=messages_html)<EOL>render_htmls['<STR_LIT>'] = overview_html<EOL>if len(stats_object['<STR_LIT>']['<STR_LIT>']) > <NUM_LIT:0>:<EOL><INDENT>pearson_matrix = plot.correlation_matrix(stats_object['<STR_LIT>']['<STR_LIT>'], '<STR_LIT>')<EOL>spearman_matrix = plot.correlation_matrix(stats_object['<STR_LIT>']['<STR_LIT>'], '<STR_LIT>')<EOL>correlations_html = templates.template('<STR_LIT>').render(<EOL>values={'<STR_LIT>': pearson_matrix, '<STR_LIT>': spearman_matrix})<EOL>render_htmls['<STR_LIT>'] = correlations_html<EOL><DEDENT>sample_html = templates.template('<STR_LIT>').render(sample_table_html=sample.to_html(classes="<STR_LIT>"))<EOL>render_htmls['<STR_LIT>'] = sample_html<EOL>return templates.template('<STR_LIT>').render(render_htmls)<EOL> | Generate a HTML report from summary statistics and a given sample.
Parameters
----------
sample : DataFrame
the sample you want to print
stats_object : dict
Summary statistics. Should be generated with an appropriate describe() function
Returns
-------
str
containing profile report in HTML format
Notes
-----
* This function as to be refactored since it's huge and it contains inner functions | f15891:m0 |
def describe_numeric_1d(series, **kwargs): | <EOL>_percentile_format = "<STR_LIT>"<EOL>stats = dict()<EOL>stats['<STR_LIT:type>'] = base.TYPE_NUM<EOL>stats['<STR_LIT>'] = series.mean()<EOL>stats['<STR_LIT>'] = series.std()<EOL>stats['<STR_LIT>'] = series.var()<EOL>stats['<STR_LIT>'] = series.min()<EOL>stats['<STR_LIT>'] = series.max()<EOL>stats['<STR_LIT>'] = stats['<STR_LIT>'] - stats['<STR_LIT>']<EOL>_series_no_na = series.dropna()<EOL>for percentile in np.array([<NUM_LIT>, <NUM_LIT>, <NUM_LIT:0.5>, <NUM_LIT>, <NUM_LIT>]):<EOL><INDENT>stats[_percentile_format.format(percentile)] = _series_no_na.quantile(percentile)<EOL><DEDENT>stats['<STR_LIT>'] = stats['<STR_LIT>'] - stats['<STR_LIT>']<EOL>stats['<STR_LIT>'] = series.kurt()<EOL>stats['<STR_LIT>'] = series.skew()<EOL>stats['<STR_LIT>'] = series.sum()<EOL>stats['<STR_LIT>'] = series.mad()<EOL>stats['<STR_LIT>'] = stats['<STR_LIT>'] / stats['<STR_LIT>'] if stats['<STR_LIT>'] else np.NaN<EOL>stats['<STR_LIT>'] = (len(series) - np.count_nonzero(series))<EOL>stats['<STR_LIT>'] = stats['<STR_LIT>'] * <NUM_LIT:1.0> / len(series)<EOL>stats['<STR_LIT>'] = histogram(series, **kwargs)<EOL>stats['<STR_LIT>'] = mini_histogram(series, **kwargs)<EOL>return pd.Series(stats, name=series.name)<EOL> | Compute summary statistics of a numerical (`TYPE_NUM`) variable (a Series).
Also create histograms (mini an full) of its distribution.
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats keys. | f15892:m0 |
def describe_date_1d(series): | stats = dict()<EOL>stats['<STR_LIT:type>'] = base.TYPE_DATE<EOL>stats['<STR_LIT>'] = series.min()<EOL>stats['<STR_LIT>'] = series.max()<EOL>stats['<STR_LIT>'] = stats['<STR_LIT>'] - stats['<STR_LIT>']<EOL>stats['<STR_LIT>'] = histogram(series)<EOL>stats['<STR_LIT>'] = mini_histogram(series)<EOL>return pd.Series(stats, name=series.name)<EOL> | Compute summary statistics of a date (`TYPE_DATE`) variable (a Series).
Also create histograms (mini an full) of its distribution.
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats keys. | f15892:m1 |
def describe_categorical_1d(series): | <EOL>value_counts, distinct_count = base.get_groupby_statistic(series)<EOL>top, freq = value_counts.index[<NUM_LIT:0>], value_counts.iloc[<NUM_LIT:0>]<EOL>names = []<EOL>result = []<EOL>if base.get_vartype(series) == base.TYPE_CAT:<EOL><INDENT>names += ['<STR_LIT>', '<STR_LIT>', '<STR_LIT:type>']<EOL>result += [top, freq, base.TYPE_CAT]<EOL><DEDENT>return pd.Series(result, index=names, name=series.name)<EOL> | Compute summary statistics of a categorical (`TYPE_CAT`) variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats keys. | f15892:m2 |
def describe_boolean_1d(series): | value_counts, distinct_count = base.get_groupby_statistic(series)<EOL>top, freq = value_counts.index[<NUM_LIT:0>], value_counts.iloc[<NUM_LIT:0>]<EOL>mean = series.mean()<EOL>names = []<EOL>result = []<EOL>names += ['<STR_LIT>', '<STR_LIT>', '<STR_LIT:type>', '<STR_LIT>']<EOL>result += [top, freq, base.TYPE_BOOL, mean]<EOL>return pd.Series(result, index=names, name=series.name)<EOL> | Compute summary statistics of a boolean (`TYPE_BOOL`) variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats keys. | f15892:m3 |
def describe_constant_1d(series): | return pd.Series([base.S_TYPE_CONST], index=['<STR_LIT:type>'], name=series.name)<EOL> | Compute summary statistics of a constant (`S_TYPE_CONST`) variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats keys. | f15892:m4 |
def describe_unique_1d(series): | return pd.Series([base.S_TYPE_UNIQUE], index=['<STR_LIT:type>'], name=series.name)<EOL> | Compute summary statistics of a unique (`S_TYPE_UNIQUE`) variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats keys. | f15892:m5 |
def describe_supported(series, **kwargs): | leng = len(series) <EOL>count = series.count() <EOL>n_infinite = count - series.count() <EOL>value_counts, distinct_count = base.get_groupby_statistic(series)<EOL>if count > distinct_count > <NUM_LIT:1>:<EOL><INDENT>mode = series.mode().iloc[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>mode = series[<NUM_LIT:0>]<EOL><DEDENT>results_data = {'<STR_LIT:count>': count,<EOL>'<STR_LIT>': distinct_count,<EOL>'<STR_LIT>': <NUM_LIT:1> - count * <NUM_LIT:1.0> / leng,<EOL>'<STR_LIT>': leng - count,<EOL>'<STR_LIT>': n_infinite * <NUM_LIT:1.0> / leng,<EOL>'<STR_LIT>': n_infinite,<EOL>'<STR_LIT>': distinct_count == leng,<EOL>'<STR_LIT>': mode,<EOL>'<STR_LIT>': distinct_count * <NUM_LIT:1.0> / leng}<EOL>try:<EOL><INDENT>results_data['<STR_LIT>'] = series.memory_usage()<EOL><DEDENT>except:<EOL><INDENT>results_data['<STR_LIT>'] = <NUM_LIT:0><EOL><DEDENT>return pd.Series(results_data, name=series.name)<EOL> | Compute summary statistics of a supported variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats keys. | f15892:m6 |
def describe_unsupported(series, **kwargs): | leng = len(series) <EOL>count = series.count() <EOL>n_infinite = count - series.count() <EOL>results_data = {'<STR_LIT:count>': count,<EOL>'<STR_LIT>': <NUM_LIT:1> - count * <NUM_LIT:1.0> / leng,<EOL>'<STR_LIT>': leng - count,<EOL>'<STR_LIT>': n_infinite * <NUM_LIT:1.0> / leng,<EOL>'<STR_LIT>': n_infinite,<EOL>'<STR_LIT:type>': base.S_TYPE_UNSUPPORTED}<EOL>try:<EOL><INDENT>results_data['<STR_LIT>'] = series.memory_usage()<EOL><DEDENT>except:<EOL><INDENT>results_data['<STR_LIT>'] = <NUM_LIT:0><EOL><DEDENT>return pd.Series(results_data, name=series.name)<EOL> | Compute summary statistics of a unsupported (`S_TYPE_UNSUPPORTED`) variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats keys. | f15892:m7 |
def describe_1d(data, **kwargs): | <EOL>data.replace(to_replace=[np.inf, np.NINF, np.PINF], value=np.nan, inplace=True)<EOL>result = pd.Series({}, name=data.name)<EOL>vartype = base.get_vartype(data)<EOL>if vartype == base.S_TYPE_UNSUPPORTED:<EOL><INDENT>result = result.append(describe_unsupported(data))<EOL><DEDENT>else:<EOL><INDENT>result = result.append(describe_supported(data))<EOL>if vartype == base.S_TYPE_CONST:<EOL><INDENT>result = result.append(describe_constant_1d(data))<EOL><DEDENT>elif vartype == base.TYPE_BOOL:<EOL><INDENT>result = result.append(describe_boolean_1d(data))<EOL><DEDENT>elif vartype == base.TYPE_NUM:<EOL><INDENT>result = result.append(describe_numeric_1d(data, **kwargs))<EOL><DEDENT>elif vartype == base.TYPE_DATE:<EOL><INDENT>result = result.append(describe_date_1d(data))<EOL><DEDENT>elif vartype == base.S_TYPE_UNIQUE:<EOL><INDENT>result = result.append(describe_unique_1d(data))<EOL><DEDENT>else:<EOL><INDENT>result = result.append(describe_categorical_1d(data))<EOL><DEDENT><DEDENT>return result<EOL> | Compute summary statistics of a variable (a Series).
The description is different according to the type of the variable.
However a set of common stats is also computed.
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats keys. | f15892:m8 |
def describe(df, bins=<NUM_LIT:10>, check_correlation=True, correlation_threshold=<NUM_LIT>, correlation_overrides=None, check_recoded=False, pool_size=multiprocessing.cpu_count(), **kwargs): | if not isinstance(df, pd.DataFrame):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if df.empty:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>matplotlib.style.use("<STR_LIT:default>")<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>from pandas.plotting import register_matplotlib_converters<EOL>register_matplotlib_converters()<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>matplotlib.style.use(resource_filename(__name__, "<STR_LIT>"))<EOL>base.clear_cache()<EOL>if not pd.Index(np.arange(<NUM_LIT:0>, len(df))).equals(df.index):<EOL><INDENT>df = df.reset_index()<EOL><DEDENT>kwargs.update({'<STR_LIT>': bins})<EOL>if pool_size == <NUM_LIT:1>:<EOL><INDENT>local_multiprocess_func = partial(multiprocess_func, **kwargs)<EOL>ldesc = {col: s for col, s in map(local_multiprocess_func, df.iteritems())}<EOL><DEDENT>else:<EOL><INDENT>pool = multiprocessing.Pool(pool_size)<EOL>local_multiprocess_func = partial(multiprocess_func, **kwargs)<EOL>ldesc = {col: s for col, s in pool.map(local_multiprocess_func, df.iteritems())}<EOL>pool.close()<EOL><DEDENT>dfcorrPear = df.corr(method="<STR_LIT>")<EOL>dfcorrSpear = df.corr(method="<STR_LIT>")<EOL>if check_correlation is True:<EOL><INDENT>'''<STR_LIT>'''<EOL>corr = dfcorrPear.copy()<EOL>for x, corr_x in corr.iterrows():<EOL><INDENT>if correlation_overrides and x in correlation_overrides:<EOL><INDENT>continue<EOL><DEDENT>for y, corr in corr_x.iteritems():<EOL><INDENT>if x == y: break<EOL>if corr > correlation_threshold:<EOL><INDENT>ldesc[x] = pd.Series(['<STR_LIT>', y, corr], index=['<STR_LIT:type>', '<STR_LIT>', '<STR_LIT>'])<EOL><DEDENT><DEDENT><DEDENT>if check_recoded:<EOL><INDENT>categorical_variables = [(name, data) for (name, data) in df.iteritems() if base.get_vartype(data)=='<STR_LIT>']<EOL>for (name1, data1), (name2, data2) in itertools.combinations(categorical_variables, <NUM_LIT:2>):<EOL><INDENT>if correlation_overrides and name1 in correlation_overrides:<EOL><INDENT>continue<EOL><DEDENT>confusion_matrix=pd.crosstab(data1,data2)<EOL>if confusion_matrix.values.diagonal().sum() == len(df):<EOL><INDENT>ldesc[name1] = pd.Series(['<STR_LIT>', name2], index=['<STR_LIT:type>', '<STR_LIT>'])<EOL><DEDENT><DEDENT><DEDENT><DEDENT>names = []<EOL>ldesc_indexes = sorted([x.index for x in ldesc.values()], key=len)<EOL>for idxnames in ldesc_indexes:<EOL><INDENT>for name in idxnames:<EOL><INDENT>if name not in names:<EOL><INDENT>names.append(name)<EOL><DEDENT><DEDENT><DEDENT>variable_stats = pd.concat(ldesc, join_axes=pd.Index([names]), axis=<NUM_LIT:1>)<EOL>variable_stats.columns.names = df.columns.names<EOL>table_stats = {}<EOL>table_stats['<STR_LIT:n>'] = len(df)<EOL>table_stats['<STR_LIT>'] = len(df.columns)<EOL>table_stats['<STR_LIT>'] = variable_stats.loc['<STR_LIT>'].sum() / (table_stats['<STR_LIT:n>'] * table_stats['<STR_LIT>'])<EOL>unsupported_columns = variable_stats.transpose()[variable_stats.transpose().type != base.S_TYPE_UNSUPPORTED].index.tolist()<EOL>table_stats['<STR_LIT>'] = sum(df.duplicated(subset=unsupported_columns)) if len(unsupported_columns) > <NUM_LIT:0> else <NUM_LIT:0><EOL>memsize = df.memory_usage(index=True).sum()<EOL>table_stats['<STR_LIT>'] = formatters.fmt_bytesize(memsize)<EOL>table_stats['<STR_LIT>'] = formatters.fmt_bytesize(memsize / table_stats['<STR_LIT:n>'])<EOL>table_stats.update({k: <NUM_LIT:0> for k in ("<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>")})<EOL>table_stats.update(dict(variable_stats.loc['<STR_LIT:type>'].value_counts()))<EOL>table_stats['<STR_LIT>'] = table_stats['<STR_LIT>'] + table_stats['<STR_LIT>'] + table_stats['<STR_LIT>']<EOL>return {<EOL>'<STR_LIT>': table_stats,<EOL>'<STR_LIT>': variable_stats.T,<EOL>'<STR_LIT>': {k: (base.get_groupby_statistic(df[k])[<NUM_LIT:0>] if variable_stats[k].type != base.S_TYPE_UNSUPPORTED else None) for k in df.columns},<EOL>'<STR_LIT>': {'<STR_LIT>': dfcorrPear, '<STR_LIT>': dfcorrSpear}<EOL>}<EOL> | Generates a dict containing summary statistics for a given dataset stored as a pandas `DataFrame`.
Used has is it will output its content as an HTML report in a Jupyter notebook.
Parameters
----------
df : DataFrame
Data to be analyzed
bins : int
Number of bins in histogram.
The default is 10.
check_correlation : boolean
Whether or not to check correlation.
It's `True` by default.
correlation_threshold: float
Threshold to determine if the variable pair is correlated.
The default is 0.9.
correlation_overrides : list
Variable names not to be rejected because they are correlated.
There is no variable in the list (`None`) by default.
check_recoded : boolean
Whether or not to check recoded correlation (memory heavy feature).
Since it's an expensive computation it can be activated for small datasets.
`check_correlation` must be true to disable this check.
It's `False` by default.
pool_size : int
Number of workers in thread pool
The default is equal to the number of CPU.
Returns
-------
dict
Containing the following keys:
* table: general statistics on the dataset
* variables: summary statistics for each variable
* freq: frequency table
Notes:
------
* The section dedicated to check the correlation should be externalized | f15892:m10 |
@classmethod<EOL><INDENT>def validate_port_range(cls, port_range):<DEDENT> | ports = port_range.split("<STR_LIT:->")<EOL>if all(ports) and int(ports[-<NUM_LIT:1>]) <= <NUM_LIT> and not len(ports) != <NUM_LIT:2>:<EOL><INDENT>return True<EOL><DEDENT>raise ScannerException("<STR_LIT>".format(port_range))<EOL> | Validate port range for Nmap scan | f15902:c0:m3 |
@classmethod<EOL><INDENT>def validate_proxy_args(cls, *args):<DEDENT> | supplied_proxies = Counter((not arg for arg in (*args,))).get(False)<EOL>if not supplied_proxies:<EOL><INDENT>return<EOL><DEDENT>elif supplied_proxies > <NUM_LIT:1>:<EOL><INDENT>raise RaccoonException("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT> | No more than 1 of the following can be specified: tor_routing, proxy, proxy_list | f15902:c0:m4 |
@classmethod<EOL><INDENT>def find_mac_gtimeout_executable(cls):<DEDENT> | return distutils.spawn.find_executable("<STR_LIT>")<EOL> | To add macOS support, the coreutils package needs to be installed using homebrew | f15902:c0:m8 |
@classmethod<EOL><INDENT>def create_output_directory(cls, outdir):<DEDENT> | cls.PATH = outdir<EOL>try:<EOL><INDENT>os.mkdir(outdir)<EOL><DEDENT>except FileExistsError:<EOL><INDENT>pass<EOL><DEDENT> | Tries to create base output directory | f15902:c0:m10 |
def _set_instance_proxies(self): | proxies = {}<EOL>if self.tor_routing:<EOL><INDENT>proxies = {<EOL>"<STR_LIT:http>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>"<EOL>}<EOL><DEDENT>elif self.proxy_list:<EOL><INDENT>try:<EOL><INDENT>with open(self.proxy_list, "<STR_LIT:r>") as file:<EOL><INDENT>file = file.readlines()<EOL>proxies = [x.replace("<STR_LIT:\n>", "<STR_LIT>") for x in file]<EOL><DEDENT><DEDENT>except FileNotFoundError:<EOL><INDENT>raise RequestHandlerException("<STR_LIT>".format(self.proxy_list))<EOL><DEDENT><DEDENT>elif self.single_proxy:<EOL><INDENT>proxies = {<EOL>"<STR_LIT:http>": self.single_proxy,<EOL>"<STR_LIT>": self.single_proxy<EOL>}<EOL><DEDENT>return proxies<EOL> | Set the proxies to any of the following:
Proxy List - a list of proxies to choose randomly from for each request. Read from file.
TOR - a dict of socks5 and the TOR service default 9050 that will be used
Else, No proxies - an empty dict will be used. | f15904:c0:m2 |
def send(self, method="<STR_LIT:GET>", *args, **kwargs): | proxies = self._get_request_proxies()<EOL>try:<EOL><INDENT>if method.upper() in self.allowed_methods:<EOL><INDENT>kwargs['<STR_LIT>'] = kwargs['<STR_LIT>'] if '<STR_LIT>' in kwargs else <NUM_LIT:5><EOL>return request(method, proxies=proxies, headers=self.headers, cookies=self.cookies, *args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>raise RequestHandlerException("<STR_LIT>".format(method))<EOL><DEDENT><DEDENT>except ProxyError:<EOL><INDENT>raise RequestHandlerException("<STR_LIT>")<EOL><DEDENT>except (ConnectTimeout, ReadTimeout):<EOL><INDENT>raise RequestHandlerException("<STR_LIT>")<EOL><DEDENT>except NewConnectionError:<EOL><INDENT>raise RequestHandlerException("<STR_LIT>")<EOL><DEDENT>except ConnectionError:<EOL><INDENT>raise RequestHandlerException("<STR_LIT>")<EOL><DEDENT>except TooManyRedirects:<EOL><INDENT>raise RequestHandlerException("<STR_LIT>")<EOL><DEDENT>except UnicodeDecodeError:<EOL><INDENT>pass<EOL><DEDENT> | Send a GET/POST/HEAD request using the object's proxies and headers
:param method: Method to send request in. GET/POST/HEAD | f15904:c0:m4 |
def get_new_session(self): | session = Session()<EOL>session.headers = self.headers<EOL>session.proxies = self._get_request_proxies()<EOL>return session<EOL> | Returns a new session using the object's proxies and headers | f15904:c0:m5 |
def _fetch(self, uri, sub_domain=False): | url = self._build_request_url(uri, sub_domain=sub_domain)<EOL>try:<EOL><INDENT>res = self.request_handler.send("<STR_LIT>", url=url, allow_redirects=self.follow_redirects)<EOL>if res.status_code not in self.ignored_error_codes:<EOL><INDENT>self._log_response(res.status_code, url, res.headers)<EOL><DEDENT><DEDENT>except (AttributeError, RequestHandlerException):<EOL><INDENT>pass<EOL><DEDENT> | Send a HEAD request to URL and print response code if it's not in ignored_error_codes
:param uri: URI to fuzz
:param sub_domain: If True, build destination URL with {URL}.{HOST} else {HOST}/{URL} | f15909:c0:m4 |
async def fuzz_all(self, sub_domain=False, log_file_path=None): | self.logger = self.get_log_file_path(log_file_path)<EOL>try:<EOL><INDENT>response_codes = self._generate_fake_requests(sub_domain)<EOL>self._rule_out_false_positives(response_codes, sub_domain)<EOL>if not sub_domain:<EOL><INDENT>self.logger.info("<STR_LIT>".format(COLORED_COMBOS.INFO))<EOL><DEDENT>self.logger.info("<STR_LIT>".format(COLORED_COMBOS.INFO, self.path_to_wordlist))<EOL>pool = ThreadPool(self.num_threads)<EOL>pool.map(partial(self._fetch, sub_domain=sub_domain), self.wordlist)<EOL>pool.close()<EOL>pool.join()<EOL>if not sub_domain:<EOL><INDENT>self.logger.info("<STR_LIT>".format(COLORED_COMBOS.INFO))<EOL><DEDENT><DEDENT>except FuzzerException as e:<EOL><INDENT>self.logger.info("<STR_LIT>".format(COLORED_COMBOS.BAD, e))<EOL><DEDENT>except ConnectionError as e:<EOL><INDENT>if "<STR_LIT>" in str(e):<EOL><INDENT>self.logger.info("<STR_LIT>"<EOL>"<STR_LIT>".format(COLORED_COMBOS.BAD, str(e)))<EOL><DEDENT><DEDENT> | Create a pool of threads and exhaust self.wordlist on self._fetch
Should be run in an event loop.
:param sub_domain: Indicate if this is subdomain enumeration or URL busting
:param log_file_path: Log subdomain enum results to this path. | f15909:c0:m8 |
def _are_certificates_identical(self): | sni_cert = self.sni_data.get("<STR_LIT>")<EOL>non_sni_cert = self.non_sni_data.get("<STR_LIT>")<EOL>if all(cert for cert in (sni_cert, non_sni_cert) if cert) and sni_cert == non_sni_cert:<EOL><INDENT>return True<EOL><DEDENT>return<EOL> | Validate that both certificates exist.
:returns: True if they are identical, False otherwise | f15910:c1:m2 |
async def _execute_ssl_data_extraction(self, sni=False): | <EOL>responses = await self._run_openssl_sclient_cmd(self._base_script, sni)<EOL>tls_dict = self._parse_openssl_sclient_output(responses)<EOL>for res in responses:<EOL><INDENT>if self._is_certificate_exists(res):<EOL><INDENT>tls_dict["<STR_LIT>"] = await self._get_sans_from_openssl_cmd(res)<EOL>tls_dict["<STR_LIT>"] = await self._extract_certificate_details(res)<EOL>break<EOL><DEDENT><DEDENT>return tls_dict<EOL> | Test for version support (SNI/non-SNI), get all SANs, get certificate details
:param sni: True will call cause _exec_openssl to call openssl with -servername flag | f15910:c1:m6 |
@classmethod<EOL><INDENT>def query_dns(cls, domains, records):<DEDENT> | results = {k: set() for k in records}<EOL>for record in records:<EOL><INDENT>for domain in domains:<EOL><INDENT>try:<EOL><INDENT>answers = cls.resolver.query(domain, record)<EOL>for answer in answers:<EOL><INDENT>results.get(record).add(answer)<EOL><DEDENT><DEDENT>except (resolver.NoAnswer, resolver.NXDOMAIN, resolver.NoNameservers):<EOL><INDENT>continue<EOL><DEDENT><DEDENT><DEDENT>return {k: v for k, v in results.items() if v}<EOL> | Query DNS records for host.
:param domains: Iterable of domains to get DNS Records for
:param records: Iterable of DNS records to get from domain. | f15911:c0:m0 |
def _detect_cms(self, tries=<NUM_LIT:0>): | <EOL>page = requests.get(url="<STR_LIT>".format(self.host.target))<EOL>soup = BeautifulSoup(page.text, "<STR_LIT>")<EOL>found = soup.select("<STR_LIT>")<EOL>if found:<EOL><INDENT>try:<EOL><INDENT>cms = [a for a in soup.select("<STR_LIT:a>") if "<STR_LIT>" in a.get("<STR_LIT>")][<NUM_LIT:0>]<EOL>self.logger.info("<STR_LIT>".format(<EOL>COLORED_COMBOS.GOOD, COLOR.GREEN, cms.get("<STR_LIT:title>"), COLOR.RESET))<EOL><DEDENT>except IndexError:<EOL><INDENT>if tries >= <NUM_LIT:4>:<EOL><INDENT>return<EOL><DEDENT>else:<EOL><INDENT>self._detect_cms(tries=tries + <NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if tries >= <NUM_LIT:4>:<EOL><INDENT>return<EOL><DEDENT>else:<EOL><INDENT>self._detect_cms(tries=tries + <NUM_LIT:1>)<EOL><DEDENT><DEDENT> | Detect CMS using whatcms.org.
Has a re-try mechanism because false negatives may occur
:param tries: Count of tries for CMS discovery | f15912:c0:m1 |
def _extract_from_sans(self): | self.logger.info("<STR_LIT>".format(COLORED_COMBOS.NOTIFY))<EOL>if self.host.naked:<EOL><INDENT>domain = self.host.naked<EOL>tld_less = domain.split("<STR_LIT:.>")[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>domain = self.host.target.split("<STR_LIT:.>")<EOL>tld_less = domain[<NUM_LIT:1>]<EOL>domain = "<STR_LIT:.>".join(domain[<NUM_LIT:1>:])<EOL><DEDENT>for san in self.sans:<EOL><INDENT>if (tld_less in san or domain in san) and self.target != san and not san.startswith("<STR_LIT:*>"):<EOL><INDENT>self.logger.info("<STR_LIT>".format(COLORED_COMBOS.GOOD, san))<EOL><DEDENT><DEDENT> | Looks for different TLDs as well as different sub-domains in SAN list | f15915:c0:m2 |
def parse(self): | if self.target.endswith("<STR_LIT:/>"):<EOL><INDENT>self.target = self.target[:-<NUM_LIT:1>]<EOL><DEDENT>if self._is_proto(self.target):<EOL><INDENT>try:<EOL><INDENT>self.protocol, self.target = self.target.split("<STR_LIT>")<EOL>self.logger.info("<STR_LIT>".format(COLORED_COMBOS.NOTIFY, self.protocol))<EOL>if self.protocol.lower() == "<STR_LIT>" and self.port == <NUM_LIT>:<EOL><INDENT>self.port = <NUM_LIT><EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>raise HostHandlerException("<STR_LIT>")<EOL><DEDENT><DEDENT>if "<STR_LIT::>" in self.target:<EOL><INDENT>self._extract_port(self.target)<EOL><DEDENT>if self.validate_ip(self.target):<EOL><INDENT>self.logger.info("<STR_LIT>".format(COLORED_COMBOS.NOTIFY, self.target))<EOL>self.is_ip = True<EOL><DEDENT>else:<EOL><INDENT>domains = []<EOL>if self.target.startswith("<STR_LIT>"):<EOL><INDENT>domains.extend((self.target, self.target.split("<STR_LIT>")[<NUM_LIT:1>]))<EOL>self.fqdn = self.target<EOL>self.naked = "<STR_LIT:.>".join(self.fqdn.split('<STR_LIT:.>')[<NUM_LIT:1>:])<EOL><DEDENT>else:<EOL><INDENT>domains.append(self.target)<EOL>domain_levels = self.target.split("<STR_LIT:.>")<EOL>if len(domain_levels) == <NUM_LIT:2> or (len(domain_levels) == <NUM_LIT:3> and domain_levels[<NUM_LIT:1>] == "<STR_LIT>"):<EOL><INDENT>self.logger.info("<STR_LIT>".format(COLORED_COMBOS.NOTIFY, self.target))<EOL>self.naked = self.target<EOL><DEDENT><DEDENT>try:<EOL><INDENT>self.dns_results = DNSHandler.query_dns(domains, self.dns_records)<EOL><DEDENT>except Timeout:<EOL><INDENT>raise HostHandlerException("<STR_LIT>")<EOL><DEDENT>if self.dns_results.get("<STR_LIT>"):<EOL><INDENT>self.logger.info("<STR_LIT>".format(<EOL>COLORED_COMBOS.NOTIFY, self.target))<EOL>self.fqdn = self.target<EOL>self.naked = "<STR_LIT:.>".join(self.fqdn.split('<STR_LIT:.>')[<NUM_LIT:1>:])<EOL><DEDENT><DEDENT>self.create_host_dir_and_set_file_logger()<EOL>self.write_up()<EOL> | Try to extract domain (full, naked, sub-domain), IP and port. | f15917:c0:m9 |
def _add_to_found_storage(self, storage_url): | storage_url = self._normalize_url(storage_url)<EOL>bucket = S3Bucket(storage_url)<EOL>if bucket.url not in self.storage_urls_found:<EOL><INDENT>try:<EOL><INDENT>res = self.request_handler.send("<STR_LIT:GET>", url=storage_url)<EOL>if self._is_amazon_s3_bucket(res):<EOL><INDENT>self.storage_urls_found.add(bucket.url)<EOL>self.s3_buckets.add(bucket)<EOL><DEDENT><DEDENT>except RequestHandlerException:<EOL><INDENT>pass<EOL><DEDENT><DEDENT> | Will first normalize the img src and then check if this bucket was discovered before
If it is in storage_urls_found, the function returns
Else, it send a GET for the original URL (normalized image src) and will look for "AmazonS3" in
the "Server" response header.
If found, will add to URL with the resource stripped
:param storage_url: img src scraped from page | f15918:c5:m2 |
def make_padded_frequency_series(vec, filter_N=None): | if filter_N is None:<EOL><INDENT>power = ceil(log(len(vec), <NUM_LIT:2>))+<NUM_LIT:1><EOL>N = <NUM_LIT:2> ** power<EOL><DEDENT>else:<EOL><INDENT>N = filter_N<EOL><DEDENT>n = N/<NUM_LIT:2>+<NUM_LIT:1><EOL>if isinstance(vec, FrequencySeries):<EOL><INDENT>vectilde = FrequencySeries(zeros(n, dtype=complex_same_precision_as(vec)),<EOL>delta_f=<NUM_LIT:1.0>, copy=False)<EOL>if len(vectilde) < len(vec):<EOL><INDENT>cplen = len(vectilde)<EOL><DEDENT>else:<EOL><INDENT>cplen = len(vec)<EOL><DEDENT>vectilde[<NUM_LIT:0>:cplen] = vec[<NUM_LIT:0>:cplen]<EOL>delta_f = vec.delta_f<EOL><DEDENT>if isinstance(vec, TimeSeries):<EOL><INDENT>vec_pad = TimeSeries(zeros(N), delta_t=vec.delta_t,<EOL>dtype=real_same_precision_as(vec))<EOL>vec_pad[<NUM_LIT:0>:len(vec)] = vec<EOL>delta_f = <NUM_LIT:1.0>/(vec.delta_t*N)<EOL>vectilde = FrequencySeries(zeros(n), delta_f=<NUM_LIT:1.0>,<EOL>dtype=complex_same_precision_as(vec))<EOL>fft(vec_pad, vectilde)<EOL><DEDENT>vectilde = FrequencySeries(<EOL>vectilde * DYN_RANGE_FAC, delta_f=delta_f, dtype=complex64)<EOL>return vectilde<EOL> | Pad a TimeSeries with a length of zeros greater than its length, such
that the total length is the closest power of 2. This prevents the effects
of wraparound. | f15928:m3 |
def apply_cyclic(value, bounds): | return (value - bounds._min) %(bounds._max - bounds._min) + bounds._min<EOL> | Given a value, applies cyclic boundary conditions between the minimum
and maximum bounds.
Parameters
----------
value : float
The value to apply the cyclic conditions to.
bounds : Bounds instance
Boundaries to use for applying cyclic conditions.
Returns
-------
float
The value after the cyclic bounds are applied. | f15933:m0 |
def reflect_well(value, bounds): | while value not in bounds:<EOL><INDENT>value = bounds._max.reflect_left(value)<EOL>value = bounds._min.reflect_right(value)<EOL><DEDENT>return value<EOL> | Given some boundaries, reflects the value until it falls within both
boundaries. This is done iteratively, reflecting left off of the
`boundaries.max`, then right off of the `boundaries.min`, etc.
Parameters
----------
value : float
The value to apply the reflected boundaries to.
bounds : Bounds instance
Boundaries to reflect between. Both `bounds.min` and `bounds.max` must
be instances of `ReflectedBound`, otherwise an AttributeError is
raised.
Returns
-------
float
The value after being reflected between the two bounds. | f15933:m1 |
def _pass(value): | return value<EOL> | Just return the given value. | f15933:m2 |
def larger(self, other): | raise NotImplementedError("<STR_LIT>")<EOL> | A function to determine whether or not `other` is larger
than the bound. This raises a NotImplementedError; classes that
inherit from this must define it. | f15933:c0:m0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.