_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q270100 | ExecuteHomeAssistant.get_url | test | def get_url(self):
"""Home assistant url
:return: url
:rtype: str
"""
url = super(ExecuteHomeAssistant, self).get_url()
if not self.data.get('event'):
raise InvalidConfig(extra_body='Event option is required for HomeAsistant on {} device.'.format(self.name))
... | python | {
"resource": ""
} |
q270101 | ExecuteIFTTT.get_url | test | def get_url(self):
"""IFTTT Webhook url
:return: url
:rtype: str
"""
if not self.data[self.execute_name]:
raise InvalidConfig(extra_body='Value for IFTTT is required on {} device. Get your key here: '
'https://ifttt.com/serv... | python | {
"resource": ""
} |
q270102 | pkt_text | test | def pkt_text(pkt):
"""Return source mac address for this Scapy Packet
:param scapy.packet.Packet pkt: Scapy Packet
:return: Mac address. Include (Amazon Device) for these devices
:rtype: str
"""
if pkt.src.upper() in BANNED_DEVICES:
body = ''
elif pkt.src.upper()[:8] in AMAZON_DEVIC... | python | {
"resource": ""
} |
q270103 | discovery_print | test | def discovery_print(pkt):
"""Scandevice callback. Register src mac to avoid src repetition.
Print device on screen.
:param scapy.packet.Packet pkt: Scapy Packet
:return: None
"""
if pkt.src in mac_id_list:
return
mac_id_list.append(pkt.src)
text = pkt_text(pkt)
click.secho(t... | python | {
"resource": ""
} |
q270104 | discover | test | def discover(interface=None):
"""Print help and scan devices on screen.
:return: None
"""
click.secho(HELP, fg='yellow')
scan_devices(discovery_print, lfilter=lambda d: d.src not in mac_id_list, iface=interface) | python | {
"resource": ""
} |
q270105 | Device.execute | test | def execute(self, root_allowed=False):
"""Execute this device
:param bool root_allowed: Only used for ExecuteCmd
:return: None
"""
logger.debug('%s device executed (mac %s)', self.name, self.src)
if not self.execute_instance:
msg = '%s: There is not execution... | python | {
"resource": ""
} |
q270106 | Device.send_confirmation | test | def send_confirmation(self, message, success=True):
"""Send success or error message to configured confirmation
:param str message: Body message to send
:param bool success: Device executed successfully to personalize message
:return: None
"""
message = message.strip()
... | python | {
"resource": ""
} |
q270107 | Listener.on_push | test | def on_push(self, device):
"""Press button. Check DEFAULT_DELAY.
:param scapy.packet.Packet device: Scapy packet
:return: None
"""
src = device.src.lower()
if last_execution[src] + self.settings.get('delay', DEFAULT_DELAY) > time.time():
return
last_e... | python | {
"resource": ""
} |
q270108 | Listener.execute | test | def execute(self, device):
"""Execute a device. Used if the time between executions is greater than DEFAULT_DELAY
:param scapy.packet.Packet device: Scapy packet
:return: None
"""
src = device.src.lower()
device = self.devices[src]
threading.Thread(target=device.... | python | {
"resource": ""
} |
q270109 | Listener.run | test | def run(self, root_allowed=False):
"""Start daemon mode
:param bool root_allowed: Only used for ExecuteCmd
:return: loop
"""
self.root_allowed = root_allowed
scan_devices(self.on_push, lambda d: d.src.lower() in self.devices, self.settings.get('interface')) | python | {
"resource": ""
} |
q270110 | OfxConverter.convert | test | def convert(self, txn):
"""
Convert an OFX Transaction to a posting
"""
ofxid = self.mk_ofxid(txn.id)
metadata = {}
posting_metadata = {"ofxid": ofxid}
if isinstance(txn, OfxTransaction):
posting = Posting(self.name,
Amo... | python | {
"resource": ""
} |
q270111 | find_ledger_file | test | def find_ledger_file(ledgerrcpath=None):
"""Returns main ledger file path or raise exception if it cannot be \
found."""
if ledgerrcpath is None:
ledgerrcpath = os.path.abspath(os.path.expanduser("~/.ledgerrc"))
if "LEDGER_FILE" in os.environ:
return os.path.abspath(os.path.expanduser(os.env... | python | {
"resource": ""
} |
q270112 | compatibility | test | def compatibility(session, install):
"""Run the unit test suite with each support library and Python version."""
session.install('-e', '.[dev]')
session.install(install)
_run_tests(session) | python | {
"resource": ""
} |
q270113 | get_long_description | test | def get_long_description():
"""Transform README.md into a usable long description.
Replaces relative references to svg images to absolute https references.
"""
with open('README.md') as f:
read_me = f.read()
def replace_relative_with_absolute(match):
svg_path = match.group(0)[1:-1... | python | {
"resource": ""
} |
q270114 | PrecalculatedTextMeasurer.from_json | test | def from_json(f: TextIO) -> 'PrecalculatedTextMeasurer':
"""Return a PrecalculatedTextMeasurer given a JSON stream.
See precalculate_text.py for details on the required format.
"""
o = json.load(f)
return PrecalculatedTextMeasurer(o['mean-character-length'],
... | python | {
"resource": ""
} |
q270115 | PrecalculatedTextMeasurer.default | test | def default(cls) -> 'PrecalculatedTextMeasurer':
"""Returns a reasonable default PrecalculatedTextMeasurer."""
if cls._default_cache is not None:
return cls._default_cache
if pkg_resources.resource_exists(__name__, 'default-widths.json.xz'):
import lzma
with ... | python | {
"resource": ""
} |
q270116 | badge | test | def badge(left_text: str, right_text: str, left_link: Optional[str] = None,
right_link: Optional[str] = None,
whole_link: Optional[str] = None, logo: Optional[str] = None,
left_color: str = '#555', right_color: str = '#007ec6',
measurer: Optional[text_measurer.TextMeasurer] = Non... | python | {
"resource": ""
} |
q270117 | generate_supported_characters | test | def generate_supported_characters(deja_vu_sans_path: str) -> Iterable[str]:
"""Generate the characters support by the font at the given path."""
font = ttLib.TTFont(deja_vu_sans_path)
for cmap in font['cmap'].tables:
if cmap.isUnicode():
for code in cmap.cmap:
yield chr(c... | python | {
"resource": ""
} |
q270118 | generate_encodeable_characters | test | def generate_encodeable_characters(characters: Iterable[str],
encodings: Iterable[str]) -> Iterable[str]:
"""Generates the subset of 'characters' that can be encoded by 'encodings'.
Args:
characters: The characters to check for encodeability e.g. 'abcd'.
encod... | python | {
"resource": ""
} |
q270119 | calculate_character_to_length_mapping | test | def calculate_character_to_length_mapping(
measurer: text_measurer.TextMeasurer,
characters: Iterable[str]) -> Mapping[str, float]:
"""Return a mapping between each given character and its length.
Args:
measurer: The TextMeasurer used to measure the width of the text in
pixe... | python | {
"resource": ""
} |
q270120 | write_json | test | def write_json(f: TextIO, deja_vu_sans_path: str,
measurer: text_measurer.TextMeasurer,
encodings: Iterable[str]) -> None:
"""Write the data required by PrecalculatedTextMeasurer to a stream."""
supported_characters = list(
generate_supported_characters(deja_vu_sans_path))
... | python | {
"resource": ""
} |
q270121 | convolve_gaussian_2d | test | def convolve_gaussian_2d(image, gaussian_kernel_1d):
"""Convolve 2d gaussian."""
result = scipy.ndimage.filters.correlate1d(
image, gaussian_kernel_1d, axis=0)
result = scipy.ndimage.filters.correlate1d(
result, gaussian_kernel_1d, axis=1)
return result | python | {
"resource": ""
} |
q270122 | get_gaussian_kernel | test | def get_gaussian_kernel(gaussian_kernel_width=11, gaussian_kernel_sigma=1.5):
"""Generate a gaussian kernel."""
# 1D Gaussian kernel definition
gaussian_kernel_1d = numpy.ndarray((gaussian_kernel_width))
norm_mu = int(gaussian_kernel_width / 2)
# Fill Gaussian kernel
for i in range(gaussian_ker... | python | {
"resource": ""
} |
q270123 | to_grayscale | test | def to_grayscale(img):
"""Convert PIL image to numpy grayscale array and numpy alpha array.
Args:
img (PIL.Image): PIL Image object.
Returns:
(gray, alpha): both numpy arrays.
"""
gray = numpy.asarray(ImageOps.grayscale(img)).astype(numpy.float)
imbands = img.getbands()
alpha ... | python | {
"resource": ""
} |
q270124 | main | test | def main():
"""Main function for pyssim."""
description = '\n'.join([
'Compares an image with a list of images using the SSIM metric.',
' Example:',
' pyssim test-images/test1-1.png "test-images/*"'
])
parser = argparse.ArgumentParser(
prog='pyssim', formatter_class... | python | {
"resource": ""
} |
q270125 | SSIM.ssim_value | test | def ssim_value(self, target):
"""Compute the SSIM value from the reference image to the target image.
Args:
target (str or PIL.Image): Input image to compare the reference image
to. This may be a PIL Image object or, to save time, an SSIMImage
object (e.g. the img member o... | python | {
"resource": ""
} |
q270126 | compute_ssim | test | def compute_ssim(image1, image2, gaussian_kernel_sigma=1.5,
gaussian_kernel_width=11):
"""Computes SSIM.
Args:
im1: First PIL Image object to compare.
im2: Second PIL Image object to compare.
Returns:
SSIM float value.
"""
gaussian_kernel_1d = get_gaussian_kernel... | python | {
"resource": ""
} |
q270127 | SyncObj.destroy | test | def destroy(self):
"""
Correctly destroy SyncObj. Stop autoTickThread, close connections, etc.
"""
if self.__conf.autoTick:
self.__destroying = True
else:
self._doDestroy() | python | {
"resource": ""
} |
q270128 | SyncObj.setCodeVersion | test | def setCodeVersion(self, newVersion, callback = None):
"""Switch to a new code version on all cluster nodes. You
should ensure that cluster nodes are updated, otherwise they
won't be able to apply commands.
:param newVersion: new code version
:type int
:param callback: w... | python | {
"resource": ""
} |
q270129 | SyncObj.getStatus | test | def getStatus(self):
"""Dumps different debug info about cluster to dict and return it"""
status = {}
status['version'] = VERSION
status['revision'] = REVISION
status['self'] = self.__selfNode
status['state'] = self.__raftState
status['leader'] = self.__raftLeade... | python | {
"resource": ""
} |
q270130 | SyncObj.printStatus | test | def printStatus(self):
"""Dumps different debug info about cluster to default logger"""
status = self.getStatus()
for k, v in iteritems(status):
logging.info('%s: %s' % (str(k), str(v))) | python | {
"resource": ""
} |
q270131 | TCPTransport._connToNode | test | def _connToNode(self, conn):
"""
Find the node to which a connection belongs.
:param conn: connection object
:type conn: TcpConnection
:returns corresponding node or None if the node cannot be found
:rtype Node or None
"""
for node in self._connections:
... | python | {
"resource": ""
} |
q270132 | TCPTransport._maybeBind | test | def _maybeBind(self):
"""
Bind the server unless it is already bound, this is a read-only node, or the last attempt was too recently.
:raises TransportNotReadyError if the bind attempt fails
"""
if self._ready or self._selfIsReadonlyNode or time.time() < self._lastBindAttemptTi... | python | {
"resource": ""
} |
q270133 | TCPTransport._onNewIncomingConnection | test | def _onNewIncomingConnection(self, conn):
"""
Callback for connections initiated by the other side
:param conn: connection object
:type conn: TcpConnection
"""
self._unknownConnections.add(conn)
encryptor = self._syncObj.encryptor
if encryptor:
... | python | {
"resource": ""
} |
q270134 | TCPTransport._onIncomingMessageReceived | test | def _onIncomingMessageReceived(self, conn, message):
"""
Callback for initial messages on incoming connections. Handles encryption, utility messages, and association of the connection with a Node.
Once this initial setup is done, the relevant connected callback is executed, and further messages ... | python | {
"resource": ""
} |
q270135 | TCPTransport._utilityCallback | test | def _utilityCallback(self, res, err, conn, cmd, arg):
"""
Callback for the utility messages
:param res: result of the command
:param err: error code (one of pysyncobj.config.FAIL_REASON)
:param conn: utility connection
:param cmd: command
:param arg: command argu... | python | {
"resource": ""
} |
q270136 | TCPTransport._shouldConnect | test | def _shouldConnect(self, node):
"""
Check whether this node should initiate a connection to another node
:param node: the other node
:type node: Node
"""
return isinstance(node, TCPNode) and node not in self._preventConnectNodes and (self._selfIsReadonlyNode or self._se... | python | {
"resource": ""
} |
q270137 | TCPTransport._connectIfNecessarySingle | test | def _connectIfNecessarySingle(self, node):
"""
Connect to a node if necessary.
:param node: node to connect to
:type node: Node
"""
if node in self._connections and self._connections[node].state != CONNECTION_STATE.DISCONNECTED:
return True
if not se... | python | {
"resource": ""
} |
q270138 | TCPTransport._onOutgoingConnected | test | def _onOutgoingConnected(self, conn):
"""
Callback for when a new connection from this to another node is established. Handles encryption and informs the other node which node this is.
If encryption is disabled, this triggers the onNodeConnected callback and messages are deferred to the onMessag... | python | {
"resource": ""
} |
q270139 | TCPTransport._onOutgoingMessageReceived | test | def _onOutgoingMessageReceived(self, conn, message):
"""
Callback for receiving a message on a new outgoing connection. Used only if encryption is enabled to exchange the random keys.
Once the key exchange is done, this triggers the onNodeConnected callback, and further messages are deferred to ... | python | {
"resource": ""
} |
q270140 | TCPTransport._onDisconnected | test | def _onDisconnected(self, conn):
"""
Callback for when a connection is terminated or considered dead. Initiates a reconnect if necessary.
:param conn: connection object
:type conn: TcpConnection
"""
self._unknownConnections.discard(conn)
node = self._connToNode(... | python | {
"resource": ""
} |
q270141 | TCPTransport.addNode | test | def addNode(self, node):
"""
Add a node to the network
:param node: node to add
:type node: TCPNode
"""
self._nodes.add(node)
self._nodeAddrToNode[node.address] = node
if self._shouldConnect(node):
conn = TcpConnection(poller = self._syncObj.... | python | {
"resource": ""
} |
q270142 | TCPTransport.dropNode | test | def dropNode(self, node):
"""
Drop a node from the network
:param node: node to drop
:type node: Node
"""
conn = self._connections.pop(node, None)
if conn is not None:
# Calling conn.disconnect() immediately triggers the onDisconnected callback if th... | python | {
"resource": ""
} |
q270143 | TCPTransport.send | test | def send(self, node, message):
"""
Send a message to a node. Returns False if the connection appears to be dead either before or after actually trying to send the message.
:param node: target node
:type node: Node
:param message: message
:param message: any
:retu... | python | {
"resource": ""
} |
q270144 | TCPTransport.destroy | test | def destroy(self):
"""
Destroy this transport
"""
self.setOnMessageReceivedCallback(None)
self.setOnNodeConnectedCallback(None)
self.setOnNodeDisconnectedCallback(None)
self.setOnReadonlyNodeConnectedCallback(None)
self.setOnReadonlyNodeDisconnectedCallba... | python | {
"resource": ""
} |
q270145 | ReplQueue.put | test | def put(self, item):
"""Put an item into the queue.
True - if item placed in queue.
False - if queue is full and item can not be placed."""
if self.__maxsize and len(self.__data) >= self.__maxsize:
return False
self.__data.append(item)
return True | python | {
"resource": ""
} |
q270146 | ReplPriorityQueue.put | test | def put(self, item):
"""Put an item into the queue. Items should be comparable, eg. tuples.
True - if item placed in queue.
False - if queue is full and item can not be placed."""
if self.__maxsize and len(self.__data) >= self.__maxsize:
return False
heapq.heappush(se... | python | {
"resource": ""
} |
q270147 | ReplPriorityQueue.get | test | def get(self, default=None):
"""Extract the smallest item from queue.
Return default if queue is empty."""
if not self.__data:
return default
return heapq.heappop(self.__data) | python | {
"resource": ""
} |
q270148 | ReplLockManager.tryAcquire | test | def tryAcquire(self, lockID, callback=None, sync=False, timeout=None):
"""Attempt to acquire lock.
:param lockID: unique lock identifier.
:type lockID: str
:param sync: True - to wait until lock is acquired or failed to acquire.
:type sync: bool
:param callback: if sync ... | python | {
"resource": ""
} |
q270149 | ReplLockManager.isAcquired | test | def isAcquired(self, lockID):
"""Check if lock is acquired by ourselves.
:param lockID: unique lock identifier.
:type lockID: str
:return True if lock is acquired by ourselves.
"""
return self.__lockImpl.isAcquired(lockID, self.__selfID, time.time()) | python | {
"resource": ""
} |
q270150 | ReplLockManager.release | test | def release(self, lockID, callback=None, sync=False, timeout=None):
"""
Release previously-acquired lock.
:param lockID: unique lock identifier.
:type lockID: str
:param sync: True - to wait until lock is released or failed to release.
:type sync: bool
:param ca... | python | {
"resource": ""
} |
q270151 | check | test | def check(func):
"""
Decorator which wraps checks and returns an error response on failure.
"""
def wrapped(*args, **kwargs):
check_name = func.__name__
arg_name = None
if args:
arg_name = args[0]
try:
if arg_name:
logger.debug("Che... | python | {
"resource": ""
} |
q270152 | token_required | test | def token_required(view_func):
"""
Decorator which ensures that one of the WATCHMAN_TOKENS is provided if set.
WATCHMAN_TOKEN_NAME can also be set if the token GET parameter must be
customized.
"""
def _parse_auth_header(auth_header):
"""
Parse the `Authorization` header
... | python | {
"resource": ""
} |
q270153 | set_hosts | test | def set_hosts(hosts, use_ssl=False, ssl_cert_path=None):
"""
Sets the Elasticsearch hosts to use
Args:
hosts (str): A single hostname or URL, or list of hostnames or URLs
use_ssl (bool): Use a HTTPS connection to the server
ssl_cert_path (str): Path to the certificate chain
"""
... | python | {
"resource": ""
} |
q270154 | create_indexes | test | def create_indexes(names, settings=None):
"""
Create Elasticsearch indexes
Args:
names (list): A list of index names
settings (dict): Index settings
"""
for name in names:
index = Index(name)
try:
if not index.exists():
logger.debug("Crea... | python | {
"resource": ""
} |
q270155 | migrate_indexes | test | def migrate_indexes(aggregate_indexes=None, forensic_indexes=None):
"""
Updates index mappings
Args:
aggregate_indexes (list): A list of aggregate index names
forensic_indexes (list): A list of forensic index names
"""
version = 2
if aggregate_indexes is None:
aggregate_... | python | {
"resource": ""
} |
q270156 | KafkaClient.strip_metadata | test | def strip_metadata(report):
"""
Duplicates org_name, org_email and report_id into JSON root
and removes report_metadata key to bring it more inline
with Elastic output.
"""
report['org_name'] = report['report_metadata']['org_name']
report['org_email'] = repo... | python | {
"resource": ""
} |
q270157 | KafkaClient.save_aggregate_reports_to_kafka | test | def save_aggregate_reports_to_kafka(self, aggregate_reports,
aggregate_topic):
"""
Saves aggregate DMARC reports to Kafka
Args:
aggregate_reports (list): A list of aggregate report dictionaries
to save to Kafka
aggrega... | python | {
"resource": ""
} |
q270158 | extract_xml | test | def extract_xml(input_):
"""
Extracts xml from a zip or gzip file at the given path, file-like object,
or bytes.
Args:
input_: A path to a file, a file like object, or bytes
Returns:
str: The extracted XML
"""
if type(input_) == str:
file_object = open(input_, "rb"... | python | {
"resource": ""
} |
q270159 | parse_aggregate_report_file | test | def parse_aggregate_report_file(_input, nameservers=None, dns_timeout=2.0,
parallel=False):
"""Parses a file at the given path, a file-like object. or bytes as a
aggregate DMARC report
Args:
_input: A path to a file, a file like object, or bytes
nameservers (... | python | {
"resource": ""
} |
q270160 | parsed_forensic_reports_to_csv | test | def parsed_forensic_reports_to_csv(reports):
"""
Converts one or more parsed forensic reports to flat CSV format, including
headers
Args:
reports: A parsed forensic report or list of parsed forensic reports
Returns:
str: Parsed forensic report data in flat CSV format, including hea... | python | {
"resource": ""
} |
q270161 | parse_report_file | test | 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
... | python | {
"resource": ""
} |
q270162 | get_imap_capabilities | test | 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... | python | {
"resource": ""
} |
q270163 | save_output | test | 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[... | python | {
"resource": ""
} |
q270164 | get_report_zip | test | 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... | python | {
"resource": ""
} |
q270165 | email_results | test | 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
... | python | {
"resource": ""
} |
q270166 | HECClient.save_aggregate_reports_to_splunk | test | 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... | python | {
"resource": ""
} |
q270167 | HECClient.save_forensic_reports_to_splunk | test | 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")
... | python | {
"resource": ""
} |
q270168 | decode_base64 | test | 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'=... | python | {
"resource": ""
} |
q270169 | get_base_domain | test | 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... | python | {
"resource": ""
} |
q270170 | get_reverse_dns | test | 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 ... | python | {
"resource": ""
} |
q270171 | human_timestamp_to_datetime | test | 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
"... | python | {
"resource": ""
} |
q270172 | get_ip_address_country | test | 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... | python | {
"resource": ""
} |
q270173 | get_ip_address_info | test | 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... | python | {
"resource": ""
} |
q270174 | convert_outlook_msg | test | 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... | python | {
"resource": ""
} |
q270175 | _str_to_list | test | def _str_to_list(s):
"""Converts a comma separated string to a list"""
_list = s.split(",")
return list(map(lambda i: i.lstrip(), _list)) | python | {
"resource": ""
} |
q270176 | cli_parse | test | 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,
... | python | {
"resource": ""
} |
q270177 | Client.drain | test | 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... | python | {
"resource": ""
} |
q270178 | Client.publish | test | 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:
... | python | {
"resource": ""
} |
q270179 | Client.publish_request | test | 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 ... | python | {
"resource": ""
} |
q270180 | Client._publish | test | 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... | python | {
"resource": ""
} |
q270181 | Client.subscribe_async | test | 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 | python | {
"resource": ""
} |
q270182 | Client.unsubscribe | test | 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... | python | {
"resource": ""
} |
q270183 | Client.flush | test | 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... | python | {
"resource": ""
} |
q270184 | Client._select_next_server | test | 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... | python | {
"resource": ""
} |
q270185 | Client._process_err | test | 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... | python | {
"resource": ""
} |
q270186 | Client._process_op_err | test | 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.... | python | {
"resource": ""
} |
q270187 | Client._connect_command | test | 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"],
... | python | {
"resource": ""
} |
q270188 | Client._process_pong | test | 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 | python | {
"resource": ""
} |
q270189 | Client._process_msg | test | 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... | python | {
"resource": ""
} |
q270190 | Client._process_info | test | 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... | python | {
"resource": ""
} |
q270191 | Client._process_connect_init | test | 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... | python | {
"resource": ""
} |
q270192 | Client._flusher | test | 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... | python | {
"resource": ""
} |
q270193 | Client._read_loop | test | 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 ... | python | {
"resource": ""
} |
q270194 | coactivation | test | 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.
... | python | {
"resource": ""
} |
q270195 | Decoder.decode | test | 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... | python | {
"resource": ""
} |
q270196 | Decoder._load_features_from_array | test | 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]) | python | {
"resource": ""
} |
q270197 | Decoder._load_features_from_images | test | 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... | python | {
"resource": ""
} |
q270198 | Decoder._pearson_correlation | test | 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 ... | python | {
"resource": ""
} |
q270199 | Decoder._dot_product | test | def _dot_product(self, imgs_to_decode):
""" Decoding using the dot product.
"""
return np.dot(imgs_to_decode.T, self.feature_images).T | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.