Search is not available for this dataset
text stringlengths 75 104k |
|---|
def parse_report_file(input_, nameservers=None, dns_timeout=2.0,
strip_attachment_payloads=False, parallel=False):
"""Parses a DMARC aggregate or forensic file at the given path, a
file-like object. or bytes
Args:
input_: A path to a file, a file like object, or bytes
... |
def get_imap_capabilities(server):
"""
Returns a list of an IMAP server's capabilities
Args:
server (imapclient.IMAPClient): An instance of imapclient.IMAPClient
Returns (list): A list of capabilities
"""
capabilities = list(map(str, list(server.capabilities())))
for i in range(le... |
def get_dmarc_reports_from_inbox(host=None,
user=None,
password=None,
connection=None,
port=None,
ssl=True,
ssl_context=No... |
def save_output(results, output_directory="output"):
"""
Save report data in the given directory
Args:
results (OrderedDict): Parsing results
output_directory: The patch to the directory to save in
"""
aggregate_reports = results["aggregate_reports"]
forensic_reports = results[... |
def get_report_zip(results):
"""
Creates a zip file of parsed report output
Args:
results (OrderedDict): The parsed results
Returns:
bytes: zip file bytes
"""
def add_subdir(root_path, subdir):
subdir_path = os.path.join(root_path, subdir)
for subdir_root, subdi... |
def email_results(results, host, mail_from, mail_to, port=0,
ssl=False, user=None, password=None, subject=None,
attachment_filename=None, message=None, ssl_context=None):
"""
Emails parsing results as a zip file
Args:
results (OrderedDict): Parsing results
... |
def watch_inbox(host, username, password, callback, port=None, ssl=True,
ssl_context=None, reports_folder="INBOX",
archive_folder="Archive", delete=False, test=False, wait=30,
nameservers=None, dns_timeout=6.0,
strip_attachment_payloads=False):
"""
... |
def save_aggregate_reports_to_splunk(self, aggregate_reports):
"""
Saves aggregate DMARC reports to Splunk
Args:
aggregate_reports: A list of aggregate report dictionaries
to save in Splunk
"""
logger.debug("Saving aggregate reports to Splunk")
i... |
def save_forensic_reports_to_splunk(self, forensic_reports):
"""
Saves forensic DMARC reports to Splunk
Args:
forensic_reports (list): A list of forensic report dictionaries
to save in Splunk
"""
logger.debug("Saving forensic reports to Splunk")
... |
def decode_base64(data):
"""
Decodes a base64 string, with padding being optional
Args:
data: A base64 encoded string
Returns:
bytes: The decoded bytes
"""
data = bytes(data, encoding="ascii")
missing_padding = len(data) % 4
if missing_padding != 0:
data += b'=... |
def get_base_domain(domain, use_fresh_psl=False):
"""
Gets the base domain name for the given domain
.. note::
Results are based on a list of public domain suffixes at
https://publicsuffix.org/list/public_suffix_list.dat.
Args:
domain (str): A domain or subdomain
use_fr... |
def query_dns(domain, record_type, cache=None, nameservers=None, timeout=2.0):
"""
Queries DNS
Args:
domain (str): The domain or subdomain to query about
record_type (str): The record type to query for
cache (ExpiringDict): Cache storage
nameservers (list): A list of one or ... |
def get_reverse_dns(ip_address, cache=None, nameservers=None, timeout=2.0):
"""
Resolves an IP address to a hostname using a reverse DNS query
Args:
ip_address (str): The IP address to resolve
cache (ExpiringDict): Cache storage
nameservers (list): A list of one or more nameservers ... |
def human_timestamp_to_datetime(human_timestamp, to_utc=False):
"""
Converts a human-readable timestamp into a Python ``DateTime`` object
Args:
human_timestamp (str): A timestamp string
to_utc (bool): Convert the timestamp to UTC
Returns:
DateTime: The converted timestamp
"... |
def get_ip_address_country(ip_address, parallel=False):
"""
Uses the MaxMind Geolite2 Country database to return the ISO code for the
country associated with the given IPv4 or IPv6 address
Args:
ip_address (str): The IP address to query for
parallel (bool): Parallel processing
Retu... |
def get_ip_address_info(ip_address, cache=None, nameservers=None,
timeout=2.0, parallel=False):
"""
Returns reverse DNS and country information for the given IP address
Args:
ip_address (str): The IP address to check
cache (ExpiringDict): Cache storage
namese... |
def get_filename_safe_string(string):
"""
Converts a string to a string that is safe for a filename
Args:
string (str): A string to make safe for a filename
Returns:
str: A string safe for a filename
"""
invalid_filename_chars = ['\\', '/', ':', '"', '*', '?', '|', '\n',
... |
def convert_outlook_msg(msg_bytes):
"""
Uses the ``msgconvert`` Perl utility to convert an Outlook MS file to
standard RFC 822 format
Args:
msg_bytes (bytes): the content of the .msg file
Returns:
A RFC 822 string
"""
if not is_outlook_msg(msg_bytes):
raise ValueErr... |
def parse_email(data, strip_attachment_payloads=False):
"""
A simplified email parser
Args:
data: The RFC 822 message string, or MSG binary
strip_attachment_payloads (bool): Remove attachment payloads
Returns (dict): Parsed email data
"""
if type(data) == bytes:
if is_... |
def _str_to_list(s):
"""Converts a comma separated string to a list"""
_list = s.split(",")
return list(map(lambda i: i.lstrip(), _list)) |
def cli_parse(file_path, sa, nameservers, dns_timeout, parallel=False):
"""Separated this function for multiprocessing"""
try:
file_results = parse_report_file(file_path,
nameservers=nameservers,
dns_timeout=dns_timeout,
... |
def _main():
"""Called when the module is executed"""
def process_reports(reports_):
output_str = "{0}\n".format(json.dumps(reports_,
ensure_ascii=False,
indent=2))
if not opts.silent:
print... |
def drain(self, sid=None):
"""
Drain will put a connection into a drain state. All subscriptions will
immediately be put into a drain state. Upon completion, the publishers
will be drained and can not publish any additional messages. Upon draining
of the publishers, the connectio... |
def publish(self, subject, payload):
"""
Sends a PUB command to the server on the specified subject.
->> PUB hello 5
->> MSG_PAYLOAD: world
<<- MSG hello 2 5
"""
if self.is_closed:
raise ErrConnectionClosed
if self.is_draining_pubs:
... |
def publish_request(self, subject, reply, payload):
"""
Publishes a message tagging it with a reply subscription
which can be used by those receiving the message to respond.
->> PUB hello _INBOX.2007314fe0fcb2cdc2a2914c1 5
->> MSG_PAYLOAD: world
<<- MSG hello ... |
def _publish(self, subject, reply, payload, payload_size):
"""
Sends PUB command to the NATS server.
"""
if subject == "":
# Avoid sending messages with empty replies.
raise ErrBadSubject
payload_size_bytes = ("%d" % payload_size).encode()
pub_cmd... |
def subscribe(self, subject,
queue="",
cb=None,
future=None,
max_msgs=0,
is_async=False,
pending_msgs_limit=DEFAULT_SUB_PENDING_MSGS_LIMIT,
pending_bytes_limit=DEFAULT_SUB_PENDING_BYTES_LIMIT,
... |
def subscribe_async(self, subject, **kwargs):
"""
Sets the subcription to use a task per message to be processed.
..deprecated:: 7.0
Will be removed 9.0.
"""
kwargs["is_async"] = True
sid = yield from self.subscribe(subject, **kwargs)
return sid |
def unsubscribe(self, ssid, max_msgs=0):
"""
Takes a subscription sequence id and removes the subscription
from the client, optionally after receiving more than max_msgs.
"""
if self.is_closed:
raise ErrConnectionClosed
if self.is_draining:
raise E... |
def request(self, subject, payload, timeout=0.5, expected=1, cb=None):
"""
Implements the request/response pattern via pub/sub
using a single wildcard subscription that handles
the responses.
"""
if self.is_draining_pubs:
raise ErrConnectionDraining
... |
def timed_request(self, subject, payload, timeout=0.5):
"""
Implements the request/response pattern via pub/sub
using an ephemeral subscription which will be published
with a limited interest of 1 reply returning the response
or raising a Timeout error.
->> SUB _INBOX.... |
def flush(self, timeout=60):
"""
Sends a ping to the server expecting a pong back ensuring
what we have written so far has made it to the server and
also enabling measuring of roundtrip time.
In case a pong is not returned within the allowed timeout,
then it will raise Er... |
def _select_next_server(self):
"""
Looks up in the server pool for an available server
and attempts to connect.
"""
while True:
if len(self._server_pool) == 0:
self._current_server = None
raise ErrNoServers
now = time.mono... |
def _process_err(self, err_msg):
"""
Processes the raw error message sent by the server
and close connection with current server.
"""
if STALE_CONNECTION in err_msg:
yield from self._process_op_err(ErrStaleConnection)
return
if AUTHORIZATION_VIOLA... |
def _process_op_err(self, e):
"""
Process errors which occured while reading or parsing
the protocol. If allow_reconnect is enabled it will
try to switch the server to which it is currently connected
otherwise it will disconnect.
"""
if self.is_connecting or self.... |
def _connect_command(self):
'''
Generates a JSON string with the params to be used
when sending CONNECT to the server.
->> CONNECT {"lang": "python3"}
'''
options = {
"verbose": self.options["verbose"],
"pedantic": self.options["pedantic"],
... |
def _process_pong(self):
"""
Process PONG sent by server.
"""
if len(self._pongs) > 0:
future = self._pongs.pop(0)
future.set_result(True)
self._pongs_received += 1
self._pings_outstanding -= 1 |
def _process_msg(self, sid, subject, reply, data):
"""
Process MSG sent by server.
"""
payload_size = len(data)
self.stats['in_msgs'] += 1
self.stats['in_bytes'] += payload_size
sub = self._subs.get(sid)
if sub is None:
# Skip in case no subsc... |
def _process_info(self, info):
"""
Process INFO lines sent by the server to reconfigure client
with latest updates from cluster to enable server discovery.
"""
if 'connect_urls' in info:
if info['connect_urls']:
connect_urls = []
for co... |
def _process_connect_init(self):
"""
Process INFO received from the server and CONNECT to the server
with authentication. It is also responsible of setting up the
reading and ping interval tasks from the client.
"""
self._status = Client.CONNECTING
connection_co... |
def _flusher(self):
"""
Coroutine which continuously tries to consume pending commands
and then flushes them to the socket.
"""
while True:
if not self.is_connected or self.is_connecting:
break
try:
yield from self._flush_q... |
def _read_loop(self):
"""
Coroutine which gathers bytes sent by the server
and feeds them to the protocol parser.
In case of error while reading, it will stop running
and its task has to be rescheduled.
"""
while True:
try:
should_bail ... |
def coactivation(dataset, seed, threshold=0.0, output_dir='.', prefix='', r=6):
""" Compute and save coactivation map given input image as seed.
This is essentially just a wrapper for a meta-analysis defined
by the contrast between those studies that activate within the seed
and those that don't.
... |
def decode(self, images, save=None, round=4, names=None, **kwargs):
""" Decodes a set of images.
Args:
images: The images to decode. Can be:
- A single String specifying the filename of the image to decode
- A list of filenames
- A single NumPy array contai... |
def load_features(self, features, image_type=None, from_array=False,
threshold=0.001):
""" Load features from current Dataset instance or a list of files.
Args:
features: List containing paths to, or names of, features to
extract. Each element in the lis... |
def _load_features_from_array(self, features):
""" Load feature data from a 2D ndarray on disk. """
self.feature_images = np.load(features)
self.feature_names = range(self.feature_images.shape[1]) |
def _load_features_from_dataset(self, features=None, image_type=None,
threshold=0.001):
""" Load feature image data from the current Dataset instance. See
load_features() for documentation.
"""
self.feature_names = self.dataset.feature_table.feature_na... |
def _load_features_from_images(self, images, names=None):
""" Load feature image data from image files.
Args:
images: A list of image filenames.
names: An optional list of strings to use as the feature names. Must
be in the same order as the images.
"""
i... |
def _pearson_correlation(self, imgs_to_decode):
""" Decode images using Pearson's r.
Computes the correlation between each input image and each feature
image across voxels.
Args:
imgs_to_decode: An ndarray of images to decode, with voxels in rows
and images ... |
def _dot_product(self, imgs_to_decode):
""" Decoding using the dot product.
"""
return np.dot(imgs_to_decode.T, self.feature_images).T |
def _roi_association(self, imgs_to_decode, value='z', binarize=None):
""" Computes the strength of association between activation in a mask
and presence/absence of a semantic feature. This is essentially a
generalization of the voxel-wise reverse inference z-score to the
multivoxel case.... |
def feature_selection(feat_select, X, y):
"""" Implements various kinds of feature selection """
# K-best
if re.match('.*-best', feat_select) is not None:
n = int(feat_select.split('-')[0])
selector = SelectKBest(k=n)
import warnings
with warnings.catch_warnings():
... |
def get_studies_by_regions(dataset, masks, threshold=0.08, remove_overlap=True,
studies=None, features=None,
regularization="scale"):
""" Set up data for a classification task given a set of masks
Given a set of masks, this function retrieves studies as... |
def get_feature_order(dataset, features):
""" Returns a list with the order that features requested appear in
dataset """
all_features = dataset.get_feature_names()
i = [all_features.index(f) for f in features]
return i |
def classify_regions(dataset, masks, method='ERF', threshold=0.08,
remove_overlap=True, regularization='scale',
output='summary', studies=None, features=None,
class_weight='auto', classifier=None,
cross_val='4-Fold', param_grid=None, sc... |
def classify(X, y, clf_method='ERF', classifier=None, output='summary_clf',
cross_val=None, class_weight=None, regularization=None,
param_grid=None, scoring='accuracy', refit_all=True,
feat_select=None):
""" Wrapper for scikit-learn classification functions
Imlements vario... |
def fit(self, X, y, cv=None, class_weight='auto'):
""" Fits X to outcomes y, using clf """
# Incorporate error checking such as :
# if isinstance(self.classifier, ScikitClassifier):
# do one thingNone
# otherwiseNone.
self.X = X
self.y = y
self.set_... |
def set_class_weight(self, class_weight='auto', y=None):
""" Sets the class_weight of the classifier to match y """
if class_weight is None:
cw = None
try:
self.clf.set_params(class_weight=cw)
except ValueError:
pass
elif cla... |
def cross_val_fit(self, X, y, cross_val='4-Fold', scoring='accuracy',
feat_select=None, class_weight='auto'):
""" Fits X to outcomes y, using clf and cv_method """
from sklearn import cross_validation
self.X = X
self.y = y
self.set_class_weight(class_weig... |
def feat_select_cvs(self, scoring=None, feat_select=None):
""" Returns cross validated scores (just like cross_val_score),
but includes feature selection as part of the cross validation loop """
scores = []
self.predictions = []
for train, test in self.cver:
X_train... |
def fit_dataset(self, dataset, y, features=None,
feature_type='features'):
""" Given a dataset, fits either features or voxels to y """
# Get data from dataset
if feature_type == 'features':
X = np.rot90(dataset.feature_table.data.toarray())
elif feature... |
def p_list_andnot(self, p):
'list : list ANDNOT list'
p[0] = p[1].loc[set(p[1].index) - set(p[3].index)] |
def p_list_and(self, p):
'list : list AND list'
p[0] = pd.concat(
[p[1], p[3]], axis=1).dropna().apply(self.func, axis=1) |
def p_list_or(self, p):
'list : list OR list'
p[0] = pd.concat(
[p[1], p[3]], axis=1).fillna(0.0).apply(self.func, axis=1) |
def p_list_feature(self, p):
'''list : feature
| WORD '''
p[0] = self.dataset.get_studies(
features=p[1], frequency_threshold=self.threshold, func=self.func,
return_type='weights') |
def average_within_regions(dataset, regions, masker=None, threshold=None,
remove_zero=True):
""" Aggregates over all voxels within each ROI in the input image.
Takes a Dataset and a Nifti image that defines distinct regions, and
returns a numpy matrix of ROIs x mappables, where ... |
def apply_grid(dataset, masker=None, scale=5, threshold=None):
""" Imposes a 3D grid on the brain volume and averages across all voxels
that fall within each cell.
Args:
dataset: Data to apply grid to. Either a Dataset instance, or a numpy
array with voxels in rows and features in column... |
def get_random_voxels(dataset, n_voxels):
""" Returns mappable data for a random subset of voxels.
May be useful as a baseline in predictive analyses--e.g., to compare
performance of a more principled feature selection method with simple
random selection.
Args:
dataset: A Dataset instance
... |
def _get_top_words(model, feature_names, n_top_words=40):
""" Return top forty words from each topic in trained topic model.
"""
topic_words = []
for topic in model.components_:
top_words = [feature_names[i] for i in topic.argsort()[:-n_top_words-1:-1]]
topic_words += [top_words]
ret... |
def run_lda(abstracts, n_topics=50, n_words=31, n_iters=1000, alpha=None,
beta=0.001):
""" Perform topic modeling using Latent Dirichlet Allocation with the
Java toolbox MALLET.
Args:
abstracts: A pandas DataFrame with two columns ('pmid' and 'abstract')
containing ... |
def pearson(x, y):
""" Correlates row vector x with each row vector in 2D array y. """
data = np.vstack((x, y))
ms = data.mean(axis=1)[(slice(None, None, None), None)]
datam = data - ms
datass = np.sqrt(np.sum(datam**2, axis=1))
temp = np.dot(datam[1:], datam[0].T)
rs = temp / (datass[1:] * ... |
def two_way(cells):
""" Two-way chi-square test of independence.
Takes a 3D array as input: N(voxels) x 2 x 2, where the last two dimensions
are the contingency table for each of N voxels. Returns an array of
p-values.
"""
# Mute divide-by-zero warning for bad voxels since we account for that
... |
def one_way(data, n):
""" One-way chi-square test of independence.
Takes a 1D array as input and compares activation at each voxel to
proportion expected under a uniform distribution throughout the array. Note
that if you're testing activation with this, make sure that only valid
voxels (e.g., in-ma... |
def fdr(p, q=.05):
""" Determine FDR threshold given a p value array and desired false
discovery rate q. """
s = np.sort(p)
nvox = p.shape[0]
null = np.array(range(1, nvox + 1), dtype='float') * q / nvox
below = np.where(s <= null)[0]
return s[max(below)] if len(below) else -1 |
def download(path='.', url=None, unpack=False):
""" Download the latest data files.
Args:
path (str): Location to save the retrieved data files. Defaults to
current directory.
unpack (bool): If True, unzips the data file post-download.
"""
if url is None:
url = 'http... |
def download_abstracts(dataset, path='.', email=None, out_file=None):
""" Download the abstracts for a dataset/list of pmids
"""
try:
from Bio import Entrez, Medline
except:
raise Exception(
'Module biopython is required for downloading abstracts from PubMed.')
if email ... |
def _load_activations(self, filename):
""" Load activation data from a text file.
Args:
filename (str): a string pointing to the location of the txt file
to read from.
"""
logger.info("Loading activation data from %s..." % filename)
activations = pd.... |
def create_image_table(self, r=None):
""" Create and store a new ImageTable instance based on the current
Dataset. Will generally be called privately, but may be useful as a
convenience method in cases where the user wants to re-generate the
table with a new smoothing kernel of different... |
def get_studies(self, features=None, expression=None, mask=None,
peaks=None, frequency_threshold=0.001,
activation_threshold=0.0, func=np.sum, return_type='ids',
r=6
):
""" Get IDs or data for studies that meet specific criteria.
... |
def add_features(self, features, append=True, merge='outer',
duplicates='ignore', min_studies=0.0, threshold=0.001):
""" Construct a new FeatureTable from file.
Args:
features: Feature data to add. Can be:
(a) A text file containing the feature data, whe... |
def get_image_data(self, ids=None, voxels=None, dense=True):
""" A convenience wrapper for ImageTable.get_image_data().
Args:
ids (list, array): A list or 1D numpy array of study ids to
return. If None, returns data for all studies.
voxels (list, array): A list o... |
def get_feature_names(self, features=None):
""" Returns names of features. If features is None, returns all
features. Otherwise assumes the user is trying to find the order of the
features. """
if features:
return self.feature_table.get_ordered_names(features)
else:
... |
def get_feature_counts(self, threshold=0.001):
""" Returns a dictionary, where the keys are the feature names
and the values are the number of studies tagged with the feature. """
counts = np.sum(self.get_feature_data() >= threshold, 0)
return dict(zip(self.get_feature_names(), list(coun... |
def load(cls, filename):
""" Load a pickled Dataset instance from file. """
try:
dataset = pickle.load(open(filename, 'rb'))
except UnicodeDecodeError:
# Need to try this for python3
dataset = pickle.load(open(filename, 'rb'), encoding='latin')
if has... |
def save(self, filename):
""" Pickle the Dataset instance to the provided file.
"""
if hasattr(self, 'feature_table'):
self.feature_table._sdf_to_csr()
pickle.dump(self, open(filename, 'wb'), -1)
if hasattr(self, 'feature_table'):
self.feature_table._csr... |
def get_image_data(self, ids=None, voxels=None, dense=True):
""" Slices and returns a subset of image data.
Args:
ids (list, array): A list or 1D numpy array of study ids to
return. If None, returns data for all studies.
voxels (list, array): A list or 1D numpy a... |
def trim(self, ids):
""" Trim ImageTable to keep only the passed studies. This is a
convenience method, and should generally be avoided in favor of
non-destructive alternatives that don't require slicing (e.g.,
matrix multiplication). """
self.data = self.get_image_data(ids, ... |
def add_features(self, features, merge='outer', duplicates='ignore',
min_studies=0, threshold=0.0001):
""" Add new features to FeatureTable.
Args:
features (str, DataFrame): A filename to load data from, or a
pandas DataFrame. In either case, studies are ... |
def get_feature_data(self, ids=None, features=None, dense=True):
""" Slices and returns a subset of feature data.
Args:
ids (list, array): A list or 1D numpy array of study ids to
return rows for. If None, returns data for all studies
(i.e., all rows in array... |
def get_ordered_names(self, features):
""" Given a list of features, returns features in order that they
appear in database.
Args:
features (list): A list or 1D numpy array of named features to
return.
Returns:
A list of features in order they appear... |
def get_ids(self, features, threshold=0.0, func=np.sum, get_weights=False):
""" Returns a list of all studies in the table that meet the desired
feature-based criteria.
Will most commonly be used to retrieve studies that use one or more
features with some minimum frequency; e.g.,:
... |
def search_features(self, search):
''' Returns all features that match any of the elements in the input
list.
Args:
search (str, list): A string or list of strings defining the query.
Returns:
A list of matching feature names.
'''
if isinstance(s... |
def get_ids_by_expression(self, expression, threshold=0.001, func=np.sum):
""" Use a PEG to parse expression and return study IDs."""
lexer = lp.Lexer()
lexer.build()
parser = lp.Parser(
lexer, self.dataset, threshold=threshold, func=func)
parser.build()
retur... |
def get_features_by_ids(self, ids=None, threshold=0.0001, func=np.mean,
get_weights=False):
''' Returns features for which the mean loading across all specified
studies (in ids) is >= threshold. '''
weights = self.data.ix[ids].apply(func, 0)
above_thresh = wei... |
def _sdf_to_csr(self):
""" Convert FeatureTable to SciPy CSR matrix. """
data = self.data.to_dense()
self.data = {
'columns': list(data.columns),
'index': list(data.index),
'values': sparse.csr_matrix(data.values)
} |
def _csr_to_sdf(self):
""" Inverse of _sdf_to_csr(). """
self.data = pd.DataFrame(self.data['values'].todense(),
index=self.data['index'],
columns=self.data['columns']).to_sparse() |
def deprecated(*args):
""" Deprecation warning decorator. Takes optional deprecation message,
otherwise will use a generic warning. """
def wrap(func):
def wrapped_func(*args, **kwargs):
warnings.warn(msg, category=DeprecationWarning)
return func(*args, **kwargs)
retu... |
def magic(dataset, method='coactivation', roi_mask=None,
coactivation_mask=None, features=None, feature_threshold=0.05,
min_voxels_per_study=None, min_studies_per_voxel=None,
reduce_reference='pca', n_components=100,
distance_metric='correlation', clustering_algorithm='kmeans',
... |
def transform(self, transformer, transpose=False):
''' Apply a transformation to the Clusterable instance. Accepts any
scikit-learn-style class that implements a fit_transform() method. '''
data = self.data.T if transpose else self.data
data = transformer.fit_transform(data)
self... |
def analyze_features(dataset, features=None, image_type='association-test_z',
threshold=0.001, q=0.01, output_dir=None, prefix=None):
""" Generate meta-analysis images for a set of features.
Args:
dataset: A Dataset instance containing feature and activation data.
features: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.