_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q2500 | RepoResultManager.add_git | train | def add_git(meta, git_info):
"""Enrich the result meta information with commit data."""
meta["hexsha"] = git_info.hexsha
meta["author"] = git_info.author
meta["email"] = git_info.email
meta["authored_on"] = git_info.authored_on.isoformat(" ") | python | {
"resource": ""
} |
q2501 | RepoResultManager.load | train | def load(self, commit=None):
"""Load a result from the storage directory."""
git_info = self.record_git_info(commit)
LOGGER.debug("Loading the result for commit '%s'.", git_info.hexsha)
filename = self.get_filename(git_info)
LOGGER.debug("Loading the result '%s'.", filename)
... | python | {
"resource": ""
} |
q2502 | MemoteExtension.normalize | train | def normalize(filename):
"""Return an absolute path of the given file name."""
# Default value means we do not resolve a model file.
if filename == "default":
return filename
filename = expanduser(filename)
if isabs(filename):
return filename
else:... | python | {
"resource": ""
} |
q2503 | GrowthExperiment.evaluate | train | def evaluate(self, model, threshold=0.1):
"""Evaluate in silico growth rates."""
with model:
if self.medium is not None:
self.medium.apply(model)
if self.objective is not None:
model.objective = self.objective
model.add_cons_vars(self.c... | python | {
"resource": ""
} |
q2504 | BJSON.process_bind_param | train | def process_bind_param(self, value, dialect):
"""Convert the value to a JSON encoded string before storing it."""
try:
with BytesIO() as stream:
with GzipFile(fileobj=stream, mode="wb") as file_handle:
file_handle.write(
jsonify(val... | python | {
"resource": ""
} |
q2505 | BJSON.process_result_value | train | def process_result_value(self, value, dialect):
"""Convert a JSON encoded string to a dictionary structure."""
if value is not None:
with BytesIO(value) as stream:
with GzipFile(fileobj=stream, mode="rb") as file_handle:
value = json.loads(file_handle.read... | python | {
"resource": ""
} |
q2506 | ZXCVBNValidator.validate | train | def validate(self, password, user=None):
"""Validate method, run zxcvbn and check score."""
user_inputs = []
if user is not None:
for attribute in self.user_attributes:
if hasattr(user, attribute):
user_inputs.append(getattr(user, attribute))
... | python | {
"resource": ""
} |
q2507 | _get_html_contents | train | def _get_html_contents(html):
"""Process a HTML block and detects whether it is a code block,
a math block, or a regular HTML block."""
parser = MyHTMLParser()
parser.feed(html)
if parser.is_code:
return ('code', parser.data.strip())
elif parser.is_math:
return ('math', parser.da... | python | {
"resource": ""
} |
q2508 | _is_path | train | def _is_path(s):
"""Return whether an object is a path."""
if isinstance(s, string_types):
try:
return op.exists(s)
except (OSError, ValueError):
return False
else:
return False | python | {
"resource": ""
} |
q2509 | FormatManager.format_manager | train | def format_manager(cls):
"""Return the instance singleton, creating if necessary
"""
if cls._instance is None:
# Discover the formats and register them with a new singleton.
cls._instance = cls().register_entrypoints()
return cls._instance | python | {
"resource": ""
} |
q2510 | FormatManager.register_entrypoints | train | def register_entrypoints(self):
"""Look through the `setup_tools` `entry_points` and load all of
the formats.
"""
for spec in iter_entry_points(self.entry_point_group):
format_properties = {"name": spec.name}
try:
format_properties.update(spec.l... | python | {
"resource": ""
} |
q2511 | FormatManager.format_from_extension | train | def format_from_extension(self, extension):
"""Find a format from its extension."""
formats = [name
for name, format in self._formats.items()
if format.get('file_extension', None) == extension]
if len(formats) == 0:
return None
elif len(f... | python | {
"resource": ""
} |
q2512 | FormatManager.load | train | def load(self, file, name=None):
"""Load a file. The format name can be specified explicitly or
inferred from the file extension."""
if name is None:
name = self.format_from_extension(op.splitext(file)[1])
file_format = self.file_type(name)
if file_format == 'text':
... | python | {
"resource": ""
} |
q2513 | FormatManager.save | train | def save(self, file, contents, name=None, overwrite=False):
"""Save contents into a file. The format name can be specified
explicitly or inferred from the file extension."""
if name is None:
name = self.format_from_extension(op.splitext(file)[1])
file_format = self.file_type(... | python | {
"resource": ""
} |
q2514 | FormatManager.create_reader | train | def create_reader(self, name, *args, **kwargs):
"""Create a new reader instance for a given format."""
self._check_format(name)
return self._formats[name]['reader'](*args, **kwargs) | python | {
"resource": ""
} |
q2515 | FormatManager.create_writer | train | def create_writer(self, name, *args, **kwargs):
"""Create a new writer instance for a given format."""
self._check_format(name)
return self._formats[name]['writer'](*args, **kwargs) | python | {
"resource": ""
} |
q2516 | FormatManager.convert | train | def convert(self,
contents_or_path,
from_=None,
to=None,
reader=None,
writer=None,
from_kwargs=None,
to_kwargs=None,
):
"""Convert contents between supported formats.
Paramete... | python | {
"resource": ""
} |
q2517 | FormatManager.clean_meta | train | def clean_meta(self, meta):
"""Removes unwanted metadata
Parameters
----------
meta : dict
Notebook metadata.
"""
if not self.verbose_metadata:
default_kernel_name = (self.default_kernel_name or
self._km.kernel_... | python | {
"resource": ""
} |
q2518 | FormatManager.clean_cell_meta | train | def clean_cell_meta(self, meta):
"""Remove cell metadata that matches the default cell metadata."""
for k, v in DEFAULT_CELL_METADATA.items():
if meta.get(k, None) == v:
meta.pop(k, None)
return meta | python | {
"resource": ""
} |
q2519 | _starts_with_regex | train | def _starts_with_regex(line, regex):
"""Return whether a line starts with a regex or not."""
if not regex.startswith('^'):
regex = '^' + regex
reg = re.compile(regex)
return reg.match(line) | python | {
"resource": ""
} |
q2520 | create_prompt | train | def create_prompt(prompt):
"""Create a prompt manager.
Parameters
----------
prompt : str or class driving from BasePromptManager
The prompt name ('python' or 'ipython') or a custom PromptManager
class.
"""
if prompt is None:
prompt = 'python'
if prompt == 'python'... | python | {
"resource": ""
} |
q2521 | BasePromptManager.split_input_output | train | def split_input_output(self, text):
"""Split code into input lines and output lines, according to the
input and output prompt templates."""
lines = _to_lines(text)
i = 0
for line in lines:
if _starts_with_regex(line, self.input_prompt_regex):
i += 1
... | python | {
"resource": ""
} |
q2522 | _split_python | train | def _split_python(python):
"""Split Python source into chunks.
Chunks are separated by at least two return lines. The break must not
be followed by a space. Also, long Python strings spanning several lines
are not splitted.
"""
python = _preprocess(python)
if not python:
return []
... | python | {
"resource": ""
} |
q2523 | _is_chunk_markdown | train | def _is_chunk_markdown(source):
"""Return whether a chunk contains Markdown contents."""
lines = source.splitlines()
if all(line.startswith('# ') for line in lines):
# The chunk is a Markdown *unless* it is commented Python code.
source = '\n'.join(line[2:] for line in lines
... | python | {
"resource": ""
} |
q2524 | _filter_markdown | train | def _filter_markdown(source, filters):
"""Only keep some Markdown headers from a Markdown string."""
lines = source.splitlines()
# Filters is a list of 'hN' strings where 1 <= N <= 6.
headers = [_replace_header_filter(filter) for filter in filters]
lines = [line for line in lines if line.startswith(... | python | {
"resource": ""
} |
q2525 | BlockLexer.parse_lheading | train | def parse_lheading(self, m):
"""Parse setext heading."""
level = 1 if m.group(2) == '=' else 2
self.renderer.heading(m.group(1), level=level) | python | {
"resource": ""
} |
q2526 | MarkdownWriter.ensure_newline | train | def ensure_newline(self, n):
"""Make sure there are 'n' line breaks at the end."""
assert n >= 0
text = self._output.getvalue().rstrip('\n')
if not text:
return
self._output = StringIO()
self._output.write(text)
self._output.write('\n' * n)
tex... | python | {
"resource": ""
} |
q2527 | BaseMarkdownReader._meta_from_regex | train | def _meta_from_regex(self, m):
"""Extract and parse YAML metadata from a meta match
Notebook metadata must appear at the beginning of the file and follows
the Jekyll front-matter convention of dashed delimiters:
---
some: yaml
---
Cell metadata foll... | python | {
"resource": ""
} |
q2528 | MarkdownReader._code_cell | train | def _code_cell(self, source):
"""Split the source into input and output."""
input, output = self._prompt.to_cell(source)
return {'cell_type': 'code',
'input': input,
'output': output} | python | {
"resource": ""
} |
q2529 | _preprocess | train | def _preprocess(text, tab=4):
"""Normalize a text."""
text = re.sub(r'\r\n|\r', '\n', text)
text = text.replace('\t', ' ' * tab)
text = text.replace('\u00a0', ' ')
text = text.replace('\u2424', '\n')
pattern = re.compile(r'^ +$', re.M)
text = pattern.sub('', text)
text = _rstrip_lines(te... | python | {
"resource": ""
} |
q2530 | _diff | train | def _diff(text_0, text_1):
"""Return a diff between two strings."""
diff = difflib.ndiff(text_0.splitlines(), text_1.splitlines())
return _diff_removed_lines(diff) | python | {
"resource": ""
} |
q2531 | _write_json | train | def _write_json(file, contents):
"""Write a dict to a JSON file."""
with open(file, 'w') as f:
return json.dump(contents, f, indent=2, sort_keys=True) | python | {
"resource": ""
} |
q2532 | _numbered_style | train | def _numbered_style():
"""Create a numbered list style."""
style = ListStyle(name='_numbered_list')
lls = ListLevelStyleNumber(level=1)
lls.setAttribute('displaylevels', 1)
lls.setAttribute('numsuffix', '. ')
lls.setAttribute('numformat', '1')
llp = ListLevelProperties()
llp.setAttri... | python | {
"resource": ""
} |
q2533 | _create_style | train | def _create_style(name, family=None, **kwargs):
"""Helper function for creating a new style."""
if family == 'paragraph' and 'marginbottom' not in kwargs:
kwargs['marginbottom'] = '.5cm'
style = Style(name=name, family=family)
# Extract paragraph properties.
kwargs_par = {}
keys = sorted... | python | {
"resource": ""
} |
q2534 | default_styles | train | def default_styles():
"""Generate default ODF styles."""
styles = {}
def _add_style(name, **kwargs):
styles[name] = _create_style(name, **kwargs)
_add_style('heading-1',
family='paragraph',
fontsize='24pt',
fontweight='bold',
)
_... | python | {
"resource": ""
} |
q2535 | load_styles | train | def load_styles(path_or_doc):
"""Return a dictionary of all styles contained in an ODF document."""
if isinstance(path_or_doc, string_types):
doc = load(path_or_doc)
else:
# Recover the OpenDocumentText instance.
if isinstance(path_or_doc, ODFDocument):
doc = path_or_doc.... | python | {
"resource": ""
} |
q2536 | _item_type | train | def _item_type(item):
"""Indicate to the ODF reader the type of the block or text."""
tag = item['tag']
style = item.get('style', None)
if tag == 'p':
if style is None or 'paragraph' in style:
return 'paragraph'
else:
return style
elif tag == 'span':
i... | python | {
"resource": ""
} |
q2537 | ODFDocument.add_styles | train | def add_styles(self, **styles):
"""Add ODF styles to the current document."""
for stylename in sorted(styles):
self._doc.styles.addElement(styles[stylename]) | python | {
"resource": ""
} |
q2538 | ODFDocument._add_element | train | def _add_element(self, cls, **kwargs):
"""Add an element."""
# Convert stylename strings to actual style elements.
kwargs = self._replace_stylename(kwargs)
el = cls(**kwargs)
self._doc.text.addElement(el) | python | {
"resource": ""
} |
q2539 | ODFDocument._style_name | train | def _style_name(self, el):
"""Return the style name of an element."""
if el.attributes is None:
return None
style_field = ('urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'style-name')
name = el.attributes.get(style_field, None)
if not name:
... | python | {
"resource": ""
} |
q2540 | ODFDocument.start_container | train | def start_container(self, cls, **kwargs):
"""Append a new container."""
# Convert stylename strings to actual style elements.
kwargs = self._replace_stylename(kwargs)
# Create the container.
container = cls(**kwargs)
self._containers.append(container) | python | {
"resource": ""
} |
q2541 | ODFDocument.end_container | train | def end_container(self, cancel=None):
"""Finishes and registers the currently-active container, unless
'cancel' is True."""
if not self._containers:
return
container = self._containers.pop()
if len(self._containers) >= 1:
parent = self._containers[-1]
... | python | {
"resource": ""
} |
q2542 | ODFDocument.container | train | def container(self, cls, **kwargs):
"""Container context manager."""
self.start_container(cls, **kwargs)
yield
self.end_container() | python | {
"resource": ""
} |
q2543 | ODFDocument.start_paragraph | train | def start_paragraph(self, stylename=None):
"""Start a new paragraph."""
# Use the next paragraph style if one was set.
if stylename is None:
stylename = self._next_p_style or 'normal-paragraph'
self.start_container(P, stylename=stylename) | python | {
"resource": ""
} |
q2544 | ODFDocument.require_paragraph | train | def require_paragraph(self):
"""Create a new paragraph unless the currently-active container
is already a paragraph."""
if self._containers and _is_paragraph(self._containers[-1]):
return False
else:
self.start_paragraph()
return True | python | {
"resource": ""
} |
q2545 | ODFDocument._code_line | train | def _code_line(self, line):
"""Add a code line."""
assert self._containers
container = self._containers[-1]
# Handle extra spaces.
text = line
while text:
if text.startswith(' '):
r = re.match(r'(^ +)', text)
n = len(r.group(1)... | python | {
"resource": ""
} |
q2546 | ODFDocument.code | train | def code(self, text, lang=None):
"""Add a code block."""
# WARNING: lang is discarded currently.
with self.paragraph(stylename='code'):
lines = text.splitlines()
for line in lines[:-1]:
self._code_line(line)
self.linebreak()
sel... | python | {
"resource": ""
} |
q2547 | ODFDocument.start_numbered_list | train | def start_numbered_list(self):
"""Start a numbered list."""
self._ordered = True
self.start_container(List, stylename='_numbered_list')
self.set_next_paragraph_style('numbered-list-paragraph'
if self._item_level <= 0
... | python | {
"resource": ""
} |
q2548 | ODFDocument.start_list | train | def start_list(self):
"""Start a list."""
self._ordered = False
self.start_container(List)
self.set_next_paragraph_style('list-paragraph'
if self._item_level <= 0
else 'sublist-paragraph') | python | {
"resource": ""
} |
q2549 | ODFDocument.text | train | def text(self, text, stylename=None):
"""Add text within the current container."""
assert self._containers
container = self._containers[-1]
if stylename is not None:
stylename = self._get_style_name(stylename)
container.addElement(Span(stylename=stylename, text=te... | python | {
"resource": ""
} |
q2550 | _cell_output | train | def _cell_output(cell):
"""Return the output of an ipynb cell."""
outputs = cell.get('outputs', [])
# Add stdout.
stdout = ('\n'.join(_ensure_string(output.get('text', ''))
for output in outputs)).rstrip()
# Add text output.
text_outputs = []
for output in outputs:
... | python | {
"resource": ""
} |
q2551 | FireTV._dump | train | def _dump(self, service, grep=None):
"""Perform a service dump.
:param service: Service to dump.
:param grep: Grep for this string.
:returns: Dump, optionally grepped.
"""
if grep:
return self.adb_shell('dumpsys {0} | grep "{1}"'.format(service, grep))
... | python | {
"resource": ""
} |
q2552 | FireTV._dump_has | train | def _dump_has(self, service, grep, search):
"""Check if a dump has particular content.
:param service: Service to dump.
:param grep: Grep for this string.
:param search: Check for this substring.
:returns: Found or not.
"""
dump_grep = self._dump(service, grep=gr... | python | {
"resource": ""
} |
q2553 | FireTV._ps | train | def _ps(self, search=''):
"""Perform a ps command with optional filtering.
:param search: Check for this substring.
:returns: List of matching fields
"""
if not self.available:
return
result = []
ps = self.adb_streaming_shell('ps')
try:
... | python | {
"resource": ""
} |
q2554 | FireTV.connect | train | def connect(self, always_log_errors=True):
"""Connect to an Amazon Fire TV device.
Will attempt to establish ADB connection to the given host.
Failure sets state to UNKNOWN and disables sending actions.
:returns: True if successful, False otherwise
"""
self._adb_lock.ac... | python | {
"resource": ""
} |
q2555 | FireTV.update | train | def update(self, get_running_apps=True):
"""Get the state of the device, the current app, and the running apps.
:param get_running_apps: whether or not to get the ``running_apps`` property
:return state: the state of the device
:return current_app: the current app
:return runnin... | python | {
"resource": ""
} |
q2556 | FireTV.app_state | train | def app_state(self, app):
"""Informs if application is running."""
if not self.available or not self.screen_on:
return STATE_OFF
if self.current_app["package"] == app:
return STATE_ON
return STATE_OFF | python | {
"resource": ""
} |
q2557 | FireTV.state | train | def state(self):
"""Compute and return the device state.
:returns: Device state.
"""
# Check if device is disconnected.
if not self.available:
return STATE_UNKNOWN
# Check if device is off.
if not self.screen_on:
return STATE_OFF
#... | python | {
"resource": ""
} |
q2558 | FireTV.available | train | def available(self):
"""Check whether the ADB connection is intact."""
if not self.adb_server_ip:
# python-adb
return bool(self._adb)
# pure-python-adb
try:
# make sure the server is available
adb_devices = self._adb_client.devices()
... | python | {
"resource": ""
} |
q2559 | FireTV.running_apps | train | def running_apps(self):
"""Return a list of running user applications."""
ps = self.adb_shell(RUNNING_APPS_CMD)
if ps:
return [line.strip().rsplit(' ', 1)[-1] for line in ps.splitlines() if line.strip()]
return [] | python | {
"resource": ""
} |
q2560 | FireTV.current_app | train | def current_app(self):
"""Return the current app."""
current_focus = self.adb_shell(CURRENT_APP_CMD)
if current_focus is None:
return None
current_focus = current_focus.replace("\r", "")
matches = WINDOW_REGEX.search(current_focus)
# case 1: current app was ... | python | {
"resource": ""
} |
q2561 | FireTV.wake_lock_size | train | def wake_lock_size(self):
"""Get the size of the current wake lock."""
output = self.adb_shell(WAKE_LOCK_SIZE_CMD)
if not output:
return None
return int(output.split("=")[1].strip()) | python | {
"resource": ""
} |
q2562 | FireTV.get_properties | train | def get_properties(self, get_running_apps=True, lazy=False):
"""Get the ``screen_on``, ``awake``, ``wake_lock_size``, ``current_app``, and ``running_apps`` properties."""
if get_running_apps:
output = self.adb_shell(SCREEN_ON_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
... | python | {
"resource": ""
} |
q2563 | is_valid_device_id | train | def is_valid_device_id(device_id):
""" Check if device identifier is valid.
A valid device identifier contains only ascii word characters or dashes.
:param device_id: Device identifier
:returns: Valid or not.
"""
valid = valid_device_id.match(device_id)
if not valid:
logging.error(... | python | {
"resource": ""
} |
q2564 | add | train | def add(device_id, host, adbkey='', adb_server_ip='', adb_server_port=5037):
""" Add a device.
Creates FireTV instance associated with device identifier.
:param device_id: Device identifier.
:param host: Host in <address>:<port> format.
:param adbkey: The path to the "adbkey" file
:param adb_s... | python | {
"resource": ""
} |
q2565 | add_device | train | def add_device():
""" Add a device via HTTP POST.
POST JSON in the following format ::
{
"device_id": "<your_device_id>",
"host": "<address>:<port>",
"adbkey": "<path to the adbkey file>"
}
"""
req = request.get_json()
success = False
if 'de... | python | {
"resource": ""
} |
q2566 | list_devices | train | def list_devices():
""" List devices via HTTP GET. """
output = {}
for device_id, device in devices.items():
output[device_id] = {
'host': device.host,
'state': device.state
}
return jsonify(devices=output) | python | {
"resource": ""
} |
q2567 | device_state | train | def device_state(device_id):
""" Get device state via HTTP GET. """
if device_id not in devices:
return jsonify(success=False)
return jsonify(state=devices[device_id].state) | python | {
"resource": ""
} |
q2568 | current_app | train | def current_app(device_id):
""" Get currently running app. """
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
current = devices[device_id].current_app
if current is None:
abort(404)
return jsonify(current_app=current) | python | {
"resource": ""
} |
q2569 | running_apps | train | def running_apps(device_id):
""" Get running apps via HTTP GET. """
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
return jsonify(running_apps=devices[device_id].running_apps) | python | {
"resource": ""
} |
q2570 | get_app_state | train | def get_app_state(device_id, app_id):
""" Get the state of the requested app """
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
app_state = devices[device_id].app_state(app_id)
return jso... | python | {
"resource": ""
} |
q2571 | device_action | train | def device_action(device_id, action_id):
""" Initiate device action via HTTP GET. """
success = False
if device_id in devices:
input_cmd = getattr(devices[device_id], action_id, None)
if callable(input_cmd):
input_cmd()
success = True
return jsonify(success=succes... | python | {
"resource": ""
} |
q2572 | app_start | train | def app_start(device_id, app_id):
""" Starts an app with corresponding package name"""
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
success = devices[device_id].launch_app(app_id)
retu... | python | {
"resource": ""
} |
q2573 | app_stop | train | def app_stop(device_id, app_id):
""" stops an app with corresponding package name"""
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
success = devices[device_id].stop_app(app_id)
return j... | python | {
"resource": ""
} |
q2574 | device_connect | train | def device_connect(device_id):
""" Force a connection attempt via HTTP GET. """
success = False
if device_id in devices:
devices[device_id].connect()
success = True
return jsonify(success=success) | python | {
"resource": ""
} |
q2575 | _parse_config | train | def _parse_config(config_file_path):
""" Parse Config File from yaml file. """
config_file = open(config_file_path, 'r')
config = yaml.load(config_file)
config_file.close()
return config | python | {
"resource": ""
} |
q2576 | _add_devices_from_config | train | def _add_devices_from_config(args):
""" Add devices from config. """
config = _parse_config(args.config)
for device in config['devices']:
if args.default:
if device == "default":
raise ValueError('devicename "default" in config is not allowed if default param is set')
... | python | {
"resource": ""
} |
q2577 | main | train | def main():
""" Set up the server. """
parser = argparse.ArgumentParser(description='AFTV Server')
parser.add_argument('-p', '--port', type=int, help='listen port', default=5556)
parser.add_argument('-d', '--default', help='default Amazon Fire TV host', nargs='?')
parser.add_argument('-c', '--config... | python | {
"resource": ""
} |
q2578 | ProfanityFilter._load_words | train | def _load_words(self):
"""Loads the list of profane words from file."""
with open(self._words_file, 'r') as f:
self._censor_list = [line.strip() for line in f.readlines()] | python | {
"resource": ""
} |
q2579 | ProfanityFilter.get_profane_words | train | def get_profane_words(self):
"""Returns all profane words currently in use."""
profane_words = []
if self._custom_censor_list:
profane_words = [w for w in self._custom_censor_list] # Previous versions of Python don't have list.copy()
else:
profane_words = [w for... | python | {
"resource": ""
} |
q2580 | ProfanityFilter.censor | train | def censor(self, input_text):
"""Returns input_text with any profane words censored."""
bad_words = self.get_profane_words()
res = input_text
for word in bad_words:
# Apply word boundaries to the bad word
regex_string = r'{0}' if self._no_word_boundaries else r'\... | python | {
"resource": ""
} |
q2581 | SMB2NetworkInterfaceInfo.unpack_multiple | train | def unpack_multiple(data):
"""
Get's a list of SMB2NetworkInterfaceInfo messages from the byte value
passed in. This is the raw buffer value that is set on the
SMB2IOCTLResponse message.
:param data: bytes of the messages
:return: List of SMB2NetworkInterfaceInfo message... | python | {
"resource": ""
} |
q2582 | CreateContextName.get_response_structure | train | def get_response_structure(name):
"""
Returns the response structure for a know list of create context
responses.
:param name: The constant value above
:return: The response structure or None if unknown
"""
return {
CreateContextName.SMB2_CREATE_DURAB... | python | {
"resource": ""
} |
q2583 | SMB2CreateContextRequest.get_context_data | train | def get_context_data(self):
"""
Get the buffer_data value of a context response and try to convert it
to the relevant structure based on the buffer_name used. If it is an
unknown structure then the raw bytes are returned.
:return: relevant Structure of buffer_data or bytes if un... | python | {
"resource": ""
} |
q2584 | SMB2CreateEABuffer.pack_multiple | train | def pack_multiple(messages):
"""
Converts a list of SMB2CreateEABuffer structures and packs them as a
bytes object used when setting to the SMB2CreateContextRequest
buffer_data field. This should be used as it would calculate the
correct next_entry_offset field value for each buf... | python | {
"resource": ""
} |
q2585 | TreeConnect.connect | train | def connect(self, require_secure_negotiate=True):
"""
Connect to the share.
:param require_secure_negotiate: For Dialects 3.0 and 3.0.2, will
verify the negotiation parameters with the server to prevent
SMB downgrade attacks
"""
log.info("Session: %s - Cr... | python | {
"resource": ""
} |
q2586 | TreeConnect.disconnect | train | def disconnect(self):
"""
Disconnects the tree connection.
"""
if not self._connected:
return
log.info("Session: %s, Tree: %s - Disconnecting from Tree Connect"
% (self.session.username, self.share_name))
req = SMB2TreeDisconnect()
l... | python | {
"resource": ""
} |
q2587 | Connection.disconnect | train | def disconnect(self, close=True):
"""
Closes the connection as well as logs off any of the
Disconnects the TCP connection and shuts down the socket listener
running in a thread.
:param close: Will close all sessions in the connection as well as the
tree connections o... | python | {
"resource": ""
} |
q2588 | Connection.send | train | def send(self, message, sid=None, tid=None, credit_request=None):
"""
Will send a message to the server that is passed in. The final
unencrypted header is returned to the function that called this.
:param message: An SMB message structure to send
:param sid: A session_id that th... | python | {
"resource": ""
} |
q2589 | Connection.send_compound | train | def send_compound(self, messages, sid, tid, related=False):
"""
Sends multiple messages within 1 TCP request, will fail if the size
of the total length exceeds the maximum of the transport max.
:param messages: A list of messages to send to the server
:param sid: The session_id ... | python | {
"resource": ""
} |
q2590 | Connection.receive | train | def receive(self, request, wait=True, timeout=None):
"""
Polls the message buffer of the TCP connection and waits until a valid
message is received based on the message_id passed in.
:param request: The Request object to wait get the response for
:param wait: Wait for the final ... | python | {
"resource": ""
} |
q2591 | Connection.echo | train | def echo(self, sid=0, timeout=60, credit_request=1):
"""
Sends an SMB2 Echo request to the server. This can be used to request
more credits from the server with the credit_request param.
On a Samba server, the sid can be 0 but for a Windows SMB Server, the
sid of an authenticate... | python | {
"resource": ""
} |
q2592 | Connection._flush_message_buffer | train | def _flush_message_buffer(self):
"""
Loops through the transport message_buffer until there are no messages
left in the queue. Each response is assigned to the Request object
based on the message_id which are then available in
self.outstanding_requests
"""
while T... | python | {
"resource": ""
} |
q2593 | Connection._calculate_credit_charge | train | def _calculate_credit_charge(self, message):
"""
Calculates the credit charge for a request based on the command. If
connection.supports_multi_credit is not True then the credit charge
isn't valid so it returns 0.
The credit charge is the number of credits that are required for
... | python | {
"resource": ""
} |
q2594 | Session.disconnect | train | def disconnect(self, close=True):
"""
Logs off the session
:param close: Will close all tree connects in a session
"""
if not self._connected:
# already disconnected so let's return
return
if close:
for open in list(self.open_table.va... | python | {
"resource": ""
} |
q2595 | Field.pack | train | def pack(self):
"""
Packs the field value into a byte string so it can be sent to the
server.
:param structure: The message structure class object
:return: A byte string of the packed field's value
"""
value = self._get_calculated_value(self.value)
packed... | python | {
"resource": ""
} |
q2596 | Field.set_value | train | def set_value(self, value):
"""
Parses, and sets the value attribute for the field.
:param value: The value to be parsed and set, the allowed input types
vary depending on the Field used
"""
parsed_value = self._parse_value(value)
self.value = parsed_value | python | {
"resource": ""
} |
q2597 | Field.unpack | train | def unpack(self, data):
"""
Takes in a byte string and set's the field value based on field
definition.
:param structure: The message structure class object
:param data: The byte string of the data to unpack
:return: The remaining data for subsequent fields
"""
... | python | {
"resource": ""
} |
q2598 | Field._get_calculated_value | train | def _get_calculated_value(self, value):
"""
Get's the final value of the field and runs the lambda functions
recursively until a final value is derived.
:param value: The value to calculate/expand
:return: The final value
"""
if isinstance(value, types.LambdaType... | python | {
"resource": ""
} |
q2599 | Field._get_struct_format | train | def _get_struct_format(self, size):
"""
Get's the format specified for use in struct. This is only designed
for 1, 2, 4, or 8 byte values and will throw an exception if it is
anything else.
:param size: The size as an int
:return: The struct format specifier for the size... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.