repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
rossant/ipymd
ipymd/core/format_manager.py
FormatManager.create_writer
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
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)
[ "def", "create_writer", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_format", "(", "name", ")", "return", "self", ".", "_formats", "[", "name", "]", "[", "'writer'", "]", "(", "*", "args", ",",...
Create a new writer instance for a given format.
[ "Create", "a", "new", "writer", "instance", "for", "a", "given", "format", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L208-L211
rossant/ipymd
ipymd/core/format_manager.py
FormatManager.convert
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
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...
[ "def", "convert", "(", "self", ",", "contents_or_path", ",", "from_", "=", "None", ",", "to", "=", "None", ",", "reader", "=", "None", ",", "writer", "=", "None", ",", "from_kwargs", "=", "None", ",", "to_kwargs", "=", "None", ",", ")", ":", "# Load ...
Convert contents between supported formats. Parameters ---------- contents : str The contents to convert from. from_ : str or None The name of the source format. If None, this is the ipymd_cells format. to : str or None The name o...
[ "Convert", "contents", "between", "supported", "formats", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L213-L299
rossant/ipymd
ipymd/core/format_manager.py
FormatManager.clean_meta
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
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_...
[ "def", "clean_meta", "(", "self", ",", "meta", ")", ":", "if", "not", "self", ".", "verbose_metadata", ":", "default_kernel_name", "=", "(", "self", ".", "default_kernel_name", "or", "self", ".", "_km", ".", "kernel_name", ")", "if", "(", "meta", ".", "g...
Removes unwanted metadata Parameters ---------- meta : dict Notebook metadata.
[ "Removes", "unwanted", "metadata" ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L301-L319
rossant/ipymd
ipymd/core/format_manager.py
FormatManager.clean_cell_meta
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
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
[ "def", "clean_cell_meta", "(", "self", ",", "meta", ")", ":", "for", "k", ",", "v", "in", "DEFAULT_CELL_METADATA", ".", "items", "(", ")", ":", "if", "meta", ".", "get", "(", "k", ",", "None", ")", "==", "v", ":", "meta", ".", "pop", "(", "k", ...
Remove cell metadata that matches the default cell metadata.
[ "Remove", "cell", "metadata", "that", "matches", "the", "default", "cell", "metadata", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L321-L326
rossant/ipymd
ipymd/core/prompt.py
_starts_with_regex
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
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)
[ "def", "_starts_with_regex", "(", "line", ",", "regex", ")", ":", "if", "not", "regex", ".", "startswith", "(", "'^'", ")", ":", "regex", "=", "'^'", "+", "regex", "reg", "=", "re", ".", "compile", "(", "regex", ")", "return", "reg", ".", "match", ...
Return whether a line starts with a regex or not.
[ "Return", "whether", "a", "line", "starts", "with", "a", "regex", "or", "not", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/prompt.py#L37-L42
rossant/ipymd
ipymd/core/prompt.py
create_prompt
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
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'...
[ "def", "create_prompt", "(", "prompt", ")", ":", "if", "prompt", "is", "None", ":", "prompt", "=", "'python'", "if", "prompt", "==", "'python'", ":", "prompt", "=", "PythonPromptManager", "elif", "prompt", "==", "'ipython'", ":", "prompt", "=", "IPythonPromp...
Create a prompt manager. Parameters ---------- prompt : str or class driving from BasePromptManager The prompt name ('python' or 'ipython') or a custom PromptManager class.
[ "Create", "a", "prompt", "manager", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/prompt.py#L231-L252
rossant/ipymd
ipymd/core/prompt.py
BasePromptManager.split_input_output
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
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 ...
[ "def", "split_input_output", "(", "self", ",", "text", ")", ":", "lines", "=", "_to_lines", "(", "text", ")", "i", "=", "0", "for", "line", "in", "lines", ":", "if", "_starts_with_regex", "(", "line", ",", "self", ".", "input_prompt_regex", ")", ":", "...
Split code into input lines and output lines, according to the input and output prompt templates.
[ "Split", "code", "into", "input", "lines", "and", "output", "lines", "according", "to", "the", "input", "and", "output", "prompt", "templates", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/prompt.py#L87-L97
rossant/ipymd
ipymd/core/contents_manager.py
IPymdContentsManager.get
def get(self, path, content=True, type=None, format=None): """ Takes a path for an entity and returns its model Parameters ---------- path : str the API path that describes the relative path for the target content : bool Whether to include the contents in ...
python
def get(self, path, content=True, type=None, format=None): """ Takes a path for an entity and returns its model Parameters ---------- path : str the API path that describes the relative path for the target content : bool Whether to include the contents in ...
[ "def", "get", "(", "self", ",", "path", ",", "content", "=", "True", ",", "type", "=", "None", ",", "format", "=", "None", ")", ":", "path", "=", "path", ".", "strip", "(", "'/'", ")", "# File extension of the chosen format.", "file_extension", "=", "for...
Takes a path for an entity and returns its model Parameters ---------- path : str the API path that describes the relative path for the target content : bool Whether to include the contents in the reply type : str, optional The requested type -...
[ "Takes", "a", "path", "for", "an", "entity", "and", "returns", "its", "model", "Parameters", "----------", "path", ":", "str", "the", "API", "path", "that", "describes", "the", "relative", "path", "for", "the", "target", "content", ":", "bool", "Whether", ...
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/contents_manager.py#L64-L107
rossant/ipymd
ipymd/core/contents_manager.py
IPymdContentsManager._read_notebook
def _read_notebook(self, os_path, as_version=4): """Read a notebook from an os path.""" with self.open(os_path, 'r', encoding='utf-8') as f: try: # NEW file_ext = _file_extension(os_path) if file_ext == '.ipynb': return nbf...
python
def _read_notebook(self, os_path, as_version=4): """Read a notebook from an os path.""" with self.open(os_path, 'r', encoding='utf-8') as f: try: # NEW file_ext = _file_extension(os_path) if file_ext == '.ipynb': return nbf...
[ "def", "_read_notebook", "(", "self", ",", "os_path", ",", "as_version", "=", "4", ")", ":", "with", "self", ".", "open", "(", "os_path", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "try", ":", "# NEW", "file_ext", "=", "_file_e...
Read a notebook from an os path.
[ "Read", "a", "notebook", "from", "an", "os", "path", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/contents_manager.py#L110-L126
rossant/ipymd
ipymd/core/contents_manager.py
IPymdContentsManager.save
def save(self, model, path=''): """Save the file model and return the model with no content.""" path = path.strip('/') if 'type' not in model: raise web.HTTPError(400, u'No file type provided') if 'content' not in model and model['type'] != 'directory': raise web...
python
def save(self, model, path=''): """Save the file model and return the model with no content.""" path = path.strip('/') if 'type' not in model: raise web.HTTPError(400, u'No file type provided') if 'content' not in model and model['type'] != 'directory': raise web...
[ "def", "save", "(", "self", ",", "model", ",", "path", "=", "''", ")", ":", "path", "=", "path", ".", "strip", "(", "'/'", ")", "if", "'type'", "not", "in", "model", ":", "raise", "web", ".", "HTTPError", "(", "400", ",", "u'No file type provided'", ...
Save the file model and return the model with no content.
[ "Save", "the", "file", "model", "and", "return", "the", "model", "with", "no", "content", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/contents_manager.py#L128-L193
rossant/ipymd
ipymd/formats/python.py
_split_python
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
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 [] ...
[ "def", "_split_python", "(", "python", ")", ":", "python", "=", "_preprocess", "(", "python", ")", "if", "not", "python", ":", "return", "[", "]", "lexer", "=", "PythonSplitLexer", "(", ")", "lexer", ".", "read", "(", "python", ")", "return", "lexer", ...
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.
[ "Split", "Python", "source", "into", "chunks", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/python.py#L86-L99
rossant/ipymd
ipymd/formats/python.py
_is_chunk_markdown
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
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 ...
[ "def", "_is_chunk_markdown", "(", "source", ")", ":", "lines", "=", "source", ".", "splitlines", "(", ")", "if", "all", "(", "line", ".", "startswith", "(", "'# '", ")", "for", "line", "in", "lines", ")", ":", "# The chunk is a Markdown *unless* it is commente...
Return whether a chunk contains Markdown contents.
[ "Return", "whether", "a", "chunk", "contains", "Markdown", "contents", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/python.py#L102-L114
rossant/ipymd
ipymd/formats/python.py
_add_hash
def _add_hash(source): """Add a leading hash '#' at the beginning of every line in the source.""" source = '\n'.join('# ' + line.rstrip() for line in source.splitlines()) return source
python
def _add_hash(source): """Add a leading hash '#' at the beginning of every line in the source.""" source = '\n'.join('# ' + line.rstrip() for line in source.splitlines()) return source
[ "def", "_add_hash", "(", "source", ")", ":", "source", "=", "'\\n'", ".", "join", "(", "'# '", "+", "line", ".", "rstrip", "(", ")", "for", "line", "in", "source", ".", "splitlines", "(", ")", ")", "return", "source" ]
Add a leading hash '#' at the beginning of every line in the source.
[ "Add", "a", "leading", "hash", "#", "at", "the", "beginning", "of", "every", "line", "in", "the", "source", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/python.py#L122-L126
rossant/ipymd
ipymd/lib/markdown.py
_filter_markdown
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
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(...
[ "def", "_filter_markdown", "(", "source", ",", "filters", ")", ":", "lines", "=", "source", ".", "splitlines", "(", ")", "# Filters is a list of 'hN' strings where 1 <= N <= 6.", "headers", "=", "[", "_replace_header_filter", "(", "filter", ")", "for", "filter", "in...
Only keep some Markdown headers from a Markdown string.
[ "Only", "keep", "some", "Markdown", "headers", "from", "a", "Markdown", "string", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/markdown.py#L647-L653
rossant/ipymd
ipymd/lib/markdown.py
BlockLexer.parse_lheading
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
def parse_lheading(self, m): """Parse setext heading.""" level = 1 if m.group(2) == '=' else 2 self.renderer.heading(m.group(1), level=level)
[ "def", "parse_lheading", "(", "self", ",", "m", ")", ":", "level", "=", "1", "if", "m", ".", "group", "(", "2", ")", "==", "'='", "else", "2", "self", ".", "renderer", ".", "heading", "(", "m", ".", "group", "(", "1", ")", ",", "level", "=", ...
Parse setext heading.
[ "Parse", "setext", "heading", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/markdown.py#L184-L187
rossant/ipymd
ipymd/lib/markdown.py
MarkdownWriter.ensure_newline
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
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...
[ "def", "ensure_newline", "(", "self", ",", "n", ")", ":", "assert", "n", ">=", "0", "text", "=", "self", ".", "_output", ".", "getvalue", "(", ")", ".", "rstrip", "(", "'\\n'", ")", "if", "not", "text", ":", "return", "self", ".", "_output", "=", ...
Make sure there are 'n' line breaks at the end.
[ "Make", "sure", "there", "are", "n", "line", "breaks", "at", "the", "end", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/markdown.py#L560-L571
rossant/ipymd
ipymd/formats/markdown.py
BaseMarkdownReader._meta_from_regex
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
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...
[ "def", "_meta_from_regex", "(", "self", ",", "m", ")", ":", "body", "=", "m", ".", "group", "(", "'body'", ")", "is_notebook", "=", "m", ".", "group", "(", "'sep_close'", ")", "==", "'---'", "if", "is_notebook", ":", "# make it into a valid YAML object by st...
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 follows the YAML spec of dashes and periods ...
[ "Extract", "and", "parse", "YAML", "metadata", "from", "a", "meta", "match" ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/markdown.py#L77-L107
rossant/ipymd
ipymd/formats/markdown.py
MarkdownReader._code_cell
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
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}
[ "def", "_code_cell", "(", "self", ",", "source", ")", ":", "input", ",", "output", "=", "self", ".", "_prompt", ".", "to_cell", "(", "source", ")", "return", "{", "'cell_type'", ":", "'code'", ",", "'input'", ":", "input", ",", "'output'", ":", "output...
Split the source into input and output.
[ "Split", "the", "source", "into", "input", "and", "output", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/markdown.py#L201-L206
rossant/ipymd
ipymd/utils/utils.py
_preprocess
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
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...
[ "def", "_preprocess", "(", "text", ",", "tab", "=", "4", ")", ":", "text", "=", "re", ".", "sub", "(", "r'\\r\\n|\\r'", ",", "'\\n'", ",", "text", ")", "text", "=", "text", ".", "replace", "(", "'\\t'", ",", "' '", "*", "tab", ")", "text", "=", ...
Normalize a text.
[ "Normalize", "a", "text", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/utils/utils.py#L37-L46
rossant/ipymd
ipymd/utils/utils.py
_diff
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
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)
[ "def", "_diff", "(", "text_0", ",", "text_1", ")", ":", "diff", "=", "difflib", ".", "ndiff", "(", "text_0", ".", "splitlines", "(", ")", ",", "text_1", ".", "splitlines", "(", ")", ")", "return", "_diff_removed_lines", "(", "diff", ")" ]
Return a diff between two strings.
[ "Return", "a", "diff", "between", "two", "strings", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/utils/utils.py#L95-L98
rossant/ipymd
ipymd/utils/utils.py
_write_json
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
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)
[ "def", "_write_json", "(", "file", ",", "contents", ")", ":", "with", "open", "(", "file", ",", "'w'", ")", "as", "f", ":", "return", "json", ".", "dump", "(", "contents", ",", "f", ",", "indent", "=", "2", ",", "sort_keys", "=", "True", ")" ]
Write a dict to a JSON file.
[ "Write", "a", "dict", "to", "a", "JSON", "file", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/utils/utils.py#L118-L121
rossant/ipymd
ipymd/lib/opendocument.py
_numbered_style
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
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...
[ "def", "_numbered_style", "(", ")", ":", "style", "=", "ListStyle", "(", "name", "=", "'_numbered_list'", ")", "lls", "=", "ListLevelStyleNumber", "(", "level", "=", "1", ")", "lls", ".", "setAttribute", "(", "'displaylevels'", ",", "1", ")", "lls", ".", ...
Create a numbered list style.
[ "Create", "a", "numbered", "list", "style", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L119-L146
rossant/ipymd
ipymd/lib/opendocument.py
_create_style
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
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...
[ "def", "_create_style", "(", "name", ",", "family", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "family", "==", "'paragraph'", "and", "'marginbottom'", "not", "in", "kwargs", ":", "kwargs", "[", "'marginbottom'", "]", "=", "'.5cm'", "style", "=...
Helper function for creating a new style.
[ "Helper", "function", "for", "creating", "a", "new", "style", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L149-L163
rossant/ipymd
ipymd/lib/opendocument.py
default_styles
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
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', ) _...
[ "def", "default_styles", "(", ")", ":", "styles", "=", "{", "}", "def", "_add_style", "(", "name", ",", "*", "*", "kwargs", ")", ":", "styles", "[", "name", "]", "=", "_create_style", "(", "name", ",", "*", "*", "kwargs", ")", "_add_style", "(", "'...
Generate default ODF styles.
[ "Generate", "default", "ODF", "styles", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L166-L267
rossant/ipymd
ipymd/lib/opendocument.py
load_styles
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
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....
[ "def", "load_styles", "(", "path_or_doc", ")", ":", "if", "isinstance", "(", "path_or_doc", ",", "string_types", ")", ":", "doc", "=", "load", "(", "path_or_doc", ")", "else", ":", "# Recover the OpenDocumentText instance.", "if", "isinstance", "(", "path_or_doc",...
Return a dictionary of all styles contained in an ODF document.
[ "Return", "a", "dictionary", "of", "all", "styles", "contained", "in", "an", "ODF", "document", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L278-L290
rossant/ipymd
ipymd/lib/opendocument.py
_item_type
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
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...
[ "def", "_item_type", "(", "item", ")", ":", "tag", "=", "item", "[", "'tag'", "]", "style", "=", "item", ".", "get", "(", "'style'", ",", "None", ")", "if", "tag", "==", "'p'", ":", "if", "style", "is", "None", "or", "'paragraph'", "in", "style", ...
Indicate to the ODF reader the type of the block or text.
[ "Indicate", "to", "the", "ODF", "reader", "the", "type", "of", "the", "block", "or", "text", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L742-L769
rossant/ipymd
ipymd/lib/opendocument.py
ODFDocument.add_styles
def add_styles(self, **styles): """Add ODF styles to the current document.""" for stylename in sorted(styles): self._doc.styles.addElement(styles[stylename])
python
def add_styles(self, **styles): """Add ODF styles to the current document.""" for stylename in sorted(styles): self._doc.styles.addElement(styles[stylename])
[ "def", "add_styles", "(", "self", ",", "*", "*", "styles", ")", ":", "for", "stylename", "in", "sorted", "(", "styles", ")", ":", "self", ".", "_doc", ".", "styles", ".", "addElement", "(", "styles", "[", "stylename", "]", ")" ]
Add ODF styles to the current document.
[ "Add", "ODF", "styles", "to", "the", "current", "document", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L358-L361
rossant/ipymd
ipymd/lib/opendocument.py
ODFDocument._add_element
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
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)
[ "def", "_add_element", "(", "self", ",", "cls", ",", "*", "*", "kwargs", ")", ":", "# Convert stylename strings to actual style elements.", "kwargs", "=", "self", ".", "_replace_stylename", "(", "kwargs", ")", "el", "=", "cls", "(", "*", "*", "kwargs", ")", ...
Add an element.
[ "Add", "an", "element", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L421-L426
rossant/ipymd
ipymd/lib/opendocument.py
ODFDocument._style_name
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
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: ...
[ "def", "_style_name", "(", "self", ",", "el", ")", ":", "if", "el", ".", "attributes", "is", "None", ":", "return", "None", "style_field", "=", "(", "'urn:oasis:names:tc:opendocument:xmlns:text:1.0'", ",", "'style-name'", ")", "name", "=", "el", ".", "attribut...
Return the style name of an element.
[ "Return", "the", "style", "name", "of", "an", "element", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L428-L437
rossant/ipymd
ipymd/lib/opendocument.py
ODFDocument.start_container
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
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)
[ "def", "start_container", "(", "self", ",", "cls", ",", "*", "*", "kwargs", ")", ":", "# Convert stylename strings to actual style elements.", "kwargs", "=", "self", ".", "_replace_stylename", "(", "kwargs", ")", "# Create the container.", "container", "=", "cls", "...
Append a new container.
[ "Append", "a", "new", "container", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L449-L455
rossant/ipymd
ipymd/lib/opendocument.py
ODFDocument.end_container
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
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] ...
[ "def", "end_container", "(", "self", ",", "cancel", "=", "None", ")", ":", "if", "not", "self", ".", "_containers", ":", "return", "container", "=", "self", ".", "_containers", ".", "pop", "(", ")", "if", "len", "(", "self", ".", "_containers", ")", ...
Finishes and registers the currently-active container, unless 'cancel' is True.
[ "Finishes", "and", "registers", "the", "currently", "-", "active", "container", "unless", "cancel", "is", "True", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L457-L468
rossant/ipymd
ipymd/lib/opendocument.py
ODFDocument.container
def container(self, cls, **kwargs): """Container context manager.""" self.start_container(cls, **kwargs) yield self.end_container()
python
def container(self, cls, **kwargs): """Container context manager.""" self.start_container(cls, **kwargs) yield self.end_container()
[ "def", "container", "(", "self", ",", "cls", ",", "*", "*", "kwargs", ")", ":", "self", ".", "start_container", "(", "cls", ",", "*", "*", "kwargs", ")", "yield", "self", ".", "end_container", "(", ")" ]
Container context manager.
[ "Container", "context", "manager", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L471-L475
rossant/ipymd
ipymd/lib/opendocument.py
ODFDocument.start_paragraph
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
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)
[ "def", "start_paragraph", "(", "self", ",", "stylename", "=", "None", ")", ":", "# Use the next paragraph style if one was set.", "if", "stylename", "is", "None", ":", "stylename", "=", "self", ".", "_next_p_style", "or", "'normal-paragraph'", "self", ".", "start_co...
Start a new paragraph.
[ "Start", "a", "new", "paragraph", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L477-L482
rossant/ipymd
ipymd/lib/opendocument.py
ODFDocument.require_paragraph
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
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
[ "def", "require_paragraph", "(", "self", ")", ":", "if", "self", ".", "_containers", "and", "_is_paragraph", "(", "self", ".", "_containers", "[", "-", "1", "]", ")", ":", "return", "False", "else", ":", "self", ".", "start_paragraph", "(", ")", "return"...
Create a new paragraph unless the currently-active container is already a paragraph.
[ "Create", "a", "new", "paragraph", "unless", "the", "currently", "-", "active", "container", "is", "already", "a", "paragraph", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L491-L498
rossant/ipymd
ipymd/lib/opendocument.py
ODFDocument._code_line
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
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)...
[ "def", "_code_line", "(", "self", ",", "line", ")", ":", "assert", "self", ".", "_containers", "container", "=", "self", ".", "_containers", "[", "-", "1", "]", "# Handle extra spaces.", "text", "=", "line", "while", "text", ":", "if", "text", ".", "star...
Add a code line.
[ "Add", "a", "code", "line", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L507-L526
rossant/ipymd
ipymd/lib/opendocument.py
ODFDocument.code
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
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...
[ "def", "code", "(", "self", ",", "text", ",", "lang", "=", "None", ")", ":", "# WARNING: lang is discarded currently.", "with", "self", ".", "paragraph", "(", "stylename", "=", "'code'", ")", ":", "lines", "=", "text", ".", "splitlines", "(", ")", "for", ...
Add a code block.
[ "Add", "a", "code", "block", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L528-L536
rossant/ipymd
ipymd/lib/opendocument.py
ODFDocument.start_numbered_list
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
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 ...
[ "def", "start_numbered_list", "(", "self", ")", ":", "self", ".", "_ordered", "=", "True", "self", ".", "start_container", "(", "List", ",", "stylename", "=", "'_numbered_list'", ")", "self", ".", "set_next_paragraph_style", "(", "'numbered-list-paragraph'", "if",...
Start a numbered list.
[ "Start", "a", "numbered", "list", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L558-L564
rossant/ipymd
ipymd/lib/opendocument.py
ODFDocument.start_list
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
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')
[ "def", "start_list", "(", "self", ")", ":", "self", ".", "_ordered", "=", "False", "self", ".", "start_container", "(", "List", ")", "self", ".", "set_next_paragraph_style", "(", "'list-paragraph'", "if", "self", ".", "_item_level", "<=", "0", "else", "'subl...
Start a list.
[ "Start", "a", "list", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L572-L578
rossant/ipymd
ipymd/lib/opendocument.py
ODFDocument.text
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
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...
[ "def", "text", "(", "self", ",", "text", ",", "stylename", "=", "None", ")", ":", "assert", "self", ".", "_containers", "container", "=", "self", ".", "_containers", "[", "-", "1", "]", "if", "stylename", "is", "not", "None", ":", "stylename", "=", "...
Add text within the current container.
[ "Add", "text", "within", "the", "current", "container", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L617-L625
rossant/ipymd
ipymd/formats/notebook.py
_cell_output
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
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: ...
[ "def", "_cell_output", "(", "cell", ")", ":", "outputs", "=", "cell", ".", "get", "(", "'outputs'", ",", "[", "]", ")", "# Add stdout.", "stdout", "=", "(", "'\\n'", ".", "join", "(", "_ensure_string", "(", "output", ".", "get", "(", "'text'", ",", "...
Return the output of an ipynb cell.
[ "Return", "the", "output", "of", "an", "ipynb", "cell", "." ]
train
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/notebook.py#L33-L48
mk-fg/pretty-yaml
pyaml/__init__.py
dump_add_vspacing
def dump_add_vspacing(buff, vspacing): 'Post-processing to add some nice-ish spacing for deeper map/list levels.' if isinstance(vspacing, int): vspacing = ['\n']*(vspacing+1) buff.seek(0) result = list() for line in buff: level = 0 line = line.decode('utf-8') result.append(line) if ':' in line or re.sear...
python
def dump_add_vspacing(buff, vspacing): 'Post-processing to add some nice-ish spacing for deeper map/list levels.' if isinstance(vspacing, int): vspacing = ['\n']*(vspacing+1) buff.seek(0) result = list() for line in buff: level = 0 line = line.decode('utf-8') result.append(line) if ':' in line or re.sear...
[ "def", "dump_add_vspacing", "(", "buff", ",", "vspacing", ")", ":", "if", "isinstance", "(", "vspacing", ",", "int", ")", ":", "vspacing", "=", "[", "'\\n'", "]", "*", "(", "vspacing", "+", "1", ")", "buff", ".", "seek", "(", "0", ")", "result", "=...
Post-processing to add some nice-ish spacing for deeper map/list levels.
[ "Post", "-", "processing", "to", "add", "some", "nice", "-", "ish", "spacing", "for", "deeper", "map", "/", "list", "levels", "." ]
train
https://github.com/mk-fg/pretty-yaml/blob/a7f087124ad26f032357127614c87050fabb3de6/pyaml/__init__.py#L156-L174
happyleavesaoc/python-firetv
firetv/__init__.py
FireTV._dump
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
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)) ...
[ "def", "_dump", "(", "self", ",", "service", ",", "grep", "=", "None", ")", ":", "if", "grep", ":", "return", "self", ".", "adb_shell", "(", "'dumpsys {0} | grep \"{1}\"'", ".", "format", "(", "service", ",", "grep", ")", ")", "return", "self", ".", "a...
Perform a service dump. :param service: Service to dump. :param grep: Grep for this string. :returns: Dump, optionally grepped.
[ "Perform", "a", "service", "dump", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L226-L235
happyleavesaoc/python-firetv
firetv/__init__.py
FireTV._dump_has
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
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...
[ "def", "_dump_has", "(", "self", ",", "service", ",", "grep", ",", "search", ")", ":", "dump_grep", "=", "self", ".", "_dump", "(", "service", ",", "grep", "=", "grep", ")", "if", "not", "dump_grep", ":", "return", "False", "return", "dump_grep", ".", ...
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.
[ "Check", "if", "a", "dump", "has", "particular", "content", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L237-L250
happyleavesaoc/python-firetv
firetv/__init__.py
FireTV._ps
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
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: ...
[ "def", "_ps", "(", "self", ",", "search", "=", "''", ")", ":", "if", "not", "self", ".", "available", ":", "return", "result", "=", "[", "]", "ps", "=", "self", ".", "adb_streaming_shell", "(", "'ps'", ")", "try", ":", "for", "bad_line", "in", "ps"...
Perform a ps command with optional filtering. :param search: Check for this substring. :returns: List of matching fields
[ "Perform", "a", "ps", "command", "with", "optional", "filtering", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L259-L280
happyleavesaoc/python-firetv
firetv/__init__.py
FireTV.connect
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
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...
[ "def", "connect", "(", "self", ",", "always_log_errors", "=", "True", ")", ":", "self", ".", "_adb_lock", ".", "acquire", "(", "*", "*", "LOCK_KWARGS", ")", "try", ":", "if", "not", "self", ".", "adb_server_ip", ":", "# python-adb", "try", ":", "if", "...
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
[ "Connect", "to", "an", "Amazon", "Fire", "TV", "device", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L299-L350
happyleavesaoc/python-firetv
firetv/__init__.py
FireTV.update
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
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...
[ "def", "update", "(", "self", ",", "get_running_apps", "=", "True", ")", ":", "# The `screen_on`, `awake`, `wake_lock_size`, `current_app`, and `running_apps` properties.", "screen_on", ",", "awake", ",", "wake_lock_size", ",", "_current_app", ",", "running_apps", "=", "sel...
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 running_apps: the running apps
[ "Get", "the", "state", "of", "the", "device", "the", "current", "app", "and", "the", "running", "apps", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L357-L419
happyleavesaoc/python-firetv
firetv/__init__.py
FireTV.app_state
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
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
[ "def", "app_state", "(", "self", ",", "app", ")", ":", "if", "not", "self", ".", "available", "or", "not", "self", ".", "screen_on", ":", "return", "STATE_OFF", "if", "self", ".", "current_app", "[", "\"package\"", "]", "==", "app", ":", "return", "STA...
Informs if application is running.
[ "Informs", "if", "application", "is", "running", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L426-L432
happyleavesaoc/python-firetv
firetv/__init__.py
FireTV.state
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
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 #...
[ "def", "state", "(", "self", ")", ":", "# 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", "# Check if screen saver...
Compute and return the device state. :returns: Device state.
[ "Compute", "and", "return", "the", "device", "state", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L448-L469
happyleavesaoc/python-firetv
firetv/__init__.py
FireTV.available
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
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() ...
[ "def", "available", "(", "self", ")", ":", "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", ".", ...
Check whether the ADB connection is intact.
[ "Check", "whether", "the", "ADB", "connection", "is", "intact", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L472-L507
happyleavesaoc/python-firetv
firetv/__init__.py
FireTV.running_apps
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
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 []
[ "def", "running_apps", "(", "self", ")", ":", "ps", "=", "self", ".", "adb_shell", "(", "RUNNING_APPS_CMD", ")", "if", "ps", ":", "return", "[", "line", ".", "strip", "(", ")", ".", "rsplit", "(", "' '", ",", "1", ")", "[", "-", "1", "]", "for", ...
Return a list of running user applications.
[ "Return", "a", "list", "of", "running", "user", "applications", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L510-L515
happyleavesaoc/python-firetv
firetv/__init__.py
FireTV.current_app
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
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 ...
[ "def", "current_app", "(", "self", ")", ":", "current_focus", "=", "self", ".", "adb_shell", "(", "CURRENT_APP_CMD", ")", "if", "current_focus", "is", "None", ":", "return", "None", "current_focus", "=", "current_focus", ".", "replace", "(", "\"\\r\"", ",", ...
Return the current app.
[ "Return", "the", "current", "app", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L518-L534
happyleavesaoc/python-firetv
firetv/__init__.py
FireTV.wake_lock_size
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
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())
[ "def", "wake_lock_size", "(", "self", ")", ":", "output", "=", "self", ".", "adb_shell", "(", "WAKE_LOCK_SIZE_CMD", ")", "if", "not", "output", ":", "return", "None", "return", "int", "(", "output", ".", "split", "(", "\"=\"", ")", "[", "1", "]", ".", ...
Get the size of the current wake lock.
[ "Get", "the", "size", "of", "the", "current", "wake", "lock", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L552-L557
happyleavesaoc/python-firetv
firetv/__init__.py
FireTV.get_properties
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
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) + " && " + ...
[ "def", "get_properties", "(", "self", ",", "get_running_apps", "=", "True", ",", "lazy", "=", "False", ")", ":", "if", "get_running_apps", ":", "output", "=", "self", ".", "adb_shell", "(", "SCREEN_ON_CMD", "+", "(", "SUCCESS1", "if", "lazy", "else", "SUCC...
Get the ``screen_on``, ``awake``, ``wake_lock_size``, ``current_app``, and ``running_apps`` properties.
[ "Get", "the", "screen_on", "awake", "wake_lock_size", "current_app", "and", "running_apps", "properties", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L569-L623
happyleavesaoc/python-firetv
firetv/__main__.py
is_valid_device_id
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
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(...
[ "def", "is_valid_device_id", "(", "device_id", ")", ":", "valid", "=", "valid_device_id", ".", "match", "(", "device_id", ")", "if", "not", "valid", ":", "logging", ".", "error", "(", "\"A valid device identifier contains \"", "\"only ascii word characters or dashes. \"...
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.
[ "Check", "if", "device", "identifier", "is", "valid", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L50-L63
happyleavesaoc/python-firetv
firetv/__main__.py
add
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
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...
[ "def", "add", "(", "device_id", ",", "host", ",", "adbkey", "=", "''", ",", "adb_server_ip", "=", "''", ",", "adb_server_port", "=", "5037", ")", ":", "valid", "=", "is_valid_device_id", "(", "device_id", ")", "and", "is_valid_host", "(", "host", ")", "i...
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_server_ip: the IP address for the ADB server :param adb_server_port: the port for ...
[ "Add", "a", "device", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L78-L93
happyleavesaoc/python-firetv
firetv/__main__.py
add_device
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
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...
[ "def", "add_device", "(", ")", ":", "req", "=", "request", ".", "get_json", "(", ")", "success", "=", "False", "if", "'device_id'", "in", "req", "and", "'host'", "in", "req", ":", "success", "=", "add", "(", "req", "[", "'device_id'", "]", ",", "req"...
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>" }
[ "Add", "a", "device", "via", "HTTP", "POST", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L97-L113
happyleavesaoc/python-firetv
firetv/__main__.py
list_devices
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
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)
[ "def", "list_devices", "(", ")", ":", "output", "=", "{", "}", "for", "device_id", ",", "device", "in", "devices", ".", "items", "(", ")", ":", "output", "[", "device_id", "]", "=", "{", "'host'", ":", "device", ".", "host", ",", "'state'", ":", "d...
List devices via HTTP GET.
[ "List", "devices", "via", "HTTP", "GET", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L117-L125
happyleavesaoc/python-firetv
firetv/__main__.py
device_state
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
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)
[ "def", "device_state", "(", "device_id", ")", ":", "if", "device_id", "not", "in", "devices", ":", "return", "jsonify", "(", "success", "=", "False", ")", "return", "jsonify", "(", "state", "=", "devices", "[", "device_id", "]", ".", "state", ")" ]
Get device state via HTTP GET.
[ "Get", "device", "state", "via", "HTTP", "GET", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L129-L133
happyleavesaoc/python-firetv
firetv/__main__.py
current_app
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
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)
[ "def", "current_app", "(", "device_id", ")", ":", "if", "not", "is_valid_device_id", "(", "device_id", ")", ":", "abort", "(", "403", ")", "if", "device_id", "not", "in", "devices", ":", "abort", "(", "404", ")", "current", "=", "devices", "[", "device_i...
Get currently running app.
[ "Get", "currently", "running", "app", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L137-L148
happyleavesaoc/python-firetv
firetv/__main__.py
running_apps
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
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)
[ "def", "running_apps", "(", "device_id", ")", ":", "if", "not", "is_valid_device_id", "(", "device_id", ")", ":", "abort", "(", "403", ")", "if", "device_id", "not", "in", "devices", ":", "abort", "(", "404", ")", "return", "jsonify", "(", "running_apps", ...
Get running apps via HTTP GET.
[ "Get", "running", "apps", "via", "HTTP", "GET", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L152-L158
happyleavesaoc/python-firetv
firetv/__main__.py
get_app_state
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
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...
[ "def", "get_app_state", "(", "device_id", ",", "app_id", ")", ":", "if", "not", "is_valid_app_id", "(", "app_id", ")", ":", "abort", "(", "403", ")", "if", "not", "is_valid_device_id", "(", "device_id", ")", ":", "abort", "(", "403", ")", "if", "device_i...
Get the state of the requested app
[ "Get", "the", "state", "of", "the", "requested", "app" ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L162-L171
happyleavesaoc/python-firetv
firetv/__main__.py
device_action
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
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...
[ "def", "device_action", "(", "device_id", ",", "action_id", ")", ":", "success", "=", "False", "if", "device_id", "in", "devices", ":", "input_cmd", "=", "getattr", "(", "devices", "[", "device_id", "]", ",", "action_id", ",", "None", ")", "if", "callable"...
Initiate device action via HTTP GET.
[ "Initiate", "device", "action", "via", "HTTP", "GET", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L180-L188
happyleavesaoc/python-firetv
firetv/__main__.py
app_start
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
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...
[ "def", "app_start", "(", "device_id", ",", "app_id", ")", ":", "if", "not", "is_valid_app_id", "(", "app_id", ")", ":", "abort", "(", "403", ")", "if", "not", "is_valid_device_id", "(", "device_id", ")", ":", "abort", "(", "403", ")", "if", "device_id", ...
Starts an app with corresponding package name
[ "Starts", "an", "app", "with", "corresponding", "package", "name" ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L192-L202
happyleavesaoc/python-firetv
firetv/__main__.py
app_stop
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
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...
[ "def", "app_stop", "(", "device_id", ",", "app_id", ")", ":", "if", "not", "is_valid_app_id", "(", "app_id", ")", ":", "abort", "(", "403", ")", "if", "not", "is_valid_device_id", "(", "device_id", ")", ":", "abort", "(", "403", ")", "if", "device_id", ...
stops an app with corresponding package name
[ "stops", "an", "app", "with", "corresponding", "package", "name" ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L206-L216
happyleavesaoc/python-firetv
firetv/__main__.py
device_connect
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
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)
[ "def", "device_connect", "(", "device_id", ")", ":", "success", "=", "False", "if", "device_id", "in", "devices", ":", "devices", "[", "device_id", "]", ".", "connect", "(", ")", "success", "=", "True", "return", "jsonify", "(", "success", "=", "success", ...
Force a connection attempt via HTTP GET.
[ "Force", "a", "connection", "attempt", "via", "HTTP", "GET", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L220-L226
happyleavesaoc/python-firetv
firetv/__main__.py
_parse_config
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
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
[ "def", "_parse_config", "(", "config_file_path", ")", ":", "config_file", "=", "open", "(", "config_file_path", ",", "'r'", ")", "config", "=", "yaml", ".", "load", "(", "config_file", ")", "config_file", ".", "close", "(", ")", "return", "config" ]
Parse Config File from yaml file.
[ "Parse", "Config", "File", "from", "yaml", "file", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L229-L234
happyleavesaoc/python-firetv
firetv/__main__.py
_add_devices_from_config
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
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') ...
[ "def", "_add_devices_from_config", "(", "args", ")", ":", "config", "=", "_parse_config", "(", "args", ".", "config", ")", "for", "device", "in", "config", "[", "'devices'", "]", ":", "if", "args", ".", "default", ":", "if", "device", "==", "\"default\"", ...
Add devices from config.
[ "Add", "devices", "from", "config", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L237-L247
happyleavesaoc/python-firetv
firetv/__main__.py
main
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
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...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'AFTV Server'", ")", "parser", ".", "add_argument", "(", "'-p'", ",", "'--port'", ",", "type", "=", "int", ",", "help", "=", "'listen port'", ",", "...
Set up the server.
[ "Set", "up", "the", "server", "." ]
train
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L250-L263
areebbeigh/profanityfilter
profanityfilter/profanityfilter.py
ProfanityFilter._load_words
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
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()]
[ "def", "_load_words", "(", "self", ")", ":", "with", "open", "(", "self", ".", "_words_file", ",", "'r'", ")", "as", "f", ":", "self", ".", "_censor_list", "=", "[", "line", ".", "strip", "(", ")", "for", "line", "in", "f", ".", "readlines", "(", ...
Loads the list of profane words from file.
[ "Loads", "the", "list", "of", "profane", "words", "from", "file", "." ]
train
https://github.com/areebbeigh/profanityfilter/blob/f7e1c1bb1b7aea401e0d09219610cc690acd5476/profanityfilter/profanityfilter.py#L43-L46
areebbeigh/profanityfilter
profanityfilter/profanityfilter.py
ProfanityFilter.set_censor
def set_censor(self, character): """Replaces the original censor character '*' with ``character``.""" # TODO: what if character isn't str()-able? if isinstance(character, int): character = str(character) self._censor_char = character
python
def set_censor(self, character): """Replaces the original censor character '*' with ``character``.""" # TODO: what if character isn't str()-able? if isinstance(character, int): character = str(character) self._censor_char = character
[ "def", "set_censor", "(", "self", ",", "character", ")", ":", "# TODO: what if character isn't str()-able?", "if", "isinstance", "(", "character", ",", "int", ")", ":", "character", "=", "str", "(", "character", ")", "self", ".", "_censor_char", "=", "character"...
Replaces the original censor character '*' with ``character``.
[ "Replaces", "the", "original", "censor", "character", "*", "with", "character", "." ]
train
https://github.com/areebbeigh/profanityfilter/blob/f7e1c1bb1b7aea401e0d09219610cc690acd5476/profanityfilter/profanityfilter.py#L60-L65
areebbeigh/profanityfilter
profanityfilter/profanityfilter.py
ProfanityFilter.get_profane_words
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
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...
[ "def", "get_profane_words", "(", "self", ")", ":", "profane_words", "=", "[", "]", "if", "self", ".", "_custom_censor_list", ":", "profane_words", "=", "[", "w", "for", "w", "in", "self", ".", "_custom_censor_list", "]", "# Previous versions of Python don't have l...
Returns all profane words currently in use.
[ "Returns", "all", "profane", "words", "currently", "in", "use", "." ]
train
https://github.com/areebbeigh/profanityfilter/blob/f7e1c1bb1b7aea401e0d09219610cc690acd5476/profanityfilter/profanityfilter.py#L79-L97
areebbeigh/profanityfilter
profanityfilter/profanityfilter.py
ProfanityFilter.censor
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
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'\...
[ "def", "censor", "(", "self", ",", "input_text", ")", ":", "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}'", "i...
Returns input_text with any profane words censored.
[ "Returns", "input_text", "with", "any", "profane", "words", "censored", "." ]
train
https://github.com/areebbeigh/profanityfilter/blob/f7e1c1bb1b7aea401e0d09219610cc690acd5476/profanityfilter/profanityfilter.py#L105-L117
jborean93/smbprotocol
smbprotocol/ioctl.py
SMB2NetworkInterfaceInfo.unpack_multiple
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
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...
[ "def", "unpack_multiple", "(", "data", ")", ":", "chunks", "=", "[", "]", "while", "data", ":", "info", "=", "SMB2NetworkInterfaceInfo", "(", ")", "data", "=", "info", ".", "unpack", "(", "data", ")", "chunks", ".", "append", "(", "info", ")", "return"...
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 messages
[ "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", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/ioctl.py#L419-L434
jborean93/smbprotocol
smbprotocol/create_contexts.py
CreateContextName.get_response_structure
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
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...
[ "def", "get_response_structure", "(", "name", ")", ":", "return", "{", "CreateContextName", ".", "SMB2_CREATE_DURABLE_HANDLE_REQUEST", ":", "SMB2CreateDurableHandleResponse", "(", ")", ",", "CreateContextName", ".", "SMB2_CREATE_DURABLE_HANDLE_RECONNECT", ":", "SMB2CreateDura...
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
[ "Returns", "the", "response", "structure", "for", "a", "know", "list", "of", "create", "context", "responses", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/create_contexts.py#L41-L71
jborean93/smbprotocol
smbprotocol/create_contexts.py
SMB2CreateContextRequest.get_context_data
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
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...
[ "def", "get_context_data", "(", "self", ")", ":", "buffer_name", "=", "self", "[", "'buffer_name'", "]", ".", "get_value", "(", ")", "structure", "=", "CreateContextName", ".", "get_response_structure", "(", "buffer_name", ")", "if", "structure", ":", "structure...
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 unknown name
[ "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", "th...
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/create_contexts.py#L210-L225
jborean93/smbprotocol
smbprotocol/create_contexts.py
SMB2CreateEABuffer.pack_multiple
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
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...
[ "def", "pack_multiple", "(", "messages", ")", ":", "data", "=", "b\"\"", "msg_count", "=", "len", "(", "messages", ")", "for", "i", ",", "msg", "in", "enumerate", "(", "messages", ")", ":", "if", "i", "==", "msg_count", "-", "1", ":", "msg", "[", "...
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 buffer entry. :param messages: List of SMB2...
[ "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", ...
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/create_contexts.py#L303-L326
jborean93/smbprotocol
smbprotocol/exceptions.py
SMB2SymbolicLinkErrorResponse.set_name
def set_name(self, print_name, substitute_name): """ Set's the path_buffer and print/substitute name length of the message with the values passed in. These values should be a string and not a byte string as it is encoded in this function. :param print_name: The print name string...
python
def set_name(self, print_name, substitute_name): """ Set's the path_buffer and print/substitute name length of the message with the values passed in. These values should be a string and not a byte string as it is encoded in this function. :param print_name: The print name string...
[ "def", "set_name", "(", "self", ",", "print_name", ",", "substitute_name", ")", ":", "print_bytes", "=", "print_name", ".", "encode", "(", "'utf-16-le'", ")", "sub_bytes", "=", "substitute_name", ".", "encode", "(", "'utf-16-le'", ")", "path_buffer", "=", "pri...
Set's the path_buffer and print/substitute name length of the message with the values passed in. These values should be a string and not a byte string as it is encoded in this function. :param print_name: The print name string to set :param substitute_name: The substitute name string to...
[ "Set", "s", "the", "path_buffer", "and", "print", "/", "substitute", "name", "length", "of", "the", "message", "with", "the", "values", "passed", "in", ".", "These", "values", "should", "be", "a", "string", "and", "not", "a", "byte", "string", "as", "it"...
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/exceptions.py#L325-L342
jborean93/smbprotocol
smbprotocol/tree.py
TreeConnect.connect
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
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...
[ "def", "connect", "(", "self", ",", "require_secure_negotiate", "=", "True", ")", ":", "log", ".", "info", "(", "\"Session: %s - Creating connection to share %s\"", "%", "(", "self", ".", "session", ".", "username", ",", "self", ".", "share_name", ")", ")", "u...
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
[ "Connect", "to", "the", "share", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/tree.py#L197-L248
jborean93/smbprotocol
smbprotocol/tree.py
TreeConnect.disconnect
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
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...
[ "def", "disconnect", "(", "self", ")", ":", "if", "not", "self", ".", "_connected", ":", "return", "log", ".", "info", "(", "\"Session: %s, Tree: %s - Disconnecting from Tree Connect\"", "%", "(", "self", ".", "session", ".", "username", ",", "self", ".", "sha...
Disconnects the tree connection.
[ "Disconnects", "the", "tree", "connection", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/tree.py#L250-L275
jborean93/smbprotocol
smbprotocol/connection.py
Connection.connect
def connect(self, dialect=None, timeout=60): """ Will connect to the target server and negotiate the capabilities with the client. Once setup, the client MUST call the disconnect() function to close the listener thread. This function will populate various connection properties th...
python
def connect(self, dialect=None, timeout=60): """ Will connect to the target server and negotiate the capabilities with the client. Once setup, the client MUST call the disconnect() function to close the listener thread. This function will populate various connection properties th...
[ "def", "connect", "(", "self", ",", "dialect", "=", "None", ",", "timeout", "=", "60", ")", ":", "log", ".", "info", "(", "\"Setting up transport connection\"", ")", "self", ".", "transport", ".", "connect", "(", ")", "log", ".", "info", "(", "\"Starting...
Will connect to the target server and negotiate the capabilities with the client. Once setup, the client MUST call the disconnect() function to close the listener thread. This function will populate various connection properties that denote the capabilities of the server. :param...
[ "Will", "connect", "to", "the", "target", "server", "and", "negotiate", "the", "capabilities", "with", "the", "client", ".", "Once", "setup", "the", "client", "MUST", "call", "the", "disconnect", "()", "function", "to", "close", "the", "listener", "thread", ...
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L820-L891
jborean93/smbprotocol
smbprotocol/connection.py
Connection.disconnect
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
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...
[ "def", "disconnect", "(", "self", ",", "close", "=", "True", ")", ":", "if", "close", ":", "for", "session", "in", "list", "(", "self", ".", "session_table", ".", "values", "(", ")", ")", ":", "session", ".", "disconnect", "(", "True", ")", "log", ...
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 of each session.
[ "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", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L893-L907
jborean93/smbprotocol
smbprotocol/connection.py
Connection.send
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
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...
[ "def", "send", "(", "self", ",", "message", ",", "sid", "=", "None", ",", "tid", "=", "None", ",", "credit_request", "=", "None", ")", ":", "header", "=", "self", ".", "_generate_packet_header", "(", "message", ",", "sid", ",", "tid", ",", "credit_requ...
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 the message is sent for :param tid: A tree_id object that the message is sent fo...
[ "Will", "send", "a", "message", "to", "the", "server", "that", "is", "passed", "in", ".", "The", "final", "unencrypted", "header", "is", "returned", "to", "the", "function", "that", "called", "this", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L909-L946
jborean93/smbprotocol
smbprotocol/connection.py
Connection.send_compound
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
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 ...
[ "def", "send_compound", "(", "self", ",", "messages", ",", "sid", ",", "tid", ",", "related", "=", "False", ")", ":", "send_data", "=", "b\"\"", "session", "=", "self", ".", "session_table", "[", "sid", "]", "tree", "=", "session", ".", "tree_connect_tab...
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 that the request is sent for :param tid: A tree_id object that the messa...
[ "Sends", "multiple", "messages", "within", "1", "TCP", "request", "will", "fail", "if", "the", "size", "of", "the", "total", "length", "exceeds", "the", "maximum", "of", "the", "transport", "max", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L948-L1002
jborean93/smbprotocol
smbprotocol/connection.py
Connection.receive
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
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 ...
[ "def", "receive", "(", "self", ",", "request", ",", "wait", "=", "True", ",", "timeout", "=", "None", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "# check if we have received a response", "while", "True", ":", "self", ".", "_flush_message_buf...
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 response in the case of a STATUS_PENDING response, the pendin...
[ "Polls", "the", "message", "buffer", "of", "the", "TCP", "connection", "and", "waits", "until", "a", "valid", "message", "is", "received", "based", "on", "the", "message_id", "passed", "in", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L1004-L1044
jborean93/smbprotocol
smbprotocol/connection.py
Connection.echo
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
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...
[ "def", "echo", "(", "self", ",", "sid", "=", "0", ",", "timeout", "=", "60", ",", "credit_request", "=", "1", ")", ":", "log", ".", "info", "(", "\"Sending Echo request with a timeout of %d and credit \"", "\"request of %d\"", "%", "(", "timeout", ",", "credit...
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 authenticated session must be passed into this function or else the socket wi...
[ "Sends", "an", "SMB2", "Echo", "request", "to", "the", "server", ".", "This", "can", "be", "used", "to", "request", "more", "credits", "from", "the", "server", "with", "the", "credit_request", "param", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L1046-L1076
jborean93/smbprotocol
smbprotocol/connection.py
Connection._flush_message_buffer
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
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...
[ "def", "_flush_message_buffer", "(", "self", ")", ":", "while", "True", ":", "message_bytes", "=", "self", ".", "transport", ".", "receive", "(", ")", "# there were no messages receives, so break from the loop", "if", "message_bytes", "is", "None", ":", "break", "# ...
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
[ "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", ...
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L1120-L1173
jborean93/smbprotocol
smbprotocol/connection.py
Connection._calculate_credit_charge
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
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 ...
[ "def", "_calculate_credit_charge", "(", "self", ",", "message", ")", ":", "credit_size", "=", "65536", "if", "not", "self", ".", "supports_multi_credit", ":", "credit_charge", "=", "0", "elif", "message", ".", "COMMAND", "==", "Commands", ".", "SMB2_READ", ":"...
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 sending/receiving data over 64 kilobytes, in the existing...
[ "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", ...
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L1364-L1408
jborean93/smbprotocol
smbprotocol/session.py
Session.disconnect
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
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...
[ "def", "disconnect", "(", "self", ",", "close", "=", "True", ")", ":", "if", "not", "self", ".", "_connected", ":", "# already disconnected so let's return", "return", "if", "close", ":", "for", "open", "in", "list", "(", "self", ".", "open_table", ".", "v...
Logs off the session :param close: Will close all tree connects in a session
[ "Logs", "off", "the", "session" ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/session.py#L344-L373
jborean93/smbprotocol
smbprotocol/session.py
Session._smb3kdf
def _smb3kdf(self, ki, label, context): """ See SMB 3.x key derivation function https://blogs.msdn.microsoft.com/openspecification/2017/05/26/smb-2-and-smb-3-security-in-windows-10-the-anatomy-of-signing-and-cryptographic-keys/ :param ki: The session key is the KDK used as an input to t...
python
def _smb3kdf(self, ki, label, context): """ See SMB 3.x key derivation function https://blogs.msdn.microsoft.com/openspecification/2017/05/26/smb-2-and-smb-3-security-in-windows-10-the-anatomy-of-signing-and-cryptographic-keys/ :param ki: The session key is the KDK used as an input to t...
[ "def", "_smb3kdf", "(", "self", ",", "ki", ",", "label", ",", "context", ")", ":", "kdf", "=", "KBKDFHMAC", "(", "algorithm", "=", "hashes", ".", "SHA256", "(", ")", ",", "mode", "=", "Mode", ".", "CounterMode", ",", "length", "=", "16", ",", "rlen...
See SMB 3.x key derivation function https://blogs.msdn.microsoft.com/openspecification/2017/05/26/smb-2-and-smb-3-security-in-windows-10-the-anatomy-of-signing-and-cryptographic-keys/ :param ki: The session key is the KDK used as an input to the KDF :param label: The purpose of this derived key...
[ "See", "SMB", "3", ".", "x", "key", "derivation", "function", "https", ":", "//", "blogs", ".", "msdn", ".", "microsoft", ".", "com", "/", "openspecification", "/", "2017", "/", "05", "/", "26", "/", "smb", "-", "2", "-", "and", "-", "smb", "-", ...
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/session.py#L429-L452
jborean93/smbprotocol
smbprotocol/structure.py
Field.pack
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
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...
[ "def", "pack", "(", "self", ")", ":", "value", "=", "self", ".", "_get_calculated_value", "(", "self", ".", "value", ")", "packed_value", "=", "self", ".", "_pack_value", "(", "value", ")", "size", "=", "self", ".", "_get_calculated_size", "(", "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
[ "Packs", "the", "field", "value", "into", "a", "byte", "string", "so", "it", "can", "be", "sent", "to", "the", "server", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/structure.py#L164-L180
jborean93/smbprotocol
smbprotocol/structure.py
Field.set_value
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
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
[ "def", "set_value", "(", "self", ",", "value", ")", ":", "parsed_value", "=", "self", ".", "_parse_value", "(", "value", ")", "self", ".", "value", "=", "parsed_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
[ "Parses", "and", "sets", "the", "value", "attribute", "for", "the", "field", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/structure.py#L192-L200
jborean93/smbprotocol
smbprotocol/structure.py
Field.unpack
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
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 """ ...
[ "def", "unpack", "(", "self", ",", "data", ")", ":", "size", "=", "self", ".", "_get_calculated_size", "(", "self", ".", "size", ",", "data", ")", "self", ".", "set_value", "(", "data", "[", "0", ":", "size", "]", ")", "return", "data", "[", "len",...
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
[ "Takes", "in", "a", "byte", "string", "and", "set", "s", "the", "field", "value", "based", "on", "field", "definition", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/structure.py#L202-L213
jborean93/smbprotocol
smbprotocol/structure.py
Field._get_calculated_value
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
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...
[ "def", "_get_calculated_value", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "types", ".", "LambdaType", ")", ":", "expanded_value", "=", "value", "(", "self", ".", "structure", ")", "return", "self", ".", "_get_calculated_valu...
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
[ "Get", "s", "the", "final", "value", "of", "the", "field", "and", "runs", "the", "lambda", "functions", "recursively", "until", "a", "final", "value", "is", "derived", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/structure.py#L258-L272
jborean93/smbprotocol
smbprotocol/structure.py
Field._get_calculated_size
def _get_calculated_size(self, size, data): """ Get's the final size of the field and runs the lambda functions recursively until a final size is derived. If size is None then it will just return the length of the data as it is assumed it is the final field (None should only be s...
python
def _get_calculated_size(self, size, data): """ Get's the final size of the field and runs the lambda functions recursively until a final size is derived. If size is None then it will just return the length of the data as it is assumed it is the final field (None should only be s...
[ "def", "_get_calculated_size", "(", "self", ",", "size", ",", "data", ")", ":", "# if the size is derived from a lambda function, run it now; otherwise", "# return the value we passed in or the length of the data if the size", "# is None (last field value)", "if", "size", "is", "None...
Get's the final size of the field and runs the lambda functions recursively until a final size is derived. If size is None then it will just return the length of the data as it is assumed it is the final field (None should only be set on size for the final field). :param size: The size ...
[ "Get", "s", "the", "final", "size", "of", "the", "field", "and", "runs", "the", "lambda", "functions", "recursively", "until", "a", "final", "size", "is", "derived", ".", "If", "size", "is", "None", "then", "it", "will", "just", "return", "the", "length"...
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/structure.py#L274-L294
jborean93/smbprotocol
smbprotocol/structure.py
Field._get_struct_format
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
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...
[ "def", "_get_struct_format", "(", "self", ",", "size", ")", ":", "if", "isinstance", "(", "size", ",", "types", ".", "LambdaType", ")", ":", "size", "=", "size", "(", "self", ".", "structure", ")", "struct_format", "=", "{", "1", ":", "'B'", ",", "2"...
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 specified
[ "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", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/structure.py#L296-L317
jborean93/smbprotocol
smbprotocol/open.py
SMB2QueryDirectoryRequest.unpack_response
def unpack_response(file_information_class, buffer): """ Pass in the buffer value from the response object to unpack it and return a list of query response structures for the request. :param buffer: The raw bytes value of the SMB2QueryDirectoryResponse buffer field. ...
python
def unpack_response(file_information_class, buffer): """ Pass in the buffer value from the response object to unpack it and return a list of query response structures for the request. :param buffer: The raw bytes value of the SMB2QueryDirectoryResponse buffer field. ...
[ "def", "unpack_response", "(", "file_information_class", ",", "buffer", ")", ":", "structs", "=", "smbprotocol", ".", "query_info", "resp_structure", "=", "{", "FileInformationClass", ".", "FILE_DIRECTORY_INFORMATION", ":", "structs", ".", "FileDirectoryInformation", ",...
Pass in the buffer value from the response object to unpack it and return a list of query response structures for the request. :param buffer: The raw bytes value of the SMB2QueryDirectoryResponse buffer field. :return: List of query_info.* structures based on the FileInf...
[ "Pass", "in", "the", "buffer", "value", "from", "the", "response", "object", "to", "unpack", "it", "and", "return", "a", "list", "of", "query", "response", "structures", "for", "the", "request", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/open.py#L804-L840
jborean93/smbprotocol
smbprotocol/open.py
Open.create
def create(self, impersonation_level, desired_access, file_attributes, share_access, create_disposition, create_options, create_contexts=None, send=True): """ This will open the file based on the input parameters supplied. Any file open should also be called with Op...
python
def create(self, impersonation_level, desired_access, file_attributes, share_access, create_disposition, create_options, create_contexts=None, send=True): """ This will open the file based on the input parameters supplied. Any file open should also be called with Op...
[ "def", "create", "(", "self", ",", "impersonation_level", ",", "desired_access", ",", "file_attributes", ",", "share_access", ",", "create_disposition", ",", "create_options", ",", "create_contexts", "=", "None", ",", "send", "=", "True", ")", ":", "create", "="...
This will open the file based on the input parameters supplied. Any file open should also be called with Open.close() when it is finished. More details on how each option affects the open process can be found here https://msdn.microsoft.com/en-us/library/cc246502.aspx. Supports out of ...
[ "This", "will", "open", "the", "file", "based", "on", "the", "input", "parameters", "supplied", ".", "Any", "file", "open", "should", "also", "be", "called", "with", "Open", ".", "close", "()", "when", "it", "is", "finished", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/open.py#L934-L1012
jborean93/smbprotocol
smbprotocol/open.py
Open.read
def read(self, offset, length, min_length=0, unbuffered=False, wait=True, send=True): """ Reads from an opened file or pipe Supports out of band send function, call this function with send=False to return a tuple of (SMB2ReadRequest, receive_func) instead of sending...
python
def read(self, offset, length, min_length=0, unbuffered=False, wait=True, send=True): """ Reads from an opened file or pipe Supports out of band send function, call this function with send=False to return a tuple of (SMB2ReadRequest, receive_func) instead of sending...
[ "def", "read", "(", "self", ",", "offset", ",", "length", ",", "min_length", "=", "0", ",", "unbuffered", "=", "False", ",", "wait", "=", "True", ",", "send", "=", "True", ")", ":", "if", "length", ">", "self", ".", "connection", ".", "max_read_size"...
Reads from an opened file or pipe Supports out of band send function, call this function with send=False to return a tuple of (SMB2ReadRequest, receive_func) instead of sending the the request and waiting for the response. The receive_func can be used to get the response from the server...
[ "Reads", "from", "an", "opened", "file", "or", "pipe" ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/open.py#L1047-L1101
jborean93/smbprotocol
smbprotocol/open.py
Open.write
def write(self, data, offset=0, write_through=False, unbuffered=False, wait=True, send=True): """ Writes data to an opened file. Supports out of band send function, call this function with send=False to return a tuple of (SMBWriteRequest, receive_func) instead of s...
python
def write(self, data, offset=0, write_through=False, unbuffered=False, wait=True, send=True): """ Writes data to an opened file. Supports out of band send function, call this function with send=False to return a tuple of (SMBWriteRequest, receive_func) instead of s...
[ "def", "write", "(", "self", ",", "data", ",", "offset", "=", "0", ",", "write_through", "=", "False", ",", "unbuffered", "=", "False", ",", "wait", "=", "True", ",", "send", "=", "True", ")", ":", "data_len", "=", "len", "(", "data", ")", "if", ...
Writes data to an opened file. Supports out of band send function, call this function with send=False to return a tuple of (SMBWriteRequest, receive_func) instead of sending the the request and waiting for the response. The receive_func can be used to get the response from the server by...
[ "Writes", "data", "to", "an", "opened", "file", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/open.py#L1114-L1176
jborean93/smbprotocol
smbprotocol/open.py
Open.flush
def flush(self, send=True): """ A command sent by the client to request that a server flush all cached file information for the opened file. Supports out of band send function, call this function with send=False to return a tuple of (SMB2FlushRequest, receive_func) instead of ...
python
def flush(self, send=True): """ A command sent by the client to request that a server flush all cached file information for the opened file. Supports out of band send function, call this function with send=False to return a tuple of (SMB2FlushRequest, receive_func) instead of ...
[ "def", "flush", "(", "self", ",", "send", "=", "True", ")", ":", "flush", "=", "SMB2FlushRequest", "(", ")", "flush", "[", "'file_id'", "]", "=", "self", ".", "file_id", "if", "not", "send", ":", "return", "flush", ",", "self", ".", "_flush_response", ...
A command sent by the client to request that a server flush all cached file information for the opened file. Supports out of band send function, call this function with send=False to return a tuple of (SMB2FlushRequest, receive_func) instead of sending the the request and waiting for th...
[ "A", "command", "sent", "by", "the", "client", "to", "request", "that", "a", "server", "flush", "all", "cached", "file", "information", "for", "the", "opened", "file", "." ]
train
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/open.py#L1189-L1218