id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
2,500
opencobra/memote
memote/suite/results/repo_result_manager.py
RepoResultManager.add_git
def add_git(meta, git_info): """Enrich the result meta information with commit data.""" meta["hexsha"] = git_info.hexsha meta["author"] = git_info.author meta["email"] = git_info.email meta["authored_on"] = git_info.authored_on.isoformat(" ")
python
def add_git(meta, git_info): meta["hexsha"] = git_info.hexsha meta["author"] = git_info.author meta["email"] = git_info.email meta["authored_on"] = git_info.authored_on.isoformat(" ")
[ "def", "add_git", "(", "meta", ",", "git_info", ")", ":", "meta", "[", "\"hexsha\"", "]", "=", "git_info", ".", "hexsha", "meta", "[", "\"author\"", "]", "=", "git_info", ".", "author", "meta", "[", "\"email\"", "]", "=", "git_info", ".", "email", "meta", "[", "\"authored_on\"", "]", "=", "git_info", ".", "authored_on", ".", "isoformat", "(", "\" \"", ")" ]
Enrich the result meta information with commit data.
[ "Enrich", "the", "result", "meta", "information", "with", "commit", "data", "." ]
276630fcd4449fb7b914186edfd38c239e7052df
https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/suite/results/repo_result_manager.py#L106-L111
2,501
opencobra/memote
memote/suite/results/repo_result_manager.py
RepoResultManager.load
def load(self, commit=None): """Load a result from the storage directory.""" git_info = self.record_git_info(commit) LOGGER.debug("Loading the result for commit '%s'.", git_info.hexsha) filename = self.get_filename(git_info) LOGGER.debug("Loading the result '%s'.", filename) result = super(RepoResultManager, self).load(filename) self.add_git(result.meta, git_info) return result
python
def load(self, commit=None): git_info = self.record_git_info(commit) LOGGER.debug("Loading the result for commit '%s'.", git_info.hexsha) filename = self.get_filename(git_info) LOGGER.debug("Loading the result '%s'.", filename) result = super(RepoResultManager, self).load(filename) self.add_git(result.meta, git_info) return result
[ "def", "load", "(", "self", ",", "commit", "=", "None", ")", ":", "git_info", "=", "self", ".", "record_git_info", "(", "commit", ")", "LOGGER", ".", "debug", "(", "\"Loading the result for commit '%s'.\"", ",", "git_info", ".", "hexsha", ")", "filename", "=", "self", ".", "get_filename", "(", "git_info", ")", "LOGGER", ".", "debug", "(", "\"Loading the result '%s'.\"", ",", "filename", ")", "result", "=", "super", "(", "RepoResultManager", ",", "self", ")", ".", "load", "(", "filename", ")", "self", ".", "add_git", "(", "result", ".", "meta", ",", "git_info", ")", "return", "result" ]
Load a result from the storage directory.
[ "Load", "a", "result", "from", "the", "storage", "directory", "." ]
276630fcd4449fb7b914186edfd38c239e7052df
https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/suite/results/repo_result_manager.py#L133-L141
2,502
opencobra/memote
memote/jinja2_extension.py
MemoteExtension.normalize
def normalize(filename): """Return an absolute path of the given file name.""" # Default value means we do not resolve a model file. if filename == "default": return filename filename = expanduser(filename) if isabs(filename): return filename else: return join(os.getcwd(), filename)
python
def normalize(filename): # Default value means we do not resolve a model file. if filename == "default": return filename filename = expanduser(filename) if isabs(filename): return filename else: return join(os.getcwd(), filename)
[ "def", "normalize", "(", "filename", ")", ":", "# Default value means we do not resolve a model file.", "if", "filename", "==", "\"default\"", ":", "return", "filename", "filename", "=", "expanduser", "(", "filename", ")", "if", "isabs", "(", "filename", ")", ":", "return", "filename", "else", ":", "return", "join", "(", "os", ".", "getcwd", "(", ")", ",", "filename", ")" ]
Return an absolute path of the given file name.
[ "Return", "an", "absolute", "path", "of", "the", "given", "file", "name", "." ]
276630fcd4449fb7b914186edfd38c239e7052df
https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/jinja2_extension.py#L42-L51
2,503
opencobra/memote
memote/experimental/growth.py
GrowthExperiment.evaluate
def evaluate(self, model, threshold=0.1): """Evaluate in silico growth rates.""" with model: if self.medium is not None: self.medium.apply(model) if self.objective is not None: model.objective = self.objective model.add_cons_vars(self.constraints) threshold *= model.slim_optimize() growth = list() for row in self.data.itertuples(index=False): with model: exchange = model.reactions.get_by_id(row.exchange) if bool(exchange.reactants): exchange.lower_bound = -row.uptake else: exchange.upper_bound = row.uptake growth.append(model.slim_optimize() >= threshold) return DataFrame({ "exchange": self.data["exchange"], "growth": growth })
python
def evaluate(self, model, threshold=0.1): with model: if self.medium is not None: self.medium.apply(model) if self.objective is not None: model.objective = self.objective model.add_cons_vars(self.constraints) threshold *= model.slim_optimize() growth = list() for row in self.data.itertuples(index=False): with model: exchange = model.reactions.get_by_id(row.exchange) if bool(exchange.reactants): exchange.lower_bound = -row.uptake else: exchange.upper_bound = row.uptake growth.append(model.slim_optimize() >= threshold) return DataFrame({ "exchange": self.data["exchange"], "growth": growth })
[ "def", "evaluate", "(", "self", ",", "model", ",", "threshold", "=", "0.1", ")", ":", "with", "model", ":", "if", "self", ".", "medium", "is", "not", "None", ":", "self", ".", "medium", ".", "apply", "(", "model", ")", "if", "self", ".", "objective", "is", "not", "None", ":", "model", ".", "objective", "=", "self", ".", "objective", "model", ".", "add_cons_vars", "(", "self", ".", "constraints", ")", "threshold", "*=", "model", ".", "slim_optimize", "(", ")", "growth", "=", "list", "(", ")", "for", "row", "in", "self", ".", "data", ".", "itertuples", "(", "index", "=", "False", ")", ":", "with", "model", ":", "exchange", "=", "model", ".", "reactions", ".", "get_by_id", "(", "row", ".", "exchange", ")", "if", "bool", "(", "exchange", ".", "reactants", ")", ":", "exchange", ".", "lower_bound", "=", "-", "row", ".", "uptake", "else", ":", "exchange", ".", "upper_bound", "=", "row", ".", "uptake", "growth", ".", "append", "(", "model", ".", "slim_optimize", "(", ")", ">=", "threshold", ")", "return", "DataFrame", "(", "{", "\"exchange\"", ":", "self", ".", "data", "[", "\"exchange\"", "]", ",", "\"growth\"", ":", "growth", "}", ")" ]
Evaluate in silico growth rates.
[ "Evaluate", "in", "silico", "growth", "rates", "." ]
276630fcd4449fb7b914186edfd38c239e7052df
https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/experimental/growth.py#L67-L88
2,504
opencobra/memote
memote/suite/results/models.py
BJSON.process_bind_param
def process_bind_param(self, value, dialect): """Convert the value to a JSON encoded string before storing it.""" try: with BytesIO() as stream: with GzipFile(fileobj=stream, mode="wb") as file_handle: file_handle.write( jsonify(value, pretty=False).encode("utf-8") ) output = stream.getvalue() return output except TypeError as error: log_json_incompatible_types(value) raise_with_traceback(error)
python
def process_bind_param(self, value, dialect): try: with BytesIO() as stream: with GzipFile(fileobj=stream, mode="wb") as file_handle: file_handle.write( jsonify(value, pretty=False).encode("utf-8") ) output = stream.getvalue() return output except TypeError as error: log_json_incompatible_types(value) raise_with_traceback(error)
[ "def", "process_bind_param", "(", "self", ",", "value", ",", "dialect", ")", ":", "try", ":", "with", "BytesIO", "(", ")", "as", "stream", ":", "with", "GzipFile", "(", "fileobj", "=", "stream", ",", "mode", "=", "\"wb\"", ")", "as", "file_handle", ":", "file_handle", ".", "write", "(", "jsonify", "(", "value", ",", "pretty", "=", "False", ")", ".", "encode", "(", "\"utf-8\"", ")", ")", "output", "=", "stream", ".", "getvalue", "(", ")", "return", "output", "except", "TypeError", "as", "error", ":", "log_json_incompatible_types", "(", "value", ")", "raise_with_traceback", "(", "error", ")" ]
Convert the value to a JSON encoded string before storing it.
[ "Convert", "the", "value", "to", "a", "JSON", "encoded", "string", "before", "storing", "it", "." ]
276630fcd4449fb7b914186edfd38c239e7052df
https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/suite/results/models.py#L70-L82
2,505
opencobra/memote
memote/suite/results/models.py
BJSON.process_result_value
def process_result_value(self, value, dialect): """Convert a JSON encoded string to a dictionary structure.""" if value is not None: with BytesIO(value) as stream: with GzipFile(fileobj=stream, mode="rb") as file_handle: value = json.loads(file_handle.read().decode("utf-8")) return value
python
def process_result_value(self, value, dialect): if value is not None: with BytesIO(value) as stream: with GzipFile(fileobj=stream, mode="rb") as file_handle: value = json.loads(file_handle.read().decode("utf-8")) return value
[ "def", "process_result_value", "(", "self", ",", "value", ",", "dialect", ")", ":", "if", "value", "is", "not", "None", ":", "with", "BytesIO", "(", "value", ")", "as", "stream", ":", "with", "GzipFile", "(", "fileobj", "=", "stream", ",", "mode", "=", "\"rb\"", ")", "as", "file_handle", ":", "value", "=", "json", ".", "loads", "(", "file_handle", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ")", ")", "return", "value" ]
Convert a JSON encoded string to a dictionary structure.
[ "Convert", "a", "JSON", "encoded", "string", "to", "a", "dictionary", "structure", "." ]
276630fcd4449fb7b914186edfd38c239e7052df
https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/suite/results/models.py#L84-L90
2,506
pawamoy/django-zxcvbn-password
src/zxcvbn_password/validators.py
ZXCVBNValidator.validate
def validate(self, password, user=None): """Validate method, run zxcvbn and check score.""" user_inputs = [] if user is not None: for attribute in self.user_attributes: if hasattr(user, attribute): user_inputs.append(getattr(user, attribute)) results = zxcvbn(password, user_inputs=user_inputs) if results.get('score', 0) < self.min_score: feedback = ', '.join( results.get('feedback', {}).get('suggestions', [])) raise ValidationError(_(feedback), code=self.code, params={})
python
def validate(self, password, user=None): user_inputs = [] if user is not None: for attribute in self.user_attributes: if hasattr(user, attribute): user_inputs.append(getattr(user, attribute)) results = zxcvbn(password, user_inputs=user_inputs) if results.get('score', 0) < self.min_score: feedback = ', '.join( results.get('feedback', {}).get('suggestions', [])) raise ValidationError(_(feedback), code=self.code, params={})
[ "def", "validate", "(", "self", ",", "password", ",", "user", "=", "None", ")", ":", "user_inputs", "=", "[", "]", "if", "user", "is", "not", "None", ":", "for", "attribute", "in", "self", ".", "user_attributes", ":", "if", "hasattr", "(", "user", ",", "attribute", ")", ":", "user_inputs", ".", "append", "(", "getattr", "(", "user", ",", "attribute", ")", ")", "results", "=", "zxcvbn", "(", "password", ",", "user_inputs", "=", "user_inputs", ")", "if", "results", ".", "get", "(", "'score'", ",", "0", ")", "<", "self", ".", "min_score", ":", "feedback", "=", "', '", ".", "join", "(", "results", ".", "get", "(", "'feedback'", ",", "{", "}", ")", ".", "get", "(", "'suggestions'", ",", "[", "]", ")", ")", "raise", "ValidationError", "(", "_", "(", "feedback", ")", ",", "code", "=", "self", ".", "code", ",", "params", "=", "{", "}", ")" ]
Validate method, run zxcvbn and check score.
[ "Validate", "method", "run", "zxcvbn", "and", "check", "score", "." ]
7c6d37099da0f130d6ab88a0f941b6de476a0f86
https://github.com/pawamoy/django-zxcvbn-password/blob/7c6d37099da0f130d6ab88a0f941b6de476a0f86/src/zxcvbn_password/validators.py#L42-L54
2,507
rossant/ipymd
ipymd/formats/atlas.py
_get_html_contents
def _get_html_contents(html): """Process a HTML block and detects whether it is a code block, a math block, or a regular HTML block.""" parser = MyHTMLParser() parser.feed(html) if parser.is_code: return ('code', parser.data.strip()) elif parser.is_math: return ('math', parser.data.strip()) else: return '', ''
python
def _get_html_contents(html): parser = MyHTMLParser() parser.feed(html) if parser.is_code: return ('code', parser.data.strip()) elif parser.is_math: return ('math', parser.data.strip()) else: return '', ''
[ "def", "_get_html_contents", "(", "html", ")", ":", "parser", "=", "MyHTMLParser", "(", ")", "parser", ".", "feed", "(", "html", ")", "if", "parser", ".", "is_code", ":", "return", "(", "'code'", ",", "parser", ".", "data", ".", "strip", "(", ")", ")", "elif", "parser", ".", "is_math", ":", "return", "(", "'math'", ",", "parser", ".", "data", ".", "strip", "(", ")", ")", "else", ":", "return", "''", ",", "''" ]
Process a HTML block and detects whether it is a code block, a math block, or a regular HTML block.
[ "Process", "a", "HTML", "block", "and", "detects", "whether", "it", "is", "a", "code", "block", "a", "math", "block", "or", "a", "regular", "HTML", "block", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/atlas.py#L47-L57
2,508
rossant/ipymd
ipymd/core/format_manager.py
_is_path
def _is_path(s): """Return whether an object is a path.""" if isinstance(s, string_types): try: return op.exists(s) except (OSError, ValueError): return False else: return False
python
def _is_path(s): if isinstance(s, string_types): try: return op.exists(s) except (OSError, ValueError): return False else: return False
[ "def", "_is_path", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "string_types", ")", ":", "try", ":", "return", "op", ".", "exists", "(", "s", ")", "except", "(", "OSError", ",", "ValueError", ")", ":", "return", "False", "else", ":", "return", "False" ]
Return whether an object is a path.
[ "Return", "whether", "an", "object", "is", "a", "path", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L38-L46
2,509
rossant/ipymd
ipymd/core/format_manager.py
FormatManager.format_manager
def format_manager(cls): """Return the instance singleton, creating if necessary """ if cls._instance is None: # Discover the formats and register them with a new singleton. cls._instance = cls().register_entrypoints() return cls._instance
python
def format_manager(cls): if cls._instance is None: # Discover the formats and register them with a new singleton. cls._instance = cls().register_entrypoints() return cls._instance
[ "def", "format_manager", "(", "cls", ")", ":", "if", "cls", ".", "_instance", "is", "None", ":", "# Discover the formats and register them with a new singleton.", "cls", ".", "_instance", "=", "cls", "(", ")", ".", "register_entrypoints", "(", ")", "return", "cls", ".", "_instance" ]
Return the instance singleton, creating if necessary
[ "Return", "the", "instance", "singleton", "creating", "if", "necessary" ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L79-L85
2,510
rossant/ipymd
ipymd/core/format_manager.py
FormatManager.register_entrypoints
def register_entrypoints(self): """Look through the `setup_tools` `entry_points` and load all of the formats. """ for spec in iter_entry_points(self.entry_point_group): format_properties = {"name": spec.name} try: format_properties.update(spec.load()) except (DistributionNotFound, ImportError) as err: self.log.info( "ipymd format {} could not be loaded: {}".format( spec.name, err)) continue self.register(**format_properties) return self
python
def register_entrypoints(self): for spec in iter_entry_points(self.entry_point_group): format_properties = {"name": spec.name} try: format_properties.update(spec.load()) except (DistributionNotFound, ImportError) as err: self.log.info( "ipymd format {} could not be loaded: {}".format( spec.name, err)) continue self.register(**format_properties) return self
[ "def", "register_entrypoints", "(", "self", ")", ":", "for", "spec", "in", "iter_entry_points", "(", "self", ".", "entry_point_group", ")", ":", "format_properties", "=", "{", "\"name\"", ":", "spec", ".", "name", "}", "try", ":", "format_properties", ".", "update", "(", "spec", ".", "load", "(", ")", ")", "except", "(", "DistributionNotFound", ",", "ImportError", ")", "as", "err", ":", "self", ".", "log", ".", "info", "(", "\"ipymd format {} could not be loaded: {}\"", ".", "format", "(", "spec", ".", "name", ",", "err", ")", ")", "continue", "self", ".", "register", "(", "*", "*", "format_properties", ")", "return", "self" ]
Look through the `setup_tools` `entry_points` and load all of the formats.
[ "Look", "through", "the", "setup_tools", "entry_points", "and", "load", "all", "of", "the", "formats", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L87-L103
2,511
rossant/ipymd
ipymd/core/format_manager.py
FormatManager.format_from_extension
def format_from_extension(self, extension): """Find a format from its extension.""" formats = [name for name, format in self._formats.items() if format.get('file_extension', None) == extension] if len(formats) == 0: return None elif len(formats) == 2: raise RuntimeError("Several extensions are registered with " "that extension; please specify the format " "explicitly.") else: return formats[0]
python
def format_from_extension(self, extension): formats = [name for name, format in self._formats.items() if format.get('file_extension', None) == extension] if len(formats) == 0: return None elif len(formats) == 2: raise RuntimeError("Several extensions are registered with " "that extension; please specify the format " "explicitly.") else: return formats[0]
[ "def", "format_from_extension", "(", "self", ",", "extension", ")", ":", "formats", "=", "[", "name", "for", "name", ",", "format", "in", "self", ".", "_formats", ".", "items", "(", ")", "if", "format", ".", "get", "(", "'file_extension'", ",", "None", ")", "==", "extension", "]", "if", "len", "(", "formats", ")", "==", "0", ":", "return", "None", "elif", "len", "(", "formats", ")", "==", "2", ":", "raise", "RuntimeError", "(", "\"Several extensions are registered with \"", "\"that extension; please specify the format \"", "\"explicitly.\"", ")", "else", ":", "return", "formats", "[", "0", "]" ]
Find a format from its extension.
[ "Find", "a", "format", "from", "its", "extension", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L148-L160
2,512
rossant/ipymd
ipymd/core/format_manager.py
FormatManager.load
def load(self, file, name=None): """Load a file. The format name can be specified explicitly or inferred from the file extension.""" if name is None: name = self.format_from_extension(op.splitext(file)[1]) file_format = self.file_type(name) if file_format == 'text': return _read_text(file) elif file_format == 'json': return _read_json(file) else: load_function = self._formats[name].get('load', None) if load_function is None: raise IOError("The format must declare a file type or " "load/save functions.") return load_function(file)
python
def load(self, file, name=None): if name is None: name = self.format_from_extension(op.splitext(file)[1]) file_format = self.file_type(name) if file_format == 'text': return _read_text(file) elif file_format == 'json': return _read_json(file) else: load_function = self._formats[name].get('load', None) if load_function is None: raise IOError("The format must declare a file type or " "load/save functions.") return load_function(file)
[ "def", "load", "(", "self", ",", "file", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "self", ".", "format_from_extension", "(", "op", ".", "splitext", "(", "file", ")", "[", "1", "]", ")", "file_format", "=", "self", ".", "file_type", "(", "name", ")", "if", "file_format", "==", "'text'", ":", "return", "_read_text", "(", "file", ")", "elif", "file_format", "==", "'json'", ":", "return", "_read_json", "(", "file", ")", "else", ":", "load_function", "=", "self", ".", "_formats", "[", "name", "]", ".", "get", "(", "'load'", ",", "None", ")", "if", "load_function", "is", "None", ":", "raise", "IOError", "(", "\"The format must declare a file type or \"", "\"load/save functions.\"", ")", "return", "load_function", "(", "file", ")" ]
Load a file. The format name can be specified explicitly or inferred from the file extension.
[ "Load", "a", "file", ".", "The", "format", "name", "can", "be", "specified", "explicitly", "or", "inferred", "from", "the", "file", "extension", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L166-L181
2,513
rossant/ipymd
ipymd/core/format_manager.py
FormatManager.save
def save(self, file, contents, name=None, overwrite=False): """Save contents into a file. The format name can be specified explicitly or inferred from the file extension.""" if name is None: name = self.format_from_extension(op.splitext(file)[1]) file_format = self.file_type(name) if file_format == 'text': _write_text(file, contents) elif file_format == 'json': _write_json(file, contents) else: write_function = self._formats[name].get('save', None) if write_function is None: raise IOError("The format must declare a file type or " "load/save functions.") if op.exists(file) and not overwrite: print("The file already exists, please use overwrite=True.") return write_function(file, contents)
python
def save(self, file, contents, name=None, overwrite=False): if name is None: name = self.format_from_extension(op.splitext(file)[1]) file_format = self.file_type(name) if file_format == 'text': _write_text(file, contents) elif file_format == 'json': _write_json(file, contents) else: write_function = self._formats[name].get('save', None) if write_function is None: raise IOError("The format must declare a file type or " "load/save functions.") if op.exists(file) and not overwrite: print("The file already exists, please use overwrite=True.") return write_function(file, contents)
[ "def", "save", "(", "self", ",", "file", ",", "contents", ",", "name", "=", "None", ",", "overwrite", "=", "False", ")", ":", "if", "name", "is", "None", ":", "name", "=", "self", ".", "format_from_extension", "(", "op", ".", "splitext", "(", "file", ")", "[", "1", "]", ")", "file_format", "=", "self", ".", "file_type", "(", "name", ")", "if", "file_format", "==", "'text'", ":", "_write_text", "(", "file", ",", "contents", ")", "elif", "file_format", "==", "'json'", ":", "_write_json", "(", "file", ",", "contents", ")", "else", ":", "write_function", "=", "self", ".", "_formats", "[", "name", "]", ".", "get", "(", "'save'", ",", "None", ")", "if", "write_function", "is", "None", ":", "raise", "IOError", "(", "\"The format must declare a file type or \"", "\"load/save functions.\"", ")", "if", "op", ".", "exists", "(", "file", ")", "and", "not", "overwrite", ":", "print", "(", "\"The file already exists, please use overwrite=True.\"", ")", "return", "write_function", "(", "file", ",", "contents", ")" ]
Save contents into a file. The format name can be specified explicitly or inferred from the file extension.
[ "Save", "contents", "into", "a", "file", ".", "The", "format", "name", "can", "be", "specified", "explicitly", "or", "inferred", "from", "the", "file", "extension", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L183-L201
2,514
rossant/ipymd
ipymd/core/format_manager.py
FormatManager.create_reader
def create_reader(self, name, *args, **kwargs): """Create a new reader instance for a given format.""" self._check_format(name) return self._formats[name]['reader'](*args, **kwargs)
python
def create_reader(self, name, *args, **kwargs): self._check_format(name) return self._formats[name]['reader'](*args, **kwargs)
[ "def", "create_reader", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_format", "(", "name", ")", "return", "self", ".", "_formats", "[", "name", "]", "[", "'reader'", "]", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Create a new reader instance for a given format.
[ "Create", "a", "new", "reader", "instance", "for", "a", "given", "format", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L203-L206
2,515
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): 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", ",", "*", "*", "kwargs", ")" ]
Create a new writer instance for a given format.
[ "Create", "a", "new", "writer", "instance", "for", "a", "given", "format", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L208-L211
2,516
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. 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 of the target format. If None, this is the ipymd_cells format. reader : a Reader instance or None writer : a Writer instance or None from_kwargs : dict Optional keyword arguments to pass to the reader instance. to_kwargs : dict Optional keyword arguments to pass to the writer instance. """ # Load the file if 'contents_or_path' is a path. if _is_path(contents_or_path): contents = self.load(contents_or_path, from_) else: contents = contents_or_path if from_kwargs is None: from_kwargs = {} if to_kwargs is None: to_kwargs = {} if reader is None: reader = (self.create_reader(from_, **from_kwargs) if from_ is not None else None) if writer is None: writer = (self.create_writer(to, **to_kwargs) if to is not None else None) if reader is not None: # Convert from the source format to ipymd cells. cells = [cell for cell in reader.read(contents)] else: # If no reader is specified, 'contents' is assumed to already be # a list of ipymd cells. cells = contents notebook_metadata = [cell for cell in cells if cell["cell_type"] == "notebook_metadata"] if writer is not None: if notebook_metadata: [cells.remove(cell) for cell in notebook_metadata] notebook_metadata = self.clean_meta( notebook_metadata[0]["metadata"] ) if hasattr(writer, "write_notebook_metadata"): writer.write_notebook_metadata(notebook_metadata) else: print("{} does not support notebook metadata, " "dropping metadata: {}".format( writer, notebook_metadata)) # Convert from ipymd cells to the target format. for cell in cells: meta = self.clean_cell_meta(cell.get("metadata", {})) if not meta: cell.pop("metadata", None) writer.write(cell) return writer.contents else: # If no writer is specified, the output is supposed to be # a list of ipymd cells. return cells
python
def convert(self, contents_or_path, from_=None, to=None, reader=None, writer=None, from_kwargs=None, to_kwargs=None, ): # Load the file if 'contents_or_path' is a path. if _is_path(contents_or_path): contents = self.load(contents_or_path, from_) else: contents = contents_or_path if from_kwargs is None: from_kwargs = {} if to_kwargs is None: to_kwargs = {} if reader is None: reader = (self.create_reader(from_, **from_kwargs) if from_ is not None else None) if writer is None: writer = (self.create_writer(to, **to_kwargs) if to is not None else None) if reader is not None: # Convert from the source format to ipymd cells. cells = [cell for cell in reader.read(contents)] else: # If no reader is specified, 'contents' is assumed to already be # a list of ipymd cells. cells = contents notebook_metadata = [cell for cell in cells if cell["cell_type"] == "notebook_metadata"] if writer is not None: if notebook_metadata: [cells.remove(cell) for cell in notebook_metadata] notebook_metadata = self.clean_meta( notebook_metadata[0]["metadata"] ) if hasattr(writer, "write_notebook_metadata"): writer.write_notebook_metadata(notebook_metadata) else: print("{} does not support notebook metadata, " "dropping metadata: {}".format( writer, notebook_metadata)) # Convert from ipymd cells to the target format. for cell in cells: meta = self.clean_cell_meta(cell.get("metadata", {})) if not meta: cell.pop("metadata", None) writer.write(cell) return writer.contents else: # If no writer is specified, the output is supposed to be # a list of ipymd cells. return cells
[ "def", "convert", "(", "self", ",", "contents_or_path", ",", "from_", "=", "None", ",", "to", "=", "None", ",", "reader", "=", "None", ",", "writer", "=", "None", ",", "from_kwargs", "=", "None", ",", "to_kwargs", "=", "None", ",", ")", ":", "# Load the file if 'contents_or_path' is a path.", "if", "_is_path", "(", "contents_or_path", ")", ":", "contents", "=", "self", ".", "load", "(", "contents_or_path", ",", "from_", ")", "else", ":", "contents", "=", "contents_or_path", "if", "from_kwargs", "is", "None", ":", "from_kwargs", "=", "{", "}", "if", "to_kwargs", "is", "None", ":", "to_kwargs", "=", "{", "}", "if", "reader", "is", "None", ":", "reader", "=", "(", "self", ".", "create_reader", "(", "from_", ",", "*", "*", "from_kwargs", ")", "if", "from_", "is", "not", "None", "else", "None", ")", "if", "writer", "is", "None", ":", "writer", "=", "(", "self", ".", "create_writer", "(", "to", ",", "*", "*", "to_kwargs", ")", "if", "to", "is", "not", "None", "else", "None", ")", "if", "reader", "is", "not", "None", ":", "# Convert from the source format to ipymd cells.", "cells", "=", "[", "cell", "for", "cell", "in", "reader", ".", "read", "(", "contents", ")", "]", "else", ":", "# If no reader is specified, 'contents' is assumed to already be", "# a list of ipymd cells.", "cells", "=", "contents", "notebook_metadata", "=", "[", "cell", "for", "cell", "in", "cells", "if", "cell", "[", "\"cell_type\"", "]", "==", "\"notebook_metadata\"", "]", "if", "writer", "is", "not", "None", ":", "if", "notebook_metadata", ":", "[", "cells", ".", "remove", "(", "cell", ")", "for", "cell", "in", "notebook_metadata", "]", "notebook_metadata", "=", "self", ".", "clean_meta", "(", "notebook_metadata", "[", "0", "]", "[", "\"metadata\"", "]", ")", "if", "hasattr", "(", "writer", ",", "\"write_notebook_metadata\"", ")", ":", "writer", ".", "write_notebook_metadata", "(", "notebook_metadata", ")", "else", ":", "print", "(", "\"{} does not support notebook metadata, \"", "\"dropping metadata: {}\"", ".", "format", "(", "writer", ",", "notebook_metadata", ")", ")", "# Convert from ipymd cells to the target format.", "for", "cell", "in", "cells", ":", "meta", "=", "self", ".", "clean_cell_meta", "(", "cell", ".", "get", "(", "\"metadata\"", ",", "{", "}", ")", ")", "if", "not", "meta", ":", "cell", ".", "pop", "(", "\"metadata\"", ",", "None", ")", "writer", ".", "write", "(", "cell", ")", "return", "writer", ".", "contents", "else", ":", "# If no writer is specified, the output is supposed to be", "# a list of ipymd cells.", "return", "cells" ]
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 of the target format. If None, this is the ipymd_cells format. reader : a Reader instance or None writer : a Writer instance or None from_kwargs : dict Optional keyword arguments to pass to the reader instance. to_kwargs : dict Optional keyword arguments to pass to the writer instance.
[ "Convert", "contents", "between", "supported", "formats", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L213-L299
2,517
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_name) if (meta.get("kernelspec", {}) .get("name", None) == default_kernel_name): del meta["kernelspec"] meta.pop("language_info", None) return meta
python
def clean_meta(self, meta): if not self.verbose_metadata: default_kernel_name = (self.default_kernel_name or self._km.kernel_name) if (meta.get("kernelspec", {}) .get("name", None) == default_kernel_name): del meta["kernelspec"] meta.pop("language_info", None) return meta
[ "def", "clean_meta", "(", "self", ",", "meta", ")", ":", "if", "not", "self", ".", "verbose_metadata", ":", "default_kernel_name", "=", "(", "self", ".", "default_kernel_name", "or", "self", ".", "_km", ".", "kernel_name", ")", "if", "(", "meta", ".", "get", "(", "\"kernelspec\"", ",", "{", "}", ")", ".", "get", "(", "\"name\"", ",", "None", ")", "==", "default_kernel_name", ")", ":", "del", "meta", "[", "\"kernelspec\"", "]", "meta", ".", "pop", "(", "\"language_info\"", ",", "None", ")", "return", "meta" ]
Removes unwanted metadata Parameters ---------- meta : dict Notebook metadata.
[ "Removes", "unwanted", "metadata" ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L301-L319
2,518
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): 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", ",", "None", ")", "return", "meta" ]
Remove cell metadata that matches the default cell metadata.
[ "Remove", "cell", "metadata", "that", "matches", "the", "default", "cell", "metadata", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L321-L326
2,519
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): 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", "(", "line", ")" ]
Return whether a line starts with a regex or not.
[ "Return", "whether", "a", "line", "starts", "with", "a", "regex", "or", "not", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/prompt.py#L37-L42
2,520
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': prompt = PythonPromptManager elif prompt == 'ipython': prompt = IPythonPromptManager # Instanciate the class. if isinstance(prompt, BasePromptManager): return prompt else: return prompt()
python
def create_prompt(prompt): if prompt is None: prompt = 'python' if prompt == 'python': prompt = PythonPromptManager elif prompt == 'ipython': prompt = IPythonPromptManager # Instanciate the class. if isinstance(prompt, BasePromptManager): return prompt else: return prompt()
[ "def", "create_prompt", "(", "prompt", ")", ":", "if", "prompt", "is", "None", ":", "prompt", "=", "'python'", "if", "prompt", "==", "'python'", ":", "prompt", "=", "PythonPromptManager", "elif", "prompt", "==", "'ipython'", ":", "prompt", "=", "IPythonPromptManager", "# Instanciate the class.", "if", "isinstance", "(", "prompt", ",", "BasePromptManager", ")", ":", "return", "prompt", "else", ":", "return", "prompt", "(", ")" ]
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", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/prompt.py#L231-L252
2,521
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 else: break return lines[:i], lines[i:]
python
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): i += 1 else: break return lines[:i], lines[i:]
[ "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", ")", ":", "i", "+=", "1", "else", ":", "break", "return", "lines", "[", ":", "i", "]", ",", "lines", "[", "i", ":", "]" ]
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", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/prompt.py#L87-L97
2,522
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 [] lexer = PythonSplitLexer() lexer.read(python) return lexer.chunks
python
def _split_python(python): python = _preprocess(python) if not python: return [] lexer = PythonSplitLexer() lexer.read(python) return lexer.chunks
[ "def", "_split_python", "(", "python", ")", ":", "python", "=", "_preprocess", "(", "python", ")", "if", "not", "python", ":", "return", "[", "]", "lexer", "=", "PythonSplitLexer", "(", ")", "lexer", ".", "read", "(", "python", ")", "return", "lexer", ".", "chunks" ]
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", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/python.py#L86-L99
2,523
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 if not line[2:].startswith('#')) # skip headers if not source: return True # Try to parse the chunk: if it fails, it is Markdown, otherwise, # it is Python. return not _is_python(source) return False
python
def _is_chunk_markdown(source): 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 if not line[2:].startswith('#')) # skip headers if not source: return True # Try to parse the chunk: if it fails, it is Markdown, otherwise, # it is Python. return not _is_python(source) return False
[ "def", "_is_chunk_markdown", "(", "source", ")", ":", "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", "if", "not", "line", "[", "2", ":", "]", ".", "startswith", "(", "'#'", ")", ")", "# skip headers", "if", "not", "source", ":", "return", "True", "# Try to parse the chunk: if it fails, it is Markdown, otherwise,", "# it is Python.", "return", "not", "_is_python", "(", "source", ")", "return", "False" ]
Return whether a chunk contains Markdown contents.
[ "Return", "whether", "a", "chunk", "contains", "Markdown", "contents", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/python.py#L102-L114
2,524
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(tuple(headers))] return '\n'.join(lines)
python
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 filters] lines = [line for line in lines if line.startswith(tuple(headers))] return '\n'.join(lines)
[ "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", "filters", "]", "lines", "=", "[", "line", "for", "line", "in", "lines", "if", "line", ".", "startswith", "(", "tuple", "(", "headers", ")", ")", "]", "return", "'\\n'", ".", "join", "(", "lines", ")" ]
Only keep some Markdown headers from a Markdown string.
[ "Only", "keep", "some", "Markdown", "headers", "from", "a", "Markdown", "string", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/markdown.py#L647-L653
2,525
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): 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", "=", "level", ")" ]
Parse setext heading.
[ "Parse", "setext", "heading", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/markdown.py#L184-L187
2,526
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) text = self._output.getvalue() assert text[-n-1] != '\n' assert text[-n:] == '\n' * n
python
def ensure_newline(self, n): 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) text = self._output.getvalue() assert text[-n-1] != '\n' assert text[-n:] == '\n' * n
[ "def", "ensure_newline", "(", "self", ",", "n", ")", ":", "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", ")", "text", "=", "self", ".", "_output", ".", "getvalue", "(", ")", "assert", "text", "[", "-", "n", "-", "1", "]", "!=", "'\\n'", "assert", "text", "[", "-", "n", ":", "]", "==", "'\\n'", "*", "n" ]
Make sure there are 'n' line breaks at the end.
[ "Make", "sure", "there", "are", "n", "line", "breaks", "at", "the", "end", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/markdown.py#L560-L571
2,527
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 follows the YAML spec of dashes and periods --- some: yaml ... Both must be followed by at least one blank line (\n\n). """ body = m.group('body') is_notebook = m.group('sep_close') == '---' if is_notebook: # make it into a valid YAML object by stripping --- body = body.strip()[:-3] + '...' try: if body: return self._meta(yaml.safe_load(m.group('body')), is_notebook) else: return self._meta({'ipymd': {'empty_meta': True}}, is_notebook) except Exception as err: raise Exception(body, err)
python
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 stripping --- body = body.strip()[:-3] + '...' try: if body: return self._meta(yaml.safe_load(m.group('body')), is_notebook) else: return self._meta({'ipymd': {'empty_meta': True}}, is_notebook) except Exception as err: raise Exception(body, err)
[ "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 stripping ---", "body", "=", "body", ".", "strip", "(", ")", "[", ":", "-", "3", "]", "+", "'...'", "try", ":", "if", "body", ":", "return", "self", ".", "_meta", "(", "yaml", ".", "safe_load", "(", "m", ".", "group", "(", "'body'", ")", ")", ",", "is_notebook", ")", "else", ":", "return", "self", ".", "_meta", "(", "{", "'ipymd'", ":", "{", "'empty_meta'", ":", "True", "}", "}", ",", "is_notebook", ")", "except", "Exception", "as", "err", ":", "raise", "Exception", "(", "body", ",", "err", ")" ]
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 --- some: yaml ... Both must be followed by at least one blank line (\n\n).
[ "Extract", "and", "parse", "YAML", "metadata", "from", "a", "meta", "match" ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/markdown.py#L77-L107
2,528
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): 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", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/markdown.py#L201-L206
2,529
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(text) return text
python
def _preprocess(text, tab=4): 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(text) return text
[ "def", "_preprocess", "(", "text", ",", "tab", "=", "4", ")", ":", "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", "(", "text", ")", "return", "text" ]
Normalize a text.
[ "Normalize", "a", "text", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/utils/utils.py#L37-L46
2,530
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): 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", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/utils/utils.py#L95-L98
2,531
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): 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", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/utils/utils.py#L118-L121
2,532
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.setAttribute('listlevelpositionandspacemode', 'label-alignment') llla = ListLevelLabelAlignment(labelfollowedby='listtab') llla.setAttribute('listtabstopposition', '1.27cm') llla.setAttribute('textindent', '-0.635cm') llla.setAttribute('marginleft', '1.27cm') llp.addElement(llla) # llp.setAttribute('spacebefore', '') # llp.setAttribute('minlabelwidth', '') lls.addElement(llp) style.addElement(lls) return style
python
def _numbered_style(): style = ListStyle(name='_numbered_list') lls = ListLevelStyleNumber(level=1) lls.setAttribute('displaylevels', 1) lls.setAttribute('numsuffix', '. ') lls.setAttribute('numformat', '1') llp = ListLevelProperties() llp.setAttribute('listlevelpositionandspacemode', 'label-alignment') llla = ListLevelLabelAlignment(labelfollowedby='listtab') llla.setAttribute('listtabstopposition', '1.27cm') llla.setAttribute('textindent', '-0.635cm') llla.setAttribute('marginleft', '1.27cm') llp.addElement(llla) # llp.setAttribute('spacebefore', '') # llp.setAttribute('minlabelwidth', '') lls.addElement(llp) style.addElement(lls) return style
[ "def", "_numbered_style", "(", ")", ":", "style", "=", "ListStyle", "(", "name", "=", "'_numbered_list'", ")", "lls", "=", "ListLevelStyleNumber", "(", "level", "=", "1", ")", "lls", ".", "setAttribute", "(", "'displaylevels'", ",", "1", ")", "lls", ".", "setAttribute", "(", "'numsuffix'", ",", "'. '", ")", "lls", ".", "setAttribute", "(", "'numformat'", ",", "'1'", ")", "llp", "=", "ListLevelProperties", "(", ")", "llp", ".", "setAttribute", "(", "'listlevelpositionandspacemode'", ",", "'label-alignment'", ")", "llla", "=", "ListLevelLabelAlignment", "(", "labelfollowedby", "=", "'listtab'", ")", "llla", ".", "setAttribute", "(", "'listtabstopposition'", ",", "'1.27cm'", ")", "llla", ".", "setAttribute", "(", "'textindent'", ",", "'-0.635cm'", ")", "llla", ".", "setAttribute", "(", "'marginleft'", ",", "'1.27cm'", ")", "llp", ".", "addElement", "(", "llla", ")", "# llp.setAttribute('spacebefore', '')", "# llp.setAttribute('minlabelwidth', '')", "lls", ".", "addElement", "(", "llp", ")", "style", ".", "addElement", "(", "lls", ")", "return", "style" ]
Create a numbered list style.
[ "Create", "a", "numbered", "list", "style", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L119-L146
2,533
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(kwargs.keys()) for k in keys: if 'margin' in k: kwargs_par[k] = kwargs.pop(k) style.addElement(TextProperties(**kwargs)) if kwargs_par: style.addElement(ParagraphProperties(**kwargs_par)) return style
python
def _create_style(name, family=None, **kwargs): if family == 'paragraph' and 'marginbottom' not in kwargs: kwargs['marginbottom'] = '.5cm' style = Style(name=name, family=family) # Extract paragraph properties. kwargs_par = {} keys = sorted(kwargs.keys()) for k in keys: if 'margin' in k: kwargs_par[k] = kwargs.pop(k) style.addElement(TextProperties(**kwargs)) if kwargs_par: style.addElement(ParagraphProperties(**kwargs_par)) return style
[ "def", "_create_style", "(", "name", ",", "family", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "family", "==", "'paragraph'", "and", "'marginbottom'", "not", "in", "kwargs", ":", "kwargs", "[", "'marginbottom'", "]", "=", "'.5cm'", "style", "=", "Style", "(", "name", "=", "name", ",", "family", "=", "family", ")", "# Extract paragraph properties.", "kwargs_par", "=", "{", "}", "keys", "=", "sorted", "(", "kwargs", ".", "keys", "(", ")", ")", "for", "k", "in", "keys", ":", "if", "'margin'", "in", "k", ":", "kwargs_par", "[", "k", "]", "=", "kwargs", ".", "pop", "(", "k", ")", "style", ".", "addElement", "(", "TextProperties", "(", "*", "*", "kwargs", ")", ")", "if", "kwargs_par", ":", "style", ".", "addElement", "(", "ParagraphProperties", "(", "*", "*", "kwargs_par", ")", ")", "return", "style" ]
Helper function for creating a new style.
[ "Helper", "function", "for", "creating", "a", "new", "style", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L149-L163
2,534
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', ) _add_style('heading-2', family='paragraph', fontsize='22pt', fontweight='bold', ) _add_style('heading-3', family='paragraph', fontsize='20pt', fontweight='bold', ) _add_style('heading-4', family='paragraph', fontsize='18pt', fontweight='bold', ) _add_style('heading-5', family='paragraph', fontsize='16pt', fontweight='bold', ) _add_style('heading-6', family='paragraph', fontsize='14pt', fontweight='bold', ) _add_style('normal-paragraph', family='paragraph', fontsize='12pt', marginbottom='0.25cm', ) _add_style('code', family='paragraph', fontsize='10pt', fontweight='bold', fontfamily='Courier New', color='#555555', ) _add_style('quote', family='paragraph', fontsize='12pt', fontstyle='italic', ) _add_style('list-paragraph', family='paragraph', fontsize='12pt', marginbottom='.1cm', ) _add_style('sublist-paragraph', family='paragraph', fontsize='12pt', marginbottom='.1cm', ) _add_style('numbered-list-paragraph', family='paragraph', fontsize='12pt', marginbottom='.1cm', ) _add_style('normal-text', family='text', fontsize='12pt', ) _add_style('italic', family='text', fontstyle='italic', fontsize='12pt', ) _add_style('bold', family='text', fontweight='bold', fontsize='12pt', ) _add_style('url', family='text', fontsize='12pt', fontweight='bold', fontfamily='Courier', ) _add_style('inline-code', family='text', fontsize='10pt', fontweight='bold', fontfamily='Courier New', color='#555555', ) styles['_numbered_list'] = _numbered_style() return styles
python
def default_styles(): styles = {} def _add_style(name, **kwargs): styles[name] = _create_style(name, **kwargs) _add_style('heading-1', family='paragraph', fontsize='24pt', fontweight='bold', ) _add_style('heading-2', family='paragraph', fontsize='22pt', fontweight='bold', ) _add_style('heading-3', family='paragraph', fontsize='20pt', fontweight='bold', ) _add_style('heading-4', family='paragraph', fontsize='18pt', fontweight='bold', ) _add_style('heading-5', family='paragraph', fontsize='16pt', fontweight='bold', ) _add_style('heading-6', family='paragraph', fontsize='14pt', fontweight='bold', ) _add_style('normal-paragraph', family='paragraph', fontsize='12pt', marginbottom='0.25cm', ) _add_style('code', family='paragraph', fontsize='10pt', fontweight='bold', fontfamily='Courier New', color='#555555', ) _add_style('quote', family='paragraph', fontsize='12pt', fontstyle='italic', ) _add_style('list-paragraph', family='paragraph', fontsize='12pt', marginbottom='.1cm', ) _add_style('sublist-paragraph', family='paragraph', fontsize='12pt', marginbottom='.1cm', ) _add_style('numbered-list-paragraph', family='paragraph', fontsize='12pt', marginbottom='.1cm', ) _add_style('normal-text', family='text', fontsize='12pt', ) _add_style('italic', family='text', fontstyle='italic', fontsize='12pt', ) _add_style('bold', family='text', fontweight='bold', fontsize='12pt', ) _add_style('url', family='text', fontsize='12pt', fontweight='bold', fontfamily='Courier', ) _add_style('inline-code', family='text', fontsize='10pt', fontweight='bold', fontfamily='Courier New', color='#555555', ) styles['_numbered_list'] = _numbered_style() return styles
[ "def", "default_styles", "(", ")", ":", "styles", "=", "{", "}", "def", "_add_style", "(", "name", ",", "*", "*", "kwargs", ")", ":", "styles", "[", "name", "]", "=", "_create_style", "(", "name", ",", "*", "*", "kwargs", ")", "_add_style", "(", "'heading-1'", ",", "family", "=", "'paragraph'", ",", "fontsize", "=", "'24pt'", ",", "fontweight", "=", "'bold'", ",", ")", "_add_style", "(", "'heading-2'", ",", "family", "=", "'paragraph'", ",", "fontsize", "=", "'22pt'", ",", "fontweight", "=", "'bold'", ",", ")", "_add_style", "(", "'heading-3'", ",", "family", "=", "'paragraph'", ",", "fontsize", "=", "'20pt'", ",", "fontweight", "=", "'bold'", ",", ")", "_add_style", "(", "'heading-4'", ",", "family", "=", "'paragraph'", ",", "fontsize", "=", "'18pt'", ",", "fontweight", "=", "'bold'", ",", ")", "_add_style", "(", "'heading-5'", ",", "family", "=", "'paragraph'", ",", "fontsize", "=", "'16pt'", ",", "fontweight", "=", "'bold'", ",", ")", "_add_style", "(", "'heading-6'", ",", "family", "=", "'paragraph'", ",", "fontsize", "=", "'14pt'", ",", "fontweight", "=", "'bold'", ",", ")", "_add_style", "(", "'normal-paragraph'", ",", "family", "=", "'paragraph'", ",", "fontsize", "=", "'12pt'", ",", "marginbottom", "=", "'0.25cm'", ",", ")", "_add_style", "(", "'code'", ",", "family", "=", "'paragraph'", ",", "fontsize", "=", "'10pt'", ",", "fontweight", "=", "'bold'", ",", "fontfamily", "=", "'Courier New'", ",", "color", "=", "'#555555'", ",", ")", "_add_style", "(", "'quote'", ",", "family", "=", "'paragraph'", ",", "fontsize", "=", "'12pt'", ",", "fontstyle", "=", "'italic'", ",", ")", "_add_style", "(", "'list-paragraph'", ",", "family", "=", "'paragraph'", ",", "fontsize", "=", "'12pt'", ",", "marginbottom", "=", "'.1cm'", ",", ")", "_add_style", "(", "'sublist-paragraph'", ",", "family", "=", "'paragraph'", ",", "fontsize", "=", "'12pt'", ",", "marginbottom", "=", "'.1cm'", ",", ")", "_add_style", "(", "'numbered-list-paragraph'", ",", "family", "=", "'paragraph'", ",", "fontsize", "=", "'12pt'", ",", "marginbottom", "=", "'.1cm'", ",", ")", "_add_style", "(", "'normal-text'", ",", "family", "=", "'text'", ",", "fontsize", "=", "'12pt'", ",", ")", "_add_style", "(", "'italic'", ",", "family", "=", "'text'", ",", "fontstyle", "=", "'italic'", ",", "fontsize", "=", "'12pt'", ",", ")", "_add_style", "(", "'bold'", ",", "family", "=", "'text'", ",", "fontweight", "=", "'bold'", ",", "fontsize", "=", "'12pt'", ",", ")", "_add_style", "(", "'url'", ",", "family", "=", "'text'", ",", "fontsize", "=", "'12pt'", ",", "fontweight", "=", "'bold'", ",", "fontfamily", "=", "'Courier'", ",", ")", "_add_style", "(", "'inline-code'", ",", "family", "=", "'text'", ",", "fontsize", "=", "'10pt'", ",", "fontweight", "=", "'bold'", ",", "fontfamily", "=", "'Courier New'", ",", "color", "=", "'#555555'", ",", ")", "styles", "[", "'_numbered_list'", "]", "=", "_numbered_style", "(", ")", "return", "styles" ]
Generate default ODF styles.
[ "Generate", "default", "ODF", "styles", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L166-L267
2,535
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._doc else: doc = path_or_doc assert isinstance(doc, OpenDocument), doc styles = {_style_name(style): style for style in doc.styles.childNodes} return styles
python
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, ODFDocument): doc = path_or_doc._doc else: doc = path_or_doc assert isinstance(doc, OpenDocument), doc styles = {_style_name(style): style for style in doc.styles.childNodes} return styles
[ "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", ",", "ODFDocument", ")", ":", "doc", "=", "path_or_doc", ".", "_doc", "else", ":", "doc", "=", "path_or_doc", "assert", "isinstance", "(", "doc", ",", "OpenDocument", ")", ",", "doc", "styles", "=", "{", "_style_name", "(", "style", ")", ":", "style", "for", "style", "in", "doc", ".", "styles", ".", "childNodes", "}", "return", "styles" ]
Return a dictionary of all styles contained in an ODF document.
[ "Return", "a", "dictionary", "of", "all", "styles", "contained", "in", "an", "ODF", "document", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L278-L290
2,536
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': if style in (None, 'normal-text'): return 'text' elif style == 'url': return 'link' else: return style elif tag == 'h': assert style is not None return style elif tag in ('list', 'list-item', 'line-break'): if style == '_numbered_list': return 'numbered-list' else: return tag elif tag == 's': return 'spaces' raise Exception("The tag '{0}' with style '{1}' hasn't " "been implemented.".format(tag, style))
python
def _item_type(item): 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': if style in (None, 'normal-text'): return 'text' elif style == 'url': return 'link' else: return style elif tag == 'h': assert style is not None return style elif tag in ('list', 'list-item', 'line-break'): if style == '_numbered_list': return 'numbered-list' else: return tag elif tag == 's': return 'spaces' raise Exception("The tag '{0}' with style '{1}' hasn't " "been implemented.".format(tag, style))
[ "def", "_item_type", "(", "item", ")", ":", "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'", ":", "if", "style", "in", "(", "None", ",", "'normal-text'", ")", ":", "return", "'text'", "elif", "style", "==", "'url'", ":", "return", "'link'", "else", ":", "return", "style", "elif", "tag", "==", "'h'", ":", "assert", "style", "is", "not", "None", "return", "style", "elif", "tag", "in", "(", "'list'", ",", "'list-item'", ",", "'line-break'", ")", ":", "if", "style", "==", "'_numbered_list'", ":", "return", "'numbered-list'", "else", ":", "return", "tag", "elif", "tag", "==", "'s'", ":", "return", "'spaces'", "raise", "Exception", "(", "\"The tag '{0}' with style '{1}' hasn't \"", "\"been implemented.\"", ".", "format", "(", "tag", ",", "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", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L742-L769
2,537
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): 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", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L358-L361
2,538
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): # 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", ")", "self", ".", "_doc", ".", "text", ".", "addElement", "(", "el", ")" ]
Add an element.
[ "Add", "an", "element", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L421-L426
2,539
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: return None return self._get_style_name(name)
python
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.attributes.get(style_field, None) if not name: return None return self._get_style_name(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", ".", "attributes", ".", "get", "(", "style_field", ",", "None", ")", "if", "not", "name", ":", "return", "None", "return", "self", ".", "_get_style_name", "(", "name", ")" ]
Return the style name of an element.
[ "Return", "the", "style", "name", "of", "an", "element", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L428-L437
2,540
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): # 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", "(", "*", "*", "kwargs", ")", "self", ".", "_containers", ".", "append", "(", "container", ")" ]
Append a new container.
[ "Append", "a", "new", "container", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L449-L455
2,541
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] else: parent = self._doc.text if not cancel: parent.addElement(container)
python
def end_container(self, cancel=None): if not self._containers: return container = self._containers.pop() if len(self._containers) >= 1: parent = self._containers[-1] else: parent = self._doc.text if not cancel: parent.addElement(container)
[ "def", "end_container", "(", "self", ",", "cancel", "=", "None", ")", ":", "if", "not", "self", ".", "_containers", ":", "return", "container", "=", "self", ".", "_containers", ".", "pop", "(", ")", "if", "len", "(", "self", ".", "_containers", ")", ">=", "1", ":", "parent", "=", "self", ".", "_containers", "[", "-", "1", "]", "else", ":", "parent", "=", "self", ".", "_doc", ".", "text", "if", "not", "cancel", ":", "parent", ".", "addElement", "(", "container", ")" ]
Finishes and registers the currently-active container, unless 'cancel' is True.
[ "Finishes", "and", "registers", "the", "currently", "-", "active", "container", "unless", "cancel", "is", "True", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L457-L468
2,542
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): 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", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L471-L475
2,543
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): # 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_container", "(", "P", ",", "stylename", "=", "stylename", ")" ]
Start a new paragraph.
[ "Start", "a", "new", "paragraph", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L477-L482
2,544
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): 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", "True" ]
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", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L491-L498
2,545
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)) container.addElement(S(c=n)) text = text[n:] elif ' ' in text: assert not text.startswith(' ') i = text.index(' ') container.addElement(Span(text=text[:i])) text = text[i:] else: container.addElement(Span(text=text)) text = ''
python
def _code_line(self, 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)) container.addElement(S(c=n)) text = text[n:] elif ' ' in text: assert not text.startswith(' ') i = text.index(' ') container.addElement(Span(text=text[:i])) text = text[i:] else: container.addElement(Span(text=text)) text = ''
[ "def", "_code_line", "(", "self", ",", "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", ")", ")", "container", ".", "addElement", "(", "S", "(", "c", "=", "n", ")", ")", "text", "=", "text", "[", "n", ":", "]", "elif", "' '", "in", "text", ":", "assert", "not", "text", ".", "startswith", "(", "' '", ")", "i", "=", "text", ".", "index", "(", "' '", ")", "container", ".", "addElement", "(", "Span", "(", "text", "=", "text", "[", ":", "i", "]", ")", ")", "text", "=", "text", "[", "i", ":", "]", "else", ":", "container", ".", "addElement", "(", "Span", "(", "text", "=", "text", ")", ")", "text", "=", "''" ]
Add a code line.
[ "Add", "a", "code", "line", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L507-L526
2,546
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() self._code_line(lines[-1])
python
def code(self, text, lang=None): # WARNING: lang is discarded currently. with self.paragraph(stylename='code'): lines = text.splitlines() for line in lines[:-1]: self._code_line(line) self.linebreak() self._code_line(lines[-1])
[ "def", "code", "(", "self", ",", "text", ",", "lang", "=", "None", ")", ":", "# WARNING: lang is discarded currently.", "with", "self", ".", "paragraph", "(", "stylename", "=", "'code'", ")", ":", "lines", "=", "text", ".", "splitlines", "(", ")", "for", "line", "in", "lines", "[", ":", "-", "1", "]", ":", "self", ".", "_code_line", "(", "line", ")", "self", ".", "linebreak", "(", ")", "self", ".", "_code_line", "(", "lines", "[", "-", "1", "]", ")" ]
Add a code block.
[ "Add", "a", "code", "block", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L528-L536
2,547
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 else 'sublist-paragraph')
python
def start_numbered_list(self): self._ordered = True self.start_container(List, stylename='_numbered_list') self.set_next_paragraph_style('numbered-list-paragraph' if self._item_level <= 0 else 'sublist-paragraph')
[ "def", "start_numbered_list", "(", "self", ")", ":", "self", ".", "_ordered", "=", "True", "self", ".", "start_container", "(", "List", ",", "stylename", "=", "'_numbered_list'", ")", "self", ".", "set_next_paragraph_style", "(", "'numbered-list-paragraph'", "if", "self", ".", "_item_level", "<=", "0", "else", "'sublist-paragraph'", ")" ]
Start a numbered list.
[ "Start", "a", "numbered", "list", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L558-L564
2,548
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): 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", "'sublist-paragraph'", ")" ]
Start a list.
[ "Start", "a", "list", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L572-L578
2,549
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=text)) else: container.addElement(Span(text=text))
python
def text(self, text, stylename=None): assert self._containers container = self._containers[-1] if stylename is not None: stylename = self._get_style_name(stylename) container.addElement(Span(stylename=stylename, text=text)) else: container.addElement(Span(text=text))
[ "def", "text", "(", "self", ",", "text", ",", "stylename", "=", "None", ")", ":", "assert", "self", ".", "_containers", "container", "=", "self", ".", "_containers", "[", "-", "1", "]", "if", "stylename", "is", "not", "None", ":", "stylename", "=", "self", ".", "_get_style_name", "(", "stylename", ")", "container", ".", "addElement", "(", "Span", "(", "stylename", "=", "stylename", ",", "text", "=", "text", ")", ")", "else", ":", "container", ".", "addElement", "(", "Span", "(", "text", "=", "text", ")", ")" ]
Add text within the current container.
[ "Add", "text", "within", "the", "current", "container", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L617-L625
2,550
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: out = output.get('data', {}).get('text/plain', []) out = _ensure_string(out) # HACK: skip <matplotlib ...> outputs. if out.startswith('<matplotlib'): continue text_outputs.append(out) return stdout + '\n'.join(text_outputs).rstrip()
python
def _cell_output(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: out = output.get('data', {}).get('text/plain', []) out = _ensure_string(out) # HACK: skip <matplotlib ...> outputs. if out.startswith('<matplotlib'): continue text_outputs.append(out) return stdout + '\n'.join(text_outputs).rstrip()
[ "def", "_cell_output", "(", "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", ":", "out", "=", "output", ".", "get", "(", "'data'", ",", "{", "}", ")", ".", "get", "(", "'text/plain'", ",", "[", "]", ")", "out", "=", "_ensure_string", "(", "out", ")", "# HACK: skip <matplotlib ...> outputs.", "if", "out", ".", "startswith", "(", "'<matplotlib'", ")", ":", "continue", "text_outputs", ".", "append", "(", "out", ")", "return", "stdout", "+", "'\\n'", ".", "join", "(", "text_outputs", ")", ".", "rstrip", "(", ")" ]
Return the output of an ipynb cell.
[ "Return", "the", "output", "of", "an", "ipynb", "cell", "." ]
d87c9ebc59d67fe78b0139ee00e0e5307682e303
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/notebook.py#L33-L48
2,551
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)) return self.adb_shell('dumpsys {0}'.format(service))
python
def _dump(self, service, grep=None): if grep: return self.adb_shell('dumpsys {0} | grep "{1}"'.format(service, grep)) return self.adb_shell('dumpsys {0}'.format(service))
[ "def", "_dump", "(", "self", ",", "service", ",", "grep", "=", "None", ")", ":", "if", "grep", ":", "return", "self", ".", "adb_shell", "(", "'dumpsys {0} | grep \"{1}\"'", ".", "format", "(", "service", ",", "grep", ")", ")", "return", "self", ".", "adb_shell", "(", "'dumpsys {0}'", ".", "format", "(", "service", ")", ")" ]
Perform a service dump. :param service: Service to dump. :param grep: Grep for this string. :returns: Dump, optionally grepped.
[ "Perform", "a", "service", "dump", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L226-L235
2,552
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=grep) if not dump_grep: return False return dump_grep.strip().find(search) > -1
python
def _dump_has(self, service, grep, search): dump_grep = self._dump(service, grep=grep) if not dump_grep: return False return dump_grep.strip().find(search) > -1
[ "def", "_dump_has", "(", "self", ",", "service", ",", "grep", ",", "search", ")", ":", "dump_grep", "=", "self", ".", "_dump", "(", "service", ",", "grep", "=", "grep", ")", "if", "not", "dump_grep", ":", "return", "False", "return", "dump_grep", ".", "strip", "(", ")", ".", "find", "(", "search", ")", ">", "-", "1" ]
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", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L237-L250
2,553
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: for bad_line in ps: # The splitting of the StreamingShell doesn't always work # this is to ensure that we get only one line for line in bad_line.splitlines(): if search in line: result.append(line.strip().rsplit(' ', 1)[-1]) return result except InvalidChecksumError as e: print(e) self.connect() raise IOError
python
def _ps(self, search=''): if not self.available: return result = [] ps = self.adb_streaming_shell('ps') try: for bad_line in ps: # The splitting of the StreamingShell doesn't always work # this is to ensure that we get only one line for line in bad_line.splitlines(): if search in line: result.append(line.strip().rsplit(' ', 1)[-1]) return result except InvalidChecksumError as e: print(e) self.connect() raise IOError
[ "def", "_ps", "(", "self", ",", "search", "=", "''", ")", ":", "if", "not", "self", ".", "available", ":", "return", "result", "=", "[", "]", "ps", "=", "self", ".", "adb_streaming_shell", "(", "'ps'", ")", "try", ":", "for", "bad_line", "in", "ps", ":", "# The splitting of the StreamingShell doesn't always work", "# this is to ensure that we get only one line", "for", "line", "in", "bad_line", ".", "splitlines", "(", ")", ":", "if", "search", "in", "line", ":", "result", ".", "append", "(", "line", ".", "strip", "(", ")", ".", "rsplit", "(", "' '", ",", "1", ")", "[", "-", "1", "]", ")", "return", "result", "except", "InvalidChecksumError", "as", "e", ":", "print", "(", "e", ")", "self", ".", "connect", "(", ")", "raise", "IOError" ]
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", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L259-L280
2,554
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.acquire(**LOCK_KWARGS) try: if not self.adb_server_ip: # python-adb try: if self.adbkey: signer = Signer(self.adbkey) # Connect to the device self._adb = adb_commands.AdbCommands().ConnectDevice(serial=self.host, rsa_keys=[signer], default_timeout_ms=9000) else: self._adb = adb_commands.AdbCommands().ConnectDevice(serial=self.host, default_timeout_ms=9000) # ADB connection successfully established self._available = True except socket_error as serr: if self._available or always_log_errors: if serr.strerror is None: serr.strerror = "Timed out trying to connect to ADB device." logging.warning("Couldn't connect to host: %s, error: %s", self.host, serr.strerror) # ADB connection attempt failed self._adb = None self._available = False finally: return self._available else: # pure-python-adb try: self._adb_client = AdbClient(host=self.adb_server_ip, port=self.adb_server_port) self._adb_device = self._adb_client.device(self.host) self._available = bool(self._adb_device) except: self._available = False finally: return self._available finally: self._adb_lock.release()
python
def connect(self, always_log_errors=True): self._adb_lock.acquire(**LOCK_KWARGS) try: if not self.adb_server_ip: # python-adb try: if self.adbkey: signer = Signer(self.adbkey) # Connect to the device self._adb = adb_commands.AdbCommands().ConnectDevice(serial=self.host, rsa_keys=[signer], default_timeout_ms=9000) else: self._adb = adb_commands.AdbCommands().ConnectDevice(serial=self.host, default_timeout_ms=9000) # ADB connection successfully established self._available = True except socket_error as serr: if self._available or always_log_errors: if serr.strerror is None: serr.strerror = "Timed out trying to connect to ADB device." logging.warning("Couldn't connect to host: %s, error: %s", self.host, serr.strerror) # ADB connection attempt failed self._adb = None self._available = False finally: return self._available else: # pure-python-adb try: self._adb_client = AdbClient(host=self.adb_server_ip, port=self.adb_server_port) self._adb_device = self._adb_client.device(self.host) self._available = bool(self._adb_device) except: self._available = False finally: return self._available finally: self._adb_lock.release()
[ "def", "connect", "(", "self", ",", "always_log_errors", "=", "True", ")", ":", "self", ".", "_adb_lock", ".", "acquire", "(", "*", "*", "LOCK_KWARGS", ")", "try", ":", "if", "not", "self", ".", "adb_server_ip", ":", "# python-adb", "try", ":", "if", "self", ".", "adbkey", ":", "signer", "=", "Signer", "(", "self", ".", "adbkey", ")", "# Connect to the device", "self", ".", "_adb", "=", "adb_commands", ".", "AdbCommands", "(", ")", ".", "ConnectDevice", "(", "serial", "=", "self", ".", "host", ",", "rsa_keys", "=", "[", "signer", "]", ",", "default_timeout_ms", "=", "9000", ")", "else", ":", "self", ".", "_adb", "=", "adb_commands", ".", "AdbCommands", "(", ")", ".", "ConnectDevice", "(", "serial", "=", "self", ".", "host", ",", "default_timeout_ms", "=", "9000", ")", "# ADB connection successfully established", "self", ".", "_available", "=", "True", "except", "socket_error", "as", "serr", ":", "if", "self", ".", "_available", "or", "always_log_errors", ":", "if", "serr", ".", "strerror", "is", "None", ":", "serr", ".", "strerror", "=", "\"Timed out trying to connect to ADB device.\"", "logging", ".", "warning", "(", "\"Couldn't connect to host: %s, error: %s\"", ",", "self", ".", "host", ",", "serr", ".", "strerror", ")", "# ADB connection attempt failed", "self", ".", "_adb", "=", "None", "self", ".", "_available", "=", "False", "finally", ":", "return", "self", ".", "_available", "else", ":", "# pure-python-adb", "try", ":", "self", ".", "_adb_client", "=", "AdbClient", "(", "host", "=", "self", ".", "adb_server_ip", ",", "port", "=", "self", ".", "adb_server_port", ")", "self", ".", "_adb_device", "=", "self", ".", "_adb_client", ".", "device", "(", "self", ".", "host", ")", "self", ".", "_available", "=", "bool", "(", "self", ".", "_adb_device", ")", "except", ":", "self", ".", "_available", "=", "False", "finally", ":", "return", "self", ".", "_available", "finally", ":", "self", ".", "_adb_lock", ".", "release", "(", ")" ]
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", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L299-L350
2,555
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 running_apps: the running apps """ # The `screen_on`, `awake`, `wake_lock_size`, `current_app`, and `running_apps` properties. screen_on, awake, wake_lock_size, _current_app, running_apps = self.get_properties(get_running_apps=get_running_apps, lazy=True) # Check if device is off. if not screen_on: state = STATE_OFF current_app = None running_apps = None # Check if screen saver is on. elif not awake: state = STATE_IDLE current_app = None running_apps = None else: # Get the current app. if isinstance(_current_app, dict) and 'package' in _current_app: current_app = _current_app['package'] else: current_app = None # Get the running apps. if running_apps is None and current_app: running_apps = [current_app] # Get the state. # TODO: determine the state differently based on the `current_app`. if current_app in [PACKAGE_LAUNCHER, PACKAGE_SETTINGS]: state = STATE_STANDBY # Amazon Video elif current_app == AMAZON_VIDEO: if wake_lock_size == 5: state = STATE_PLAYING else: # wake_lock_size == 2 state = STATE_PAUSED # Netflix elif current_app == NETFLIX: if wake_lock_size > 3: state = STATE_PLAYING else: state = STATE_PAUSED # Check if `wake_lock_size` is 1 (device is playing). elif wake_lock_size == 1: state = STATE_PLAYING # Otherwise, device is paused. else: state = STATE_PAUSED return state, current_app, running_apps
python
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 = self.get_properties(get_running_apps=get_running_apps, lazy=True) # Check if device is off. if not screen_on: state = STATE_OFF current_app = None running_apps = None # Check if screen saver is on. elif not awake: state = STATE_IDLE current_app = None running_apps = None else: # Get the current app. if isinstance(_current_app, dict) and 'package' in _current_app: current_app = _current_app['package'] else: current_app = None # Get the running apps. if running_apps is None and current_app: running_apps = [current_app] # Get the state. # TODO: determine the state differently based on the `current_app`. if current_app in [PACKAGE_LAUNCHER, PACKAGE_SETTINGS]: state = STATE_STANDBY # Amazon Video elif current_app == AMAZON_VIDEO: if wake_lock_size == 5: state = STATE_PLAYING else: # wake_lock_size == 2 state = STATE_PAUSED # Netflix elif current_app == NETFLIX: if wake_lock_size > 3: state = STATE_PLAYING else: state = STATE_PAUSED # Check if `wake_lock_size` is 1 (device is playing). elif wake_lock_size == 1: state = STATE_PLAYING # Otherwise, device is paused. else: state = STATE_PAUSED return state, current_app, running_apps
[ "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", "=", "self", ".", "get_properties", "(", "get_running_apps", "=", "get_running_apps", ",", "lazy", "=", "True", ")", "# Check if device is off.", "if", "not", "screen_on", ":", "state", "=", "STATE_OFF", "current_app", "=", "None", "running_apps", "=", "None", "# Check if screen saver is on.", "elif", "not", "awake", ":", "state", "=", "STATE_IDLE", "current_app", "=", "None", "running_apps", "=", "None", "else", ":", "# Get the current app.", "if", "isinstance", "(", "_current_app", ",", "dict", ")", "and", "'package'", "in", "_current_app", ":", "current_app", "=", "_current_app", "[", "'package'", "]", "else", ":", "current_app", "=", "None", "# Get the running apps.", "if", "running_apps", "is", "None", "and", "current_app", ":", "running_apps", "=", "[", "current_app", "]", "# Get the state.", "# TODO: determine the state differently based on the `current_app`.", "if", "current_app", "in", "[", "PACKAGE_LAUNCHER", ",", "PACKAGE_SETTINGS", "]", ":", "state", "=", "STATE_STANDBY", "# Amazon Video", "elif", "current_app", "==", "AMAZON_VIDEO", ":", "if", "wake_lock_size", "==", "5", ":", "state", "=", "STATE_PLAYING", "else", ":", "# wake_lock_size == 2", "state", "=", "STATE_PAUSED", "# Netflix", "elif", "current_app", "==", "NETFLIX", ":", "if", "wake_lock_size", ">", "3", ":", "state", "=", "STATE_PLAYING", "else", ":", "state", "=", "STATE_PAUSED", "# Check if `wake_lock_size` is 1 (device is playing).", "elif", "wake_lock_size", "==", "1", ":", "state", "=", "STATE_PLAYING", "# Otherwise, device is paused.", "else", ":", "state", "=", "STATE_PAUSED", "return", "state", ",", "current_app", ",", "running_apps" ]
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", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L357-L419
2,556
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): 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", "STATE_ON", "return", "STATE_OFF" ]
Informs if application is running.
[ "Informs", "if", "application", "is", "running", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L426-L432
2,557
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 # Check if screen saver is on. if not self.awake: return STATE_IDLE # Check if the launcher is active. if self.launcher or self.settings: return STATE_STANDBY # Check for a wake lock (device is playing). if self.wake_lock: return STATE_PLAYING # Otherwise, device is paused. return STATE_PAUSED
python
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 is on. if not self.awake: return STATE_IDLE # Check if the launcher is active. if self.launcher or self.settings: return STATE_STANDBY # Check for a wake lock (device is playing). if self.wake_lock: return STATE_PLAYING # Otherwise, device is paused. return STATE_PAUSED
[ "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 is on.", "if", "not", "self", ".", "awake", ":", "return", "STATE_IDLE", "# Check if the launcher is active.", "if", "self", ".", "launcher", "or", "self", ".", "settings", ":", "return", "STATE_STANDBY", "# Check for a wake lock (device is playing).", "if", "self", ".", "wake_lock", ":", "return", "STATE_PLAYING", "# Otherwise, device is paused.", "return", "STATE_PAUSED" ]
Compute and return the device state. :returns: Device state.
[ "Compute", "and", "return", "the", "device", "state", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L448-L469
2,558
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() # make sure the device is available try: # case 1: the device is currently available if any([self.host in dev.get_serial_no() for dev in adb_devices]): if not self._available: self._available = True return True # case 2: the device is not currently available if self._available: logging.error('ADB server is not connected to the device.') self._available = False return False except RuntimeError: if self._available: logging.error('ADB device is unavailable; encountered an error when searching for device.') self._available = False return False except RuntimeError: if self._available: logging.error('ADB server is unavailable.') self._available = False return False
python
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._adb_client.devices() # make sure the device is available try: # case 1: the device is currently available if any([self.host in dev.get_serial_no() for dev in adb_devices]): if not self._available: self._available = True return True # case 2: the device is not currently available if self._available: logging.error('ADB server is not connected to the device.') self._available = False return False except RuntimeError: if self._available: logging.error('ADB device is unavailable; encountered an error when searching for device.') self._available = False return False except RuntimeError: if self._available: logging.error('ADB server is unavailable.') self._available = False return False
[ "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", ".", "_adb_client", ".", "devices", "(", ")", "# make sure the device is available", "try", ":", "# case 1: the device is currently available", "if", "any", "(", "[", "self", ".", "host", "in", "dev", ".", "get_serial_no", "(", ")", "for", "dev", "in", "adb_devices", "]", ")", ":", "if", "not", "self", ".", "_available", ":", "self", ".", "_available", "=", "True", "return", "True", "# case 2: the device is not currently available", "if", "self", ".", "_available", ":", "logging", ".", "error", "(", "'ADB server is not connected to the device.'", ")", "self", ".", "_available", "=", "False", "return", "False", "except", "RuntimeError", ":", "if", "self", ".", "_available", ":", "logging", ".", "error", "(", "'ADB device is unavailable; encountered an error when searching for device.'", ")", "self", ".", "_available", "=", "False", "return", "False", "except", "RuntimeError", ":", "if", "self", ".", "_available", ":", "logging", ".", "error", "(", "'ADB server is unavailable.'", ")", "self", ".", "_available", "=", "False", "return", "False" ]
Check whether the ADB connection is intact.
[ "Check", "whether", "the", "ADB", "connection", "is", "intact", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L472-L507
2,559
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): 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", "line", "in", "ps", ".", "splitlines", "(", ")", "if", "line", ".", "strip", "(", ")", "]", "return", "[", "]" ]
Return a list of running user applications.
[ "Return", "a", "list", "of", "running", "user", "applications", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L510-L515
2,560
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 successfully found if matches: (pkg, activity) = matches.group("package", "activity") return {"package": pkg, "activity": activity} # case 2: current app could not be found logging.warning("Couldn't get current app, reply was %s", current_focus) return None
python
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", "") matches = WINDOW_REGEX.search(current_focus) # case 1: current app was successfully found if matches: (pkg, activity) = matches.group("package", "activity") return {"package": pkg, "activity": activity} # case 2: current app could not be found logging.warning("Couldn't get current app, reply was %s", current_focus) return None
[ "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\"", ",", "\"\"", ")", "matches", "=", "WINDOW_REGEX", ".", "search", "(", "current_focus", ")", "# case 1: current app was successfully found", "if", "matches", ":", "(", "pkg", ",", "activity", ")", "=", "matches", ".", "group", "(", "\"package\"", ",", "\"activity\"", ")", "return", "{", "\"package\"", ":", "pkg", ",", "\"activity\"", ":", "activity", "}", "# case 2: current app could not be found", "logging", ".", "warning", "(", "\"Couldn't get current app, reply was %s\"", ",", "current_focus", ")", "return", "None" ]
Return the current app.
[ "Return", "the", "current", "app", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L518-L534
2,561
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): 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", "]", ".", "strip", "(", ")", ")" ]
Get the size of the current wake lock.
[ "Get", "the", "size", "of", "the", "current", "wake", "lock", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L552-L557
2,562
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) + " && " + AWAKE_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " + WAKE_LOCK_SIZE_CMD + " && " + CURRENT_APP_CMD + " && " + RUNNING_APPS_CMD) else: output = self.adb_shell(SCREEN_ON_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " + AWAKE_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " + WAKE_LOCK_SIZE_CMD + " && " + CURRENT_APP_CMD) # ADB command was unsuccessful if output is None: return None, None, None, None, None # `screen_on` property if not output: return False, False, -1, None, None screen_on = output[0] == '1' # `awake` property if len(output) < 2: return screen_on, False, -1, None, None awake = output[1] == '1' lines = output.strip().splitlines() # `wake_lock_size` property if len(lines[0]) < 3: return screen_on, awake, -1, None, None wake_lock_size = int(lines[0].split("=")[1].strip()) # `current_app` property if len(lines) < 2: return screen_on, awake, wake_lock_size, None, None matches = WINDOW_REGEX.search(lines[1]) if matches: # case 1: current app was successfully found (pkg, activity) = matches.group("package", "activity") current_app = {"package": pkg, "activity": activity} else: # case 2: current app could not be found current_app = None # `running_apps` property if not get_running_apps or len(lines) < 3: return screen_on, awake, wake_lock_size, current_app, None running_apps = [line.strip().rsplit(' ', 1)[-1] for line in lines[2:] if line.strip()] return screen_on, awake, wake_lock_size, current_app, running_apps
python
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 SUCCESS1_FAILURE0) + " && " + AWAKE_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " + WAKE_LOCK_SIZE_CMD + " && " + CURRENT_APP_CMD + " && " + RUNNING_APPS_CMD) else: output = self.adb_shell(SCREEN_ON_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " + AWAKE_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " + WAKE_LOCK_SIZE_CMD + " && " + CURRENT_APP_CMD) # ADB command was unsuccessful if output is None: return None, None, None, None, None # `screen_on` property if not output: return False, False, -1, None, None screen_on = output[0] == '1' # `awake` property if len(output) < 2: return screen_on, False, -1, None, None awake = output[1] == '1' lines = output.strip().splitlines() # `wake_lock_size` property if len(lines[0]) < 3: return screen_on, awake, -1, None, None wake_lock_size = int(lines[0].split("=")[1].strip()) # `current_app` property if len(lines) < 2: return screen_on, awake, wake_lock_size, None, None matches = WINDOW_REGEX.search(lines[1]) if matches: # case 1: current app was successfully found (pkg, activity) = matches.group("package", "activity") current_app = {"package": pkg, "activity": activity} else: # case 2: current app could not be found current_app = None # `running_apps` property if not get_running_apps or len(lines) < 3: return screen_on, awake, wake_lock_size, current_app, None running_apps = [line.strip().rsplit(' ', 1)[-1] for line in lines[2:] if line.strip()] return screen_on, awake, wake_lock_size, current_app, running_apps
[ "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", "SUCCESS1_FAILURE0", ")", "+", "\" && \"", "+", "AWAKE_CMD", "+", "(", "SUCCESS1", "if", "lazy", "else", "SUCCESS1_FAILURE0", ")", "+", "\" && \"", "+", "WAKE_LOCK_SIZE_CMD", "+", "\" && \"", "+", "CURRENT_APP_CMD", "+", "\" && \"", "+", "RUNNING_APPS_CMD", ")", "else", ":", "output", "=", "self", ".", "adb_shell", "(", "SCREEN_ON_CMD", "+", "(", "SUCCESS1", "if", "lazy", "else", "SUCCESS1_FAILURE0", ")", "+", "\" && \"", "+", "AWAKE_CMD", "+", "(", "SUCCESS1", "if", "lazy", "else", "SUCCESS1_FAILURE0", ")", "+", "\" && \"", "+", "WAKE_LOCK_SIZE_CMD", "+", "\" && \"", "+", "CURRENT_APP_CMD", ")", "# ADB command was unsuccessful", "if", "output", "is", "None", ":", "return", "None", ",", "None", ",", "None", ",", "None", ",", "None", "# `screen_on` property", "if", "not", "output", ":", "return", "False", ",", "False", ",", "-", "1", ",", "None", ",", "None", "screen_on", "=", "output", "[", "0", "]", "==", "'1'", "# `awake` property", "if", "len", "(", "output", ")", "<", "2", ":", "return", "screen_on", ",", "False", ",", "-", "1", ",", "None", ",", "None", "awake", "=", "output", "[", "1", "]", "==", "'1'", "lines", "=", "output", ".", "strip", "(", ")", ".", "splitlines", "(", ")", "# `wake_lock_size` property", "if", "len", "(", "lines", "[", "0", "]", ")", "<", "3", ":", "return", "screen_on", ",", "awake", ",", "-", "1", ",", "None", ",", "None", "wake_lock_size", "=", "int", "(", "lines", "[", "0", "]", ".", "split", "(", "\"=\"", ")", "[", "1", "]", ".", "strip", "(", ")", ")", "# `current_app` property", "if", "len", "(", "lines", ")", "<", "2", ":", "return", "screen_on", ",", "awake", ",", "wake_lock_size", ",", "None", ",", "None", "matches", "=", "WINDOW_REGEX", ".", "search", "(", "lines", "[", "1", "]", ")", "if", "matches", ":", "# case 1: current app was successfully found", "(", "pkg", ",", "activity", ")", "=", "matches", ".", "group", "(", "\"package\"", ",", "\"activity\"", ")", "current_app", "=", "{", "\"package\"", ":", "pkg", ",", "\"activity\"", ":", "activity", "}", "else", ":", "# case 2: current app could not be found", "current_app", "=", "None", "# `running_apps` property", "if", "not", "get_running_apps", "or", "len", "(", "lines", ")", "<", "3", ":", "return", "screen_on", ",", "awake", ",", "wake_lock_size", ",", "current_app", ",", "None", "running_apps", "=", "[", "line", ".", "strip", "(", ")", ".", "rsplit", "(", "' '", ",", "1", ")", "[", "-", "1", "]", "for", "line", "in", "lines", "[", "2", ":", "]", "if", "line", ".", "strip", "(", ")", "]", "return", "screen_on", ",", "awake", ",", "wake_lock_size", ",", "current_app", ",", "running_apps" ]
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", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L569-L623
2,563
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("A valid device identifier contains " "only ascii word characters or dashes. " "Device '%s' not added.", device_id) return valid
python
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. " "Device '%s' not added.", device_id) return valid
[ "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. \"", "\"Device '%s' not added.\"", ",", "device_id", ")", "return", "valid" ]
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", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L50-L63
2,564
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_server_ip: the IP address for the ADB server :param adb_server_port: the port for the ADB server :returns: Added successfully or not. """ valid = is_valid_device_id(device_id) and is_valid_host(host) if valid: devices[device_id] = FireTV(str(host), str(adbkey), str(adb_server_ip), str(adb_server_port)) return valid
python
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) if valid: devices[device_id] = FireTV(str(host), str(adbkey), str(adb_server_ip), str(adb_server_port)) return valid
[ "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", ")", "if", "valid", ":", "devices", "[", "device_id", "]", "=", "FireTV", "(", "str", "(", "host", ")", ",", "str", "(", "adbkey", ")", ",", "str", "(", "adb_server_ip", ")", ",", "str", "(", "adb_server_port", ")", ")", "return", "valid" ]
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 the ADB server :returns: Added successfully or not.
[ "Add", "a", "device", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L78-L93
2,565
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 'device_id' in req and 'host' in req: success = add(req['device_id'], req['host'], req.get('adbkey', ''), req.get('adb_server_ip', ''), req.get('adb_server_port', 5037)) return jsonify(success=success)
python
def add_device(): req = request.get_json() success = False if 'device_id' in req and 'host' in req: success = add(req['device_id'], req['host'], req.get('adbkey', ''), req.get('adb_server_ip', ''), req.get('adb_server_port', 5037)) return jsonify(success=success)
[ "def", "add_device", "(", ")", ":", "req", "=", "request", ".", "get_json", "(", ")", "success", "=", "False", "if", "'device_id'", "in", "req", "and", "'host'", "in", "req", ":", "success", "=", "add", "(", "req", "[", "'device_id'", "]", ",", "req", "[", "'host'", "]", ",", "req", ".", "get", "(", "'adbkey'", ",", "''", ")", ",", "req", ".", "get", "(", "'adb_server_ip'", ",", "''", ")", ",", "req", ".", "get", "(", "'adb_server_port'", ",", "5037", ")", ")", "return", "jsonify", "(", "success", "=", "success", ")" ]
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", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L97-L113
2,566
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(): 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'", ":", "device", ".", "state", "}", "return", "jsonify", "(", "devices", "=", "output", ")" ]
List devices via HTTP GET.
[ "List", "devices", "via", "HTTP", "GET", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L117-L125
2,567
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): 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", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L129-L133
2,568
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): 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_id", "]", ".", "current_app", "if", "current", "is", "None", ":", "abort", "(", "404", ")", "return", "jsonify", "(", "current_app", "=", "current", ")" ]
Get currently running app.
[ "Get", "currently", "running", "app", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L137-L148
2,569
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): 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", "=", "devices", "[", "device_id", "]", ".", "running_apps", ")" ]
Get running apps via HTTP GET.
[ "Get", "running", "apps", "via", "HTTP", "GET", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L152-L158
2,570
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 jsonify(state=app_state, status=app_state)
python
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_id not in devices: abort(404) app_state = devices[device_id].app_state(app_id) return jsonify(state=app_state, status=app_state)
[ "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_id", "not", "in", "devices", ":", "abort", "(", "404", ")", "app_state", "=", "devices", "[", "device_id", "]", ".", "app_state", "(", "app_id", ")", "return", "jsonify", "(", "state", "=", "app_state", ",", "status", "=", "app_state", ")" ]
Get the state of the requested app
[ "Get", "the", "state", "of", "the", "requested", "app" ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L162-L171
2,571
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=success)
python
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(input_cmd): input_cmd() success = True return jsonify(success=success)
[ "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", "(", "input_cmd", ")", ":", "input_cmd", "(", ")", "success", "=", "True", "return", "jsonify", "(", "success", "=", "success", ")" ]
Initiate device action via HTTP GET.
[ "Initiate", "device", "action", "via", "HTTP", "GET", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L180-L188
2,572
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) return jsonify(success=success)
python
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 not in devices: abort(404) success = devices[device_id].launch_app(app_id) return jsonify(success=success)
[ "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", "not", "in", "devices", ":", "abort", "(", "404", ")", "success", "=", "devices", "[", "device_id", "]", ".", "launch_app", "(", "app_id", ")", "return", "jsonify", "(", "success", "=", "success", ")" ]
Starts an app with corresponding package name
[ "Starts", "an", "app", "with", "corresponding", "package", "name" ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L192-L202
2,573
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 jsonify(success=success)
python
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 not in devices: abort(404) success = devices[device_id].stop_app(app_id) return jsonify(success=success)
[ "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", "not", "in", "devices", ":", "abort", "(", "404", ")", "success", "=", "devices", "[", "device_id", "]", ".", "stop_app", "(", "app_id", ")", "return", "jsonify", "(", "success", "=", "success", ")" ]
stops an app with corresponding package name
[ "stops", "an", "app", "with", "corresponding", "package", "name" ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L206-L216
2,574
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): 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", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L220-L226
2,575
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): 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", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L229-L234
2,576
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') if config['devices'][device]['host'] == args.default: raise ValueError('host set in default param must not be defined in config') add(device, config['devices'][device]['host'], config['devices'][device].get('adbkey', ''), config['devices'][device].get('adb_server_ip', ''), config['devices'][device].get('adb_server_port', 5037))
python
def _add_devices_from_config(args): 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') if config['devices'][device]['host'] == args.default: raise ValueError('host set in default param must not be defined in config') add(device, config['devices'][device]['host'], config['devices'][device].get('adbkey', ''), config['devices'][device].get('adb_server_ip', ''), config['devices'][device].get('adb_server_port', 5037))
[ "def", "_add_devices_from_config", "(", "args", ")", ":", "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'", ")", "if", "config", "[", "'devices'", "]", "[", "device", "]", "[", "'host'", "]", "==", "args", ".", "default", ":", "raise", "ValueError", "(", "'host set in default param must not be defined in config'", ")", "add", "(", "device", ",", "config", "[", "'devices'", "]", "[", "device", "]", "[", "'host'", "]", ",", "config", "[", "'devices'", "]", "[", "device", "]", ".", "get", "(", "'adbkey'", ",", "''", ")", ",", "config", "[", "'devices'", "]", "[", "device", "]", ".", "get", "(", "'adb_server_ip'", ",", "''", ")", ",", "config", "[", "'devices'", "]", "[", "device", "]", ".", "get", "(", "'adb_server_port'", ",", "5037", ")", ")" ]
Add devices from config.
[ "Add", "devices", "from", "config", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L237-L247
2,577
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', type=str, help='Path to config file') args = parser.parse_args() if args.config: _add_devices_from_config(args) if args.default and not add('default', args.default): exit('invalid hostname') app.run(host='0.0.0.0', port=args.port)
python
def main(): 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', type=str, help='Path to config file') args = parser.parse_args() if args.config: _add_devices_from_config(args) if args.default and not add('default', args.default): exit('invalid hostname') app.run(host='0.0.0.0', port=args.port)
[ "def", "main", "(", ")", ":", "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'", ",", "type", "=", "str", ",", "help", "=", "'Path to config file'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "args", ".", "config", ":", "_add_devices_from_config", "(", "args", ")", "if", "args", ".", "default", "and", "not", "add", "(", "'default'", ",", "args", ".", "default", ")", ":", "exit", "(", "'invalid hostname'", ")", "app", ".", "run", "(", "host", "=", "'0.0.0.0'", ",", "port", "=", "args", ".", "port", ")" ]
Set up the server.
[ "Set", "up", "the", "server", "." ]
3dd953376c0d5af502e775ae14ed0afe03224781
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L250-L263
2,578
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): 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", "." ]
f7e1c1bb1b7aea401e0d09219610cc690acd5476
https://github.com/areebbeigh/profanityfilter/blob/f7e1c1bb1b7aea401e0d09219610cc690acd5476/profanityfilter/profanityfilter.py#L43-L46
2,579
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 w in self._censor_list] profane_words.extend(self._extra_censor_list) profane_words.extend([inflection.pluralize(word) for word in profane_words]) profane_words = list(set(profane_words)) # We sort the list based on decreasing word length so that words like # 'fu' aren't substituted before 'fuck' if no_word_boundaries = true profane_words.sort(key=len) profane_words.reverse() return profane_words
python
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 list.copy() else: profane_words = [w for w in self._censor_list] profane_words.extend(self._extra_censor_list) profane_words.extend([inflection.pluralize(word) for word in profane_words]) profane_words = list(set(profane_words)) # We sort the list based on decreasing word length so that words like # 'fu' aren't substituted before 'fuck' if no_word_boundaries = true profane_words.sort(key=len) profane_words.reverse() return profane_words
[ "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 list.copy()", "else", ":", "profane_words", "=", "[", "w", "for", "w", "in", "self", ".", "_censor_list", "]", "profane_words", ".", "extend", "(", "self", ".", "_extra_censor_list", ")", "profane_words", ".", "extend", "(", "[", "inflection", ".", "pluralize", "(", "word", ")", "for", "word", "in", "profane_words", "]", ")", "profane_words", "=", "list", "(", "set", "(", "profane_words", ")", ")", "# We sort the list based on decreasing word length so that words like", "# 'fu' aren't substituted before 'fuck' if no_word_boundaries = true", "profane_words", ".", "sort", "(", "key", "=", "len", ")", "profane_words", ".", "reverse", "(", ")", "return", "profane_words" ]
Returns all profane words currently in use.
[ "Returns", "all", "profane", "words", "currently", "in", "use", "." ]
f7e1c1bb1b7aea401e0d09219610cc690acd5476
https://github.com/areebbeigh/profanityfilter/blob/f7e1c1bb1b7aea401e0d09219610cc690acd5476/profanityfilter/profanityfilter.py#L79-L97
2,580
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'\b{0}\b' regex_string = regex_string.format(word) regex = re.compile(regex_string, re.IGNORECASE) res = regex.sub(self._censor_char * len(word), res) return res
python
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}' if self._no_word_boundaries else r'\b{0}\b' regex_string = regex_string.format(word) regex = re.compile(regex_string, re.IGNORECASE) res = regex.sub(self._censor_char * len(word), res) return res
[ "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}'", "if", "self", ".", "_no_word_boundaries", "else", "r'\\b{0}\\b'", "regex_string", "=", "regex_string", ".", "format", "(", "word", ")", "regex", "=", "re", ".", "compile", "(", "regex_string", ",", "re", ".", "IGNORECASE", ")", "res", "=", "regex", ".", "sub", "(", "self", ".", "_censor_char", "*", "len", "(", "word", ")", ",", "res", ")", "return", "res" ]
Returns input_text with any profane words censored.
[ "Returns", "input_text", "with", "any", "profane", "words", "censored", "." ]
f7e1c1bb1b7aea401e0d09219610cc690acd5476
https://github.com/areebbeigh/profanityfilter/blob/f7e1c1bb1b7aea401e0d09219610cc690acd5476/profanityfilter/profanityfilter.py#L105-L117
2,581
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 messages """ chunks = [] while data: info = SMB2NetworkInterfaceInfo() data = info.unpack(data) chunks.append(info) return chunks
python
def unpack_multiple(data): chunks = [] while data: info = SMB2NetworkInterfaceInfo() data = info.unpack(data) chunks.append(info) return chunks
[ "def", "unpack_multiple", "(", "data", ")", ":", "chunks", "=", "[", "]", "while", "data", ":", "info", "=", "SMB2NetworkInterfaceInfo", "(", ")", "data", "=", "info", ".", "unpack", "(", "data", ")", "chunks", ".", "append", "(", "info", ")", "return", "chunks" ]
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", "." ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/ioctl.py#L419-L434
2,582
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_DURABLE_HANDLE_REQUEST: SMB2CreateDurableHandleResponse(), CreateContextName.SMB2_CREATE_DURABLE_HANDLE_RECONNECT: SMB2CreateDurableHandleReconnect(), CreateContextName.SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST: SMB2CreateQueryMaximalAccessResponse(), CreateContextName.SMB2_CREATE_REQUEST_LEASE: SMB2CreateResponseLease(), CreateContextName.SMB2_CREATE_QUERY_ON_DISK_ID: SMB2CreateQueryOnDiskIDResponse(), CreateContextName.SMB2_CREATE_REQUEST_LEASE_V2: SMB2CreateResponseLeaseV2(), CreateContextName.SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2: SMB2CreateDurableHandleResponseV2(), CreateContextName.SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2: SMB2CreateDurableHandleReconnectV2, CreateContextName.SMB2_CREATE_APP_INSTANCE_ID: SMB2CreateAppInstanceId(), CreateContextName.SMB2_CREATE_APP_INSTANCE_VERSION: SMB2CreateAppInstanceVersion() }.get(name, None)
python
def get_response_structure(name): return { CreateContextName.SMB2_CREATE_DURABLE_HANDLE_REQUEST: SMB2CreateDurableHandleResponse(), CreateContextName.SMB2_CREATE_DURABLE_HANDLE_RECONNECT: SMB2CreateDurableHandleReconnect(), CreateContextName.SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST: SMB2CreateQueryMaximalAccessResponse(), CreateContextName.SMB2_CREATE_REQUEST_LEASE: SMB2CreateResponseLease(), CreateContextName.SMB2_CREATE_QUERY_ON_DISK_ID: SMB2CreateQueryOnDiskIDResponse(), CreateContextName.SMB2_CREATE_REQUEST_LEASE_V2: SMB2CreateResponseLeaseV2(), CreateContextName.SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2: SMB2CreateDurableHandleResponseV2(), CreateContextName.SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2: SMB2CreateDurableHandleReconnectV2, CreateContextName.SMB2_CREATE_APP_INSTANCE_ID: SMB2CreateAppInstanceId(), CreateContextName.SMB2_CREATE_APP_INSTANCE_VERSION: SMB2CreateAppInstanceVersion() }.get(name, None)
[ "def", "get_response_structure", "(", "name", ")", ":", "return", "{", "CreateContextName", ".", "SMB2_CREATE_DURABLE_HANDLE_REQUEST", ":", "SMB2CreateDurableHandleResponse", "(", ")", ",", "CreateContextName", ".", "SMB2_CREATE_DURABLE_HANDLE_RECONNECT", ":", "SMB2CreateDurableHandleReconnect", "(", ")", ",", "CreateContextName", ".", "SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST", ":", "SMB2CreateQueryMaximalAccessResponse", "(", ")", ",", "CreateContextName", ".", "SMB2_CREATE_REQUEST_LEASE", ":", "SMB2CreateResponseLease", "(", ")", ",", "CreateContextName", ".", "SMB2_CREATE_QUERY_ON_DISK_ID", ":", "SMB2CreateQueryOnDiskIDResponse", "(", ")", ",", "CreateContextName", ".", "SMB2_CREATE_REQUEST_LEASE_V2", ":", "SMB2CreateResponseLeaseV2", "(", ")", ",", "CreateContextName", ".", "SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2", ":", "SMB2CreateDurableHandleResponseV2", "(", ")", ",", "CreateContextName", ".", "SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2", ":", "SMB2CreateDurableHandleReconnectV2", ",", "CreateContextName", ".", "SMB2_CREATE_APP_INSTANCE_ID", ":", "SMB2CreateAppInstanceId", "(", ")", ",", "CreateContextName", ".", "SMB2_CREATE_APP_INSTANCE_VERSION", ":", "SMB2CreateAppInstanceVersion", "(", ")", "}", ".", "get", "(", "name", ",", "None", ")" ]
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", "." ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/create_contexts.py#L41-L71
2,583
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 unknown name """ buffer_name = self['buffer_name'].get_value() structure = CreateContextName.get_response_structure(buffer_name) if structure: structure.unpack(self['buffer_data'].get_value()) return structure else: # unknown structure, just return the raw bytes return self['buffer_data'].get_value()
python
def get_context_data(self): buffer_name = self['buffer_name'].get_value() structure = CreateContextName.get_response_structure(buffer_name) if structure: structure.unpack(self['buffer_data'].get_value()) return structure else: # unknown structure, just return the raw bytes return self['buffer_data'].get_value()
[ "def", "get_context_data", "(", "self", ")", ":", "buffer_name", "=", "self", "[", "'buffer_name'", "]", ".", "get_value", "(", ")", "structure", "=", "CreateContextName", ".", "get_response_structure", "(", "buffer_name", ")", "if", "structure", ":", "structure", ".", "unpack", "(", "self", "[", "'buffer_data'", "]", ".", "get_value", "(", ")", ")", "return", "structure", "else", ":", "# unknown structure, just return the raw bytes", "return", "self", "[", "'buffer_data'", "]", ".", "get_value", "(", ")" ]
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", "the", "raw", "bytes", "are", "returned", "." ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/create_contexts.py#L210-L225
2,584
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 buffer entry. :param messages: List of SMB2CreateEABuffer structures :return: bytes object that is set on the SMB2CreateContextRequest buffer_data field. """ data = b"" msg_count = len(messages) for i, msg in enumerate(messages): if i == msg_count - 1: msg['next_entry_offset'] = 0 else: # because the end padding val won't be populated if the entry # offset is 0, we set to 1 so the len calc is correct msg['next_entry_offset'] = 1 msg['next_entry_offset'] = len(msg) data += msg.pack() return data
python
def pack_multiple(messages): data = b"" msg_count = len(messages) for i, msg in enumerate(messages): if i == msg_count - 1: msg['next_entry_offset'] = 0 else: # because the end padding val won't be populated if the entry # offset is 0, we set to 1 so the len calc is correct msg['next_entry_offset'] = 1 msg['next_entry_offset'] = len(msg) data += msg.pack() return data
[ "def", "pack_multiple", "(", "messages", ")", ":", "data", "=", "b\"\"", "msg_count", "=", "len", "(", "messages", ")", "for", "i", ",", "msg", "in", "enumerate", "(", "messages", ")", ":", "if", "i", "==", "msg_count", "-", "1", ":", "msg", "[", "'next_entry_offset'", "]", "=", "0", "else", ":", "# because the end padding val won't be populated if the entry", "# offset is 0, we set to 1 so the len calc is correct", "msg", "[", "'next_entry_offset'", "]", "=", "1", "msg", "[", "'next_entry_offset'", "]", "=", "len", "(", "msg", ")", "data", "+=", "msg", ".", "pack", "(", ")", "return", "data" ]
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 SMB2CreateEABuffer structures :return: bytes object that is set on the SMB2CreateContextRequest buffer_data field.
[ "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", "." ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/create_contexts.py#L303-L326
2,585
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 - Creating connection to share %s" % (self.session.username, self.share_name)) utf_share_name = self.share_name.encode('utf-16-le') connect = SMB2TreeConnectRequest() connect['buffer'] = utf_share_name log.info("Session: %s - Sending Tree Connect message" % self.session.username) log.debug(str(connect)) request = self.session.connection.send(connect, sid=self.session.session_id) log.info("Session: %s - Receiving Tree Connect response" % self.session.username) response = self.session.connection.receive(request) tree_response = SMB2TreeConnectResponse() tree_response.unpack(response['data'].get_value()) log.debug(str(tree_response)) # https://msdn.microsoft.com/en-us/library/cc246687.aspx self.tree_connect_id = response['tree_id'].get_value() log.info("Session: %s - Created tree connection with ID %d" % (self.session.username, self.tree_connect_id)) self._connected = True self.session.tree_connect_table[self.tree_connect_id] = self capabilities = tree_response['capabilities'] self.is_dfs_share = capabilities.has_flag( ShareCapabilities.SMB2_SHARE_CAP_DFS) self.is_ca_share = capabilities.has_flag( ShareCapabilities.SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY) dialect = self.session.connection.dialect if dialect >= Dialects.SMB_3_0_0 and \ self.session.connection.supports_encryption: self.encrypt_data = tree_response['share_flags'].has_flag( ShareFlags.SMB2_SHAREFLAG_ENCRYPT_DATA) self.is_scaleout_share = capabilities.has_flag( ShareCapabilities.SMB2_SHARE_CAP_SCALEOUT) # secure negotiate is only valid for SMB 3 dialects before 3.1.1 if dialect < Dialects.SMB_3_1_1 and require_secure_negotiate: self._verify_dialect_negotiate()
python
def connect(self, require_secure_negotiate=True): log.info("Session: %s - Creating connection to share %s" % (self.session.username, self.share_name)) utf_share_name = self.share_name.encode('utf-16-le') connect = SMB2TreeConnectRequest() connect['buffer'] = utf_share_name log.info("Session: %s - Sending Tree Connect message" % self.session.username) log.debug(str(connect)) request = self.session.connection.send(connect, sid=self.session.session_id) log.info("Session: %s - Receiving Tree Connect response" % self.session.username) response = self.session.connection.receive(request) tree_response = SMB2TreeConnectResponse() tree_response.unpack(response['data'].get_value()) log.debug(str(tree_response)) # https://msdn.microsoft.com/en-us/library/cc246687.aspx self.tree_connect_id = response['tree_id'].get_value() log.info("Session: %s - Created tree connection with ID %d" % (self.session.username, self.tree_connect_id)) self._connected = True self.session.tree_connect_table[self.tree_connect_id] = self capabilities = tree_response['capabilities'] self.is_dfs_share = capabilities.has_flag( ShareCapabilities.SMB2_SHARE_CAP_DFS) self.is_ca_share = capabilities.has_flag( ShareCapabilities.SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY) dialect = self.session.connection.dialect if dialect >= Dialects.SMB_3_0_0 and \ self.session.connection.supports_encryption: self.encrypt_data = tree_response['share_flags'].has_flag( ShareFlags.SMB2_SHAREFLAG_ENCRYPT_DATA) self.is_scaleout_share = capabilities.has_flag( ShareCapabilities.SMB2_SHARE_CAP_SCALEOUT) # secure negotiate is only valid for SMB 3 dialects before 3.1.1 if dialect < Dialects.SMB_3_1_1 and require_secure_negotiate: self._verify_dialect_negotiate()
[ "def", "connect", "(", "self", ",", "require_secure_negotiate", "=", "True", ")", ":", "log", ".", "info", "(", "\"Session: %s - Creating connection to share %s\"", "%", "(", "self", ".", "session", ".", "username", ",", "self", ".", "share_name", ")", ")", "utf_share_name", "=", "self", ".", "share_name", ".", "encode", "(", "'utf-16-le'", ")", "connect", "=", "SMB2TreeConnectRequest", "(", ")", "connect", "[", "'buffer'", "]", "=", "utf_share_name", "log", ".", "info", "(", "\"Session: %s - Sending Tree Connect message\"", "%", "self", ".", "session", ".", "username", ")", "log", ".", "debug", "(", "str", "(", "connect", ")", ")", "request", "=", "self", ".", "session", ".", "connection", ".", "send", "(", "connect", ",", "sid", "=", "self", ".", "session", ".", "session_id", ")", "log", ".", "info", "(", "\"Session: %s - Receiving Tree Connect response\"", "%", "self", ".", "session", ".", "username", ")", "response", "=", "self", ".", "session", ".", "connection", ".", "receive", "(", "request", ")", "tree_response", "=", "SMB2TreeConnectResponse", "(", ")", "tree_response", ".", "unpack", "(", "response", "[", "'data'", "]", ".", "get_value", "(", ")", ")", "log", ".", "debug", "(", "str", "(", "tree_response", ")", ")", "# https://msdn.microsoft.com/en-us/library/cc246687.aspx", "self", ".", "tree_connect_id", "=", "response", "[", "'tree_id'", "]", ".", "get_value", "(", ")", "log", ".", "info", "(", "\"Session: %s - Created tree connection with ID %d\"", "%", "(", "self", ".", "session", ".", "username", ",", "self", ".", "tree_connect_id", ")", ")", "self", ".", "_connected", "=", "True", "self", ".", "session", ".", "tree_connect_table", "[", "self", ".", "tree_connect_id", "]", "=", "self", "capabilities", "=", "tree_response", "[", "'capabilities'", "]", "self", ".", "is_dfs_share", "=", "capabilities", ".", "has_flag", "(", "ShareCapabilities", ".", "SMB2_SHARE_CAP_DFS", ")", "self", ".", "is_ca_share", "=", "capabilities", ".", "has_flag", "(", "ShareCapabilities", ".", "SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY", ")", "dialect", "=", "self", ".", "session", ".", "connection", ".", "dialect", "if", "dialect", ">=", "Dialects", ".", "SMB_3_0_0", "and", "self", ".", "session", ".", "connection", ".", "supports_encryption", ":", "self", ".", "encrypt_data", "=", "tree_response", "[", "'share_flags'", "]", ".", "has_flag", "(", "ShareFlags", ".", "SMB2_SHAREFLAG_ENCRYPT_DATA", ")", "self", ".", "is_scaleout_share", "=", "capabilities", ".", "has_flag", "(", "ShareCapabilities", ".", "SMB2_SHARE_CAP_SCALEOUT", ")", "# secure negotiate is only valid for SMB 3 dialects before 3.1.1", "if", "dialect", "<", "Dialects", ".", "SMB_3_1_1", "and", "require_secure_negotiate", ":", "self", ".", "_verify_dialect_negotiate", "(", ")" ]
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", "." ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/tree.py#L197-L248
2,586
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() log.info("Session: %s, Tree: %s - Sending Tree Disconnect message" % (self.session.username, self.share_name)) log.debug(str(req)) request = self.session.connection.send(req, sid=self.session.session_id, tid=self.tree_connect_id) log.info("Session: %s, Tree: %s - Receiving Tree Disconnect response" % (self.session.username, self.share_name)) res = self.session.connection.receive(request) res_disconnect = SMB2TreeDisconnect() res_disconnect.unpack(res['data'].get_value()) log.debug(str(res_disconnect)) self._connected = False del self.session.tree_connect_table[self.tree_connect_id]
python
def disconnect(self): if not self._connected: return log.info("Session: %s, Tree: %s - Disconnecting from Tree Connect" % (self.session.username, self.share_name)) req = SMB2TreeDisconnect() log.info("Session: %s, Tree: %s - Sending Tree Disconnect message" % (self.session.username, self.share_name)) log.debug(str(req)) request = self.session.connection.send(req, sid=self.session.session_id, tid=self.tree_connect_id) log.info("Session: %s, Tree: %s - Receiving Tree Disconnect response" % (self.session.username, self.share_name)) res = self.session.connection.receive(request) res_disconnect = SMB2TreeDisconnect() res_disconnect.unpack(res['data'].get_value()) log.debug(str(res_disconnect)) self._connected = False del self.session.tree_connect_table[self.tree_connect_id]
[ "def", "disconnect", "(", "self", ")", ":", "if", "not", "self", ".", "_connected", ":", "return", "log", ".", "info", "(", "\"Session: %s, Tree: %s - Disconnecting from Tree Connect\"", "%", "(", "self", ".", "session", ".", "username", ",", "self", ".", "share_name", ")", ")", "req", "=", "SMB2TreeDisconnect", "(", ")", "log", ".", "info", "(", "\"Session: %s, Tree: %s - Sending Tree Disconnect message\"", "%", "(", "self", ".", "session", ".", "username", ",", "self", ".", "share_name", ")", ")", "log", ".", "debug", "(", "str", "(", "req", ")", ")", "request", "=", "self", ".", "session", ".", "connection", ".", "send", "(", "req", ",", "sid", "=", "self", ".", "session", ".", "session_id", ",", "tid", "=", "self", ".", "tree_connect_id", ")", "log", ".", "info", "(", "\"Session: %s, Tree: %s - Receiving Tree Disconnect response\"", "%", "(", "self", ".", "session", ".", "username", ",", "self", ".", "share_name", ")", ")", "res", "=", "self", ".", "session", ".", "connection", ".", "receive", "(", "request", ")", "res_disconnect", "=", "SMB2TreeDisconnect", "(", ")", "res_disconnect", ".", "unpack", "(", "res", "[", "'data'", "]", ".", "get_value", "(", ")", ")", "log", ".", "debug", "(", "str", "(", "res_disconnect", ")", ")", "self", ".", "_connected", "=", "False", "del", "self", ".", "session", ".", "tree_connect_table", "[", "self", ".", "tree_connect_id", "]" ]
Disconnects the tree connection.
[ "Disconnects", "the", "tree", "connection", "." ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/tree.py#L250-L275
2,587
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 of each session. """ if close: for session in list(self.session_table.values()): session.disconnect(True) log.info("Disconnecting transport connection") self.transport.disconnect()
python
def disconnect(self, close=True): if close: for session in list(self.session_table.values()): session.disconnect(True) log.info("Disconnecting transport connection") self.transport.disconnect()
[ "def", "disconnect", "(", "self", ",", "close", "=", "True", ")", ":", "if", "close", ":", "for", "session", "in", "list", "(", "self", ".", "session_table", ".", "values", "(", ")", ")", ":", "session", ".", "disconnect", "(", "True", ")", "log", ".", "info", "(", "\"Disconnecting transport connection\"", ")", "self", ".", "transport", ".", "disconnect", "(", ")" ]
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", "." ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L893-L907
2,588
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 the message is sent for :param tid: A tree_id object that the message is sent for :param credit_request: Specifies extra credits to be requested with the SMB header :return: Request of the message that was sent """ header = self._generate_packet_header(message, sid, tid, credit_request) # get the actual Session and TreeConnect object instead of the IDs session = self.session_table.get(sid, None) if sid else None tree = None if tid and session: if tid not in session.tree_connect_table.keys(): error_msg = "Cannot find Tree with the ID %d in the session " \ "tree table" % tid raise smbprotocol.exceptions.SMBException(error_msg) tree = session.tree_connect_table[tid] if session and session.signing_required and session.signing_key: self._sign(header, session) request = Request(header) self.outstanding_requests[header['message_id'].get_value()] = request send_data = header.pack() if (session and session.encrypt_data) or (tree and tree.encrypt_data): send_data = self._encrypt(send_data, session) self.transport.send(send_data) return request
python
def send(self, message, sid=None, tid=None, credit_request=None): header = self._generate_packet_header(message, sid, tid, credit_request) # get the actual Session and TreeConnect object instead of the IDs session = self.session_table.get(sid, None) if sid else None tree = None if tid and session: if tid not in session.tree_connect_table.keys(): error_msg = "Cannot find Tree with the ID %d in the session " \ "tree table" % tid raise smbprotocol.exceptions.SMBException(error_msg) tree = session.tree_connect_table[tid] if session and session.signing_required and session.signing_key: self._sign(header, session) request = Request(header) self.outstanding_requests[header['message_id'].get_value()] = request send_data = header.pack() if (session and session.encrypt_data) or (tree and tree.encrypt_data): send_data = self._encrypt(send_data, session) self.transport.send(send_data) return request
[ "def", "send", "(", "self", ",", "message", ",", "sid", "=", "None", ",", "tid", "=", "None", ",", "credit_request", "=", "None", ")", ":", "header", "=", "self", ".", "_generate_packet_header", "(", "message", ",", "sid", ",", "tid", ",", "credit_request", ")", "# get the actual Session and TreeConnect object instead of the IDs", "session", "=", "self", ".", "session_table", ".", "get", "(", "sid", ",", "None", ")", "if", "sid", "else", "None", "tree", "=", "None", "if", "tid", "and", "session", ":", "if", "tid", "not", "in", "session", ".", "tree_connect_table", ".", "keys", "(", ")", ":", "error_msg", "=", "\"Cannot find Tree with the ID %d in the session \"", "\"tree table\"", "%", "tid", "raise", "smbprotocol", ".", "exceptions", ".", "SMBException", "(", "error_msg", ")", "tree", "=", "session", ".", "tree_connect_table", "[", "tid", "]", "if", "session", "and", "session", ".", "signing_required", "and", "session", ".", "signing_key", ":", "self", ".", "_sign", "(", "header", ",", "session", ")", "request", "=", "Request", "(", "header", ")", "self", ".", "outstanding_requests", "[", "header", "[", "'message_id'", "]", ".", "get_value", "(", ")", "]", "=", "request", "send_data", "=", "header", ".", "pack", "(", ")", "if", "(", "session", "and", "session", ".", "encrypt_data", ")", "or", "(", "tree", "and", "tree", ".", "encrypt_data", ")", ":", "send_data", "=", "self", ".", "_encrypt", "(", "send_data", ",", "session", ")", "self", ".", "transport", ".", "send", "(", "send_data", ")", "return", "request" ]
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 for :param credit_request: Specifies extra credits to be requested with the SMB header :return: Request of the message that was sent
[ "Will", "send", "a", "message", "to", "the", "server", "that", "is", "passed", "in", ".", "The", "final", "unencrypted", "header", "is", "returned", "to", "the", "function", "that", "called", "this", "." ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L909-L946
2,589
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 that the request is sent for :param tid: A tree_id object that the message is sent for :return: List<Request> for each request that was sent, each entry in the list is in the same order of the message list that was passed in """ send_data = b"" session = self.session_table[sid] tree = session.tree_connect_table[tid] requests = [] total_requests = len(messages) for i, message in enumerate(messages): if i == total_requests - 1: next_command = 0 padding = b"" else: msg_length = 64 + len(message) # each compound message must start at the 8-byte boundary mod = msg_length % 8 padding_length = 8 - mod if mod > 0 else 0 padding = b"\x00" * padding_length next_command = msg_length + padding_length header = self._generate_packet_header(message, sid, tid, None) header['next_command'] = next_command if i != 0 and related: header['session_id'] = b"\xff" * 8 header['tree_id'] = b"\xff" * 4 header['flags'].set_flag( Smb2Flags.SMB2_FLAGS_RELATED_OPERATIONS ) if session.signing_required and session.signing_key: self._sign(header, session, padding=padding) send_data += header.pack() + padding request = Request(header) requests.append(request) self.outstanding_requests[header['message_id'].get_value()] = \ request if session.encrypt_data or tree.encrypt_data: send_data = self._encrypt(send_data, session) self.transport.send(send_data) return requests
python
def send_compound(self, messages, sid, tid, related=False): send_data = b"" session = self.session_table[sid] tree = session.tree_connect_table[tid] requests = [] total_requests = len(messages) for i, message in enumerate(messages): if i == total_requests - 1: next_command = 0 padding = b"" else: msg_length = 64 + len(message) # each compound message must start at the 8-byte boundary mod = msg_length % 8 padding_length = 8 - mod if mod > 0 else 0 padding = b"\x00" * padding_length next_command = msg_length + padding_length header = self._generate_packet_header(message, sid, tid, None) header['next_command'] = next_command if i != 0 and related: header['session_id'] = b"\xff" * 8 header['tree_id'] = b"\xff" * 4 header['flags'].set_flag( Smb2Flags.SMB2_FLAGS_RELATED_OPERATIONS ) if session.signing_required and session.signing_key: self._sign(header, session, padding=padding) send_data += header.pack() + padding request = Request(header) requests.append(request) self.outstanding_requests[header['message_id'].get_value()] = \ request if session.encrypt_data or tree.encrypt_data: send_data = self._encrypt(send_data, session) self.transport.send(send_data) return requests
[ "def", "send_compound", "(", "self", ",", "messages", ",", "sid", ",", "tid", ",", "related", "=", "False", ")", ":", "send_data", "=", "b\"\"", "session", "=", "self", ".", "session_table", "[", "sid", "]", "tree", "=", "session", ".", "tree_connect_table", "[", "tid", "]", "requests", "=", "[", "]", "total_requests", "=", "len", "(", "messages", ")", "for", "i", ",", "message", "in", "enumerate", "(", "messages", ")", ":", "if", "i", "==", "total_requests", "-", "1", ":", "next_command", "=", "0", "padding", "=", "b\"\"", "else", ":", "msg_length", "=", "64", "+", "len", "(", "message", ")", "# each compound message must start at the 8-byte boundary", "mod", "=", "msg_length", "%", "8", "padding_length", "=", "8", "-", "mod", "if", "mod", ">", "0", "else", "0", "padding", "=", "b\"\\x00\"", "*", "padding_length", "next_command", "=", "msg_length", "+", "padding_length", "header", "=", "self", ".", "_generate_packet_header", "(", "message", ",", "sid", ",", "tid", ",", "None", ")", "header", "[", "'next_command'", "]", "=", "next_command", "if", "i", "!=", "0", "and", "related", ":", "header", "[", "'session_id'", "]", "=", "b\"\\xff\"", "*", "8", "header", "[", "'tree_id'", "]", "=", "b\"\\xff\"", "*", "4", "header", "[", "'flags'", "]", ".", "set_flag", "(", "Smb2Flags", ".", "SMB2_FLAGS_RELATED_OPERATIONS", ")", "if", "session", ".", "signing_required", "and", "session", ".", "signing_key", ":", "self", ".", "_sign", "(", "header", ",", "session", ",", "padding", "=", "padding", ")", "send_data", "+=", "header", ".", "pack", "(", ")", "+", "padding", "request", "=", "Request", "(", "header", ")", "requests", ".", "append", "(", "request", ")", "self", ".", "outstanding_requests", "[", "header", "[", "'message_id'", "]", ".", "get_value", "(", ")", "]", "=", "request", "if", "session", ".", "encrypt_data", "or", "tree", ".", "encrypt_data", ":", "send_data", "=", "self", ".", "_encrypt", "(", "send_data", ",", "session", ")", "self", ".", "transport", ".", "send", "(", "send_data", ")", "return", "requests" ]
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 message is sent for :return: List<Request> for each request that was sent, each entry in the list is in the same order of the message list that was passed in
[ "Sends", "multiple", "messages", "within", "1", "TCP", "request", "will", "fail", "if", "the", "size", "of", "the", "total", "length", "exceeds", "the", "maximum", "of", "the", "transport", "max", "." ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L948-L1002
2,590
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 response in the case of a STATUS_PENDING response, the pending response is returned in the case of wait=False :param timeout: Set a timeout used while waiting for a response from the server :return: SMB2HeaderResponse of the received message """ start_time = time.time() # check if we have received a response while True: self._flush_message_buffer() status = request.response['status'].get_value() if \ request.response else None if status is not None and (wait and status != NtStatus.STATUS_PENDING): break current_time = time.time() - start_time if timeout and (current_time > timeout): error_msg = "Connection timeout of %d seconds exceeded while" \ " waiting for a response from the server" \ % timeout raise smbprotocol.exceptions.SMBException(error_msg) response = request.response status = response['status'].get_value() if status not in [NtStatus.STATUS_SUCCESS, NtStatus.STATUS_PENDING]: raise smbprotocol.exceptions.SMBResponseException(response, status) # now we have a retrieval request for the response, we can delete # the request from the outstanding requests message_id = request.message['message_id'].get_value() del self.outstanding_requests[message_id] return response
python
def receive(self, request, wait=True, timeout=None): start_time = time.time() # check if we have received a response while True: self._flush_message_buffer() status = request.response['status'].get_value() if \ request.response else None if status is not None and (wait and status != NtStatus.STATUS_PENDING): break current_time = time.time() - start_time if timeout and (current_time > timeout): error_msg = "Connection timeout of %d seconds exceeded while" \ " waiting for a response from the server" \ % timeout raise smbprotocol.exceptions.SMBException(error_msg) response = request.response status = response['status'].get_value() if status not in [NtStatus.STATUS_SUCCESS, NtStatus.STATUS_PENDING]: raise smbprotocol.exceptions.SMBResponseException(response, status) # now we have a retrieval request for the response, we can delete # the request from the outstanding requests message_id = request.message['message_id'].get_value() del self.outstanding_requests[message_id] return response
[ "def", "receive", "(", "self", ",", "request", ",", "wait", "=", "True", ",", "timeout", "=", "None", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "# check if we have received a response", "while", "True", ":", "self", ".", "_flush_message_buffer", "(", ")", "status", "=", "request", ".", "response", "[", "'status'", "]", ".", "get_value", "(", ")", "if", "request", ".", "response", "else", "None", "if", "status", "is", "not", "None", "and", "(", "wait", "and", "status", "!=", "NtStatus", ".", "STATUS_PENDING", ")", ":", "break", "current_time", "=", "time", ".", "time", "(", ")", "-", "start_time", "if", "timeout", "and", "(", "current_time", ">", "timeout", ")", ":", "error_msg", "=", "\"Connection timeout of %d seconds exceeded while\"", "\" waiting for a response from the server\"", "%", "timeout", "raise", "smbprotocol", ".", "exceptions", ".", "SMBException", "(", "error_msg", ")", "response", "=", "request", ".", "response", "status", "=", "response", "[", "'status'", "]", ".", "get_value", "(", ")", "if", "status", "not", "in", "[", "NtStatus", ".", "STATUS_SUCCESS", ",", "NtStatus", ".", "STATUS_PENDING", "]", ":", "raise", "smbprotocol", ".", "exceptions", ".", "SMBResponseException", "(", "response", ",", "status", ")", "# now we have a retrieval request for the response, we can delete", "# the request from the outstanding requests", "message_id", "=", "request", ".", "message", "[", "'message_id'", "]", ".", "get_value", "(", ")", "del", "self", ".", "outstanding_requests", "[", "message_id", "]", "return", "response" ]
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 pending response is returned in the case of wait=False :param timeout: Set a timeout used while waiting for a response from the server :return: SMB2HeaderResponse of the received message
[ "Polls", "the", "message", "buffer", "of", "the", "TCP", "connection", "and", "waits", "until", "a", "valid", "message", "is", "received", "based", "on", "the", "message_id", "passed", "in", "." ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L1004-L1044
2,591
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 authenticated session must be passed into this function or else the socket will close. :param sid: When talking to a Windows host this must be populated with a valid session_id from a negotiated session :param timeout: The timeout in seconds to wait for the Echo Response :param credit_request: The number of credits to request :return: the credits that were granted by the server """ log.info("Sending Echo request with a timeout of %d and credit " "request of %d" % (timeout, credit_request)) echo_msg = SMB2Echo() log.debug(str(echo_msg)) req = self.send(echo_msg, sid=sid, credit_request=credit_request) log.info("Receiving Echo response") response = self.receive(req, timeout=timeout) log.info("Credits granted from the server echo response: %d" % response['credit_response'].get_value()) echo_resp = SMB2Echo() echo_resp.unpack(response['data'].get_value()) log.debug(str(echo_resp)) return response['credit_response'].get_value()
python
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_request)) echo_msg = SMB2Echo() log.debug(str(echo_msg)) req = self.send(echo_msg, sid=sid, credit_request=credit_request) log.info("Receiving Echo response") response = self.receive(req, timeout=timeout) log.info("Credits granted from the server echo response: %d" % response['credit_response'].get_value()) echo_resp = SMB2Echo() echo_resp.unpack(response['data'].get_value()) log.debug(str(echo_resp)) return response['credit_response'].get_value()
[ "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_request", ")", ")", "echo_msg", "=", "SMB2Echo", "(", ")", "log", ".", "debug", "(", "str", "(", "echo_msg", ")", ")", "req", "=", "self", ".", "send", "(", "echo_msg", ",", "sid", "=", "sid", ",", "credit_request", "=", "credit_request", ")", "log", ".", "info", "(", "\"Receiving Echo response\"", ")", "response", "=", "self", ".", "receive", "(", "req", ",", "timeout", "=", "timeout", ")", "log", ".", "info", "(", "\"Credits granted from the server echo response: %d\"", "%", "response", "[", "'credit_response'", "]", ".", "get_value", "(", ")", ")", "echo_resp", "=", "SMB2Echo", "(", ")", "echo_resp", ".", "unpack", "(", "response", "[", "'data'", "]", ".", "get_value", "(", ")", ")", "log", ".", "debug", "(", "str", "(", "echo_resp", ")", ")", "return", "response", "[", "'credit_response'", "]", ".", "get_value", "(", ")" ]
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 will close. :param sid: When talking to a Windows host this must be populated with a valid session_id from a negotiated session :param timeout: The timeout in seconds to wait for the Echo Response :param credit_request: The number of credits to request :return: the credits that were granted by the server
[ "Sends", "an", "SMB2", "Echo", "request", "to", "the", "server", ".", "This", "can", "be", "used", "to", "request", "more", "credits", "from", "the", "server", "with", "the", "credit_request", "param", "." ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L1046-L1076
2,592
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 True: message_bytes = self.transport.receive() # there were no messages receives, so break from the loop if message_bytes is None: break # check if the message is encrypted and decrypt if necessary if message_bytes[:4] == b"\xfdSMB": message = SMB2TransformHeader() message.unpack(message_bytes) message_bytes = self._decrypt(message) # now retrieve message(s) from response is_last = False session_id = None while not is_last: next_command = struct.unpack("<L", message_bytes[20:24])[0] header_length = \ next_command if next_command != 0 else len(message_bytes) header_bytes = message_bytes[:header_length] message = SMB2HeaderResponse() message.unpack(header_bytes) flags = message['flags'] if not flags.has_flag(Smb2Flags.SMB2_FLAGS_RELATED_OPERATIONS): session_id = message['session_id'].get_value() self._verify(message, session_id) message_id = message['message_id'].get_value() request = self.outstanding_requests.get(message_id, None) if not request: error_msg = "Received response with an unknown message " \ "ID: %d" % message_id raise smbprotocol.exceptions.SMBException(error_msg) # add the upper credit limit based on the credits granted by # the server credit_response = message['credit_response'].get_value() self.sequence_window['high'] += \ credit_response if credit_response > 0 else 1 request.response = message self.outstanding_requests[message_id] = request message_bytes = message_bytes[header_length:] is_last = next_command == 0
python
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 # check if the message is encrypted and decrypt if necessary if message_bytes[:4] == b"\xfdSMB": message = SMB2TransformHeader() message.unpack(message_bytes) message_bytes = self._decrypt(message) # now retrieve message(s) from response is_last = False session_id = None while not is_last: next_command = struct.unpack("<L", message_bytes[20:24])[0] header_length = \ next_command if next_command != 0 else len(message_bytes) header_bytes = message_bytes[:header_length] message = SMB2HeaderResponse() message.unpack(header_bytes) flags = message['flags'] if not flags.has_flag(Smb2Flags.SMB2_FLAGS_RELATED_OPERATIONS): session_id = message['session_id'].get_value() self._verify(message, session_id) message_id = message['message_id'].get_value() request = self.outstanding_requests.get(message_id, None) if not request: error_msg = "Received response with an unknown message " \ "ID: %d" % message_id raise smbprotocol.exceptions.SMBException(error_msg) # add the upper credit limit based on the credits granted by # the server credit_response = message['credit_response'].get_value() self.sequence_window['high'] += \ credit_response if credit_response > 0 else 1 request.response = message self.outstanding_requests[message_id] = request message_bytes = message_bytes[header_length:] is_last = next_command == 0
[ "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", "# check if the message is encrypted and decrypt if necessary", "if", "message_bytes", "[", ":", "4", "]", "==", "b\"\\xfdSMB\"", ":", "message", "=", "SMB2TransformHeader", "(", ")", "message", ".", "unpack", "(", "message_bytes", ")", "message_bytes", "=", "self", ".", "_decrypt", "(", "message", ")", "# now retrieve message(s) from response", "is_last", "=", "False", "session_id", "=", "None", "while", "not", "is_last", ":", "next_command", "=", "struct", ".", "unpack", "(", "\"<L\"", ",", "message_bytes", "[", "20", ":", "24", "]", ")", "[", "0", "]", "header_length", "=", "next_command", "if", "next_command", "!=", "0", "else", "len", "(", "message_bytes", ")", "header_bytes", "=", "message_bytes", "[", ":", "header_length", "]", "message", "=", "SMB2HeaderResponse", "(", ")", "message", ".", "unpack", "(", "header_bytes", ")", "flags", "=", "message", "[", "'flags'", "]", "if", "not", "flags", ".", "has_flag", "(", "Smb2Flags", ".", "SMB2_FLAGS_RELATED_OPERATIONS", ")", ":", "session_id", "=", "message", "[", "'session_id'", "]", ".", "get_value", "(", ")", "self", ".", "_verify", "(", "message", ",", "session_id", ")", "message_id", "=", "message", "[", "'message_id'", "]", ".", "get_value", "(", ")", "request", "=", "self", ".", "outstanding_requests", ".", "get", "(", "message_id", ",", "None", ")", "if", "not", "request", ":", "error_msg", "=", "\"Received response with an unknown message \"", "\"ID: %d\"", "%", "message_id", "raise", "smbprotocol", ".", "exceptions", ".", "SMBException", "(", "error_msg", ")", "# add the upper credit limit based on the credits granted by", "# the server", "credit_response", "=", "message", "[", "'credit_response'", "]", ".", "get_value", "(", ")", "self", ".", "sequence_window", "[", "'high'", "]", "+=", "credit_response", "if", "credit_response", ">", "0", "else", "1", "request", ".", "response", "=", "message", "self", ".", "outstanding_requests", "[", "message_id", "]", "=", "request", "message_bytes", "=", "message_bytes", "[", "header_length", ":", "]", "is_last", "=", "next_command", "==", "0" ]
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", "then", "available", "in", "self", ".", "outstanding_requests" ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L1120-L1173
2,593
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 sending/receiving data over 64 kilobytes, in the existing messages only the Read, Write, Query Directory or IOCTL commands will end in this scenario and each require their own calculation to get the proper value. The generic formula for calculating the credit charge is https://msdn.microsoft.com/en-us/library/dn529312.aspx (max(SendPayloadSize, Expected ResponsePayloadSize) - 1) / 65536 + 1 :param message: The message being sent :return: The credit charge to set on the header """ credit_size = 65536 if not self.supports_multi_credit: credit_charge = 0 elif message.COMMAND == Commands.SMB2_READ: max_size = message['length'].get_value() + \ message['read_channel_info_length'].get_value() - 1 credit_charge = math.ceil(max_size / credit_size) elif message.COMMAND == Commands.SMB2_WRITE: max_size = message['length'].get_value() + \ message['write_channel_info_length'].get_value() - 1 credit_charge = math.ceil(max_size / credit_size) elif message.COMMAND == Commands.SMB2_IOCTL: max_in_size = len(message['buffer']) max_out_size = message['max_output_response'].get_value() max_size = max(max_in_size, max_out_size) - 1 credit_charge = math.ceil(max_size / credit_size) elif message.COMMAND == Commands.SMB2_QUERY_DIRECTORY: max_in_size = len(message['buffer']) max_out_size = message['output_buffer_length'].get_value() max_size = max(max_in_size, max_out_size) - 1 credit_charge = math.ceil(max_size / credit_size) else: credit_charge = 1 # python 2 returns a float where we need an integer return int(credit_charge)
python
def _calculate_credit_charge(self, message): credit_size = 65536 if not self.supports_multi_credit: credit_charge = 0 elif message.COMMAND == Commands.SMB2_READ: max_size = message['length'].get_value() + \ message['read_channel_info_length'].get_value() - 1 credit_charge = math.ceil(max_size / credit_size) elif message.COMMAND == Commands.SMB2_WRITE: max_size = message['length'].get_value() + \ message['write_channel_info_length'].get_value() - 1 credit_charge = math.ceil(max_size / credit_size) elif message.COMMAND == Commands.SMB2_IOCTL: max_in_size = len(message['buffer']) max_out_size = message['max_output_response'].get_value() max_size = max(max_in_size, max_out_size) - 1 credit_charge = math.ceil(max_size / credit_size) elif message.COMMAND == Commands.SMB2_QUERY_DIRECTORY: max_in_size = len(message['buffer']) max_out_size = message['output_buffer_length'].get_value() max_size = max(max_in_size, max_out_size) - 1 credit_charge = math.ceil(max_size / credit_size) else: credit_charge = 1 # python 2 returns a float where we need an integer return int(credit_charge)
[ "def", "_calculate_credit_charge", "(", "self", ",", "message", ")", ":", "credit_size", "=", "65536", "if", "not", "self", ".", "supports_multi_credit", ":", "credit_charge", "=", "0", "elif", "message", ".", "COMMAND", "==", "Commands", ".", "SMB2_READ", ":", "max_size", "=", "message", "[", "'length'", "]", ".", "get_value", "(", ")", "+", "message", "[", "'read_channel_info_length'", "]", ".", "get_value", "(", ")", "-", "1", "credit_charge", "=", "math", ".", "ceil", "(", "max_size", "/", "credit_size", ")", "elif", "message", ".", "COMMAND", "==", "Commands", ".", "SMB2_WRITE", ":", "max_size", "=", "message", "[", "'length'", "]", ".", "get_value", "(", ")", "+", "message", "[", "'write_channel_info_length'", "]", ".", "get_value", "(", ")", "-", "1", "credit_charge", "=", "math", ".", "ceil", "(", "max_size", "/", "credit_size", ")", "elif", "message", ".", "COMMAND", "==", "Commands", ".", "SMB2_IOCTL", ":", "max_in_size", "=", "len", "(", "message", "[", "'buffer'", "]", ")", "max_out_size", "=", "message", "[", "'max_output_response'", "]", ".", "get_value", "(", ")", "max_size", "=", "max", "(", "max_in_size", ",", "max_out_size", ")", "-", "1", "credit_charge", "=", "math", ".", "ceil", "(", "max_size", "/", "credit_size", ")", "elif", "message", ".", "COMMAND", "==", "Commands", ".", "SMB2_QUERY_DIRECTORY", ":", "max_in_size", "=", "len", "(", "message", "[", "'buffer'", "]", ")", "max_out_size", "=", "message", "[", "'output_buffer_length'", "]", ".", "get_value", "(", ")", "max_size", "=", "max", "(", "max_in_size", ",", "max_out_size", ")", "-", "1", "credit_charge", "=", "math", ".", "ceil", "(", "max_size", "/", "credit_size", ")", "else", ":", "credit_charge", "=", "1", "# python 2 returns a float where we need an integer", "return", "int", "(", "credit_charge", ")" ]
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 messages only the Read, Write, Query Directory or IOCTL commands will end in this scenario and each require their own calculation to get the proper value. The generic formula for calculating the credit charge is https://msdn.microsoft.com/en-us/library/dn529312.aspx (max(SendPayloadSize, Expected ResponsePayloadSize) - 1) / 65536 + 1 :param message: The message being sent :return: The credit charge to set on the header
[ "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", "." ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L1364-L1408
2,594
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.values()): open.close(False) for tree in list(self.tree_connect_table.values()): tree.disconnect() log.info("Session: %s - Logging off of SMB Session" % self.username) logoff = SMB2Logoff() log.info("Session: %s - Sending Logoff message" % self.username) log.debug(str(logoff)) request = self.connection.send(logoff, sid=self.session_id) log.info("Session: %s - Receiving Logoff response" % self.username) res = self.connection.receive(request) res_logoff = SMB2Logoff() res_logoff.unpack(res['data'].get_value()) log.debug(str(res_logoff)) self._connected = False del self.connection.session_table[self.session_id]
python
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.values()): open.close(False) for tree in list(self.tree_connect_table.values()): tree.disconnect() log.info("Session: %s - Logging off of SMB Session" % self.username) logoff = SMB2Logoff() log.info("Session: %s - Sending Logoff message" % self.username) log.debug(str(logoff)) request = self.connection.send(logoff, sid=self.session_id) log.info("Session: %s - Receiving Logoff response" % self.username) res = self.connection.receive(request) res_logoff = SMB2Logoff() res_logoff.unpack(res['data'].get_value()) log.debug(str(res_logoff)) self._connected = False del self.connection.session_table[self.session_id]
[ "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", ".", "values", "(", ")", ")", ":", "open", ".", "close", "(", "False", ")", "for", "tree", "in", "list", "(", "self", ".", "tree_connect_table", ".", "values", "(", ")", ")", ":", "tree", ".", "disconnect", "(", ")", "log", ".", "info", "(", "\"Session: %s - Logging off of SMB Session\"", "%", "self", ".", "username", ")", "logoff", "=", "SMB2Logoff", "(", ")", "log", ".", "info", "(", "\"Session: %s - Sending Logoff message\"", "%", "self", ".", "username", ")", "log", ".", "debug", "(", "str", "(", "logoff", ")", ")", "request", "=", "self", ".", "connection", ".", "send", "(", "logoff", ",", "sid", "=", "self", ".", "session_id", ")", "log", ".", "info", "(", "\"Session: %s - Receiving Logoff response\"", "%", "self", ".", "username", ")", "res", "=", "self", ".", "connection", ".", "receive", "(", "request", ")", "res_logoff", "=", "SMB2Logoff", "(", ")", "res_logoff", ".", "unpack", "(", "res", "[", "'data'", "]", ".", "get_value", "(", ")", ")", "log", ".", "debug", "(", "str", "(", "res_logoff", ")", ")", "self", ".", "_connected", "=", "False", "del", "self", ".", "connection", ".", "session_table", "[", "self", ".", "session_id", "]" ]
Logs off the session :param close: Will close all tree connects in a session
[ "Logs", "off", "the", "session" ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/session.py#L344-L373
2,595
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_value = self._pack_value(value) size = self._get_calculated_size(self.size, packed_value) if len(packed_value) != size: raise ValueError("Invalid packed data length for field %s of %d " "does not fit field size of %d" % (self.name, len(packed_value), size)) return packed_value
python
def pack(self): value = self._get_calculated_value(self.value) packed_value = self._pack_value(value) size = self._get_calculated_size(self.size, packed_value) if len(packed_value) != size: raise ValueError("Invalid packed data length for field %s of %d " "does not fit field size of %d" % (self.name, len(packed_value), size)) return packed_value
[ "def", "pack", "(", "self", ")", ":", "value", "=", "self", ".", "_get_calculated_value", "(", "self", ".", "value", ")", "packed_value", "=", "self", ".", "_pack_value", "(", "value", ")", "size", "=", "self", ".", "_get_calculated_size", "(", "self", ".", "size", ",", "packed_value", ")", "if", "len", "(", "packed_value", ")", "!=", "size", ":", "raise", "ValueError", "(", "\"Invalid packed data length for field %s of %d \"", "\"does not fit field size of %d\"", "%", "(", "self", ".", "name", ",", "len", "(", "packed_value", ")", ",", "size", ")", ")", "return", "packed_value" ]
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", "." ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/structure.py#L164-L180
2,596
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): 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", "." ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/structure.py#L192-L200
2,597
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 """ size = self._get_calculated_size(self.size, data) self.set_value(data[0:size]) return data[len(self):]
python
def unpack(self, data): size = self._get_calculated_size(self.size, data) self.set_value(data[0:size]) return data[len(self):]
[ "def", "unpack", "(", "self", ",", "data", ")", ":", "size", "=", "self", ".", "_get_calculated_size", "(", "self", ".", "size", ",", "data", ")", "self", ".", "set_value", "(", "data", "[", "0", ":", "size", "]", ")", "return", "data", "[", "len", "(", "self", ")", ":", "]" ]
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", "." ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/structure.py#L202-L213
2,598
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): expanded_value = value(self.structure) return self._get_calculated_value(expanded_value) else: # perform one final parsing of the value in case lambda value # returned a different type return self._parse_value(value)
python
def _get_calculated_value(self, value): if isinstance(value, types.LambdaType): expanded_value = value(self.structure) return self._get_calculated_value(expanded_value) else: # perform one final parsing of the value in case lambda value # returned a different type return self._parse_value(value)
[ "def", "_get_calculated_value", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "types", ".", "LambdaType", ")", ":", "expanded_value", "=", "value", "(", "self", ".", "structure", ")", "return", "self", ".", "_get_calculated_value", "(", "expanded_value", ")", "else", ":", "# perform one final parsing of the value in case lambda value", "# returned a different type", "return", "self", ".", "_parse_value", "(", "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
[ "Get", "s", "the", "final", "value", "of", "the", "field", "and", "runs", "the", "lambda", "functions", "recursively", "until", "a", "final", "value", "is", "derived", "." ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/structure.py#L258-L272
2,599
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 specified """ if isinstance(size, types.LambdaType): size = size(self.structure) struct_format = { 1: 'B', 2: 'H', 4: 'L', 8: 'Q' } if size not in struct_format.keys(): raise InvalidFieldDefinition("Cannot struct format of size %s" % size) return struct_format[size]
python
def _get_struct_format(self, size): if isinstance(size, types.LambdaType): size = size(self.structure) struct_format = { 1: 'B', 2: 'H', 4: 'L', 8: 'Q' } if size not in struct_format.keys(): raise InvalidFieldDefinition("Cannot struct format of size %s" % size) return struct_format[size]
[ "def", "_get_struct_format", "(", "self", ",", "size", ")", ":", "if", "isinstance", "(", "size", ",", "types", ".", "LambdaType", ")", ":", "size", "=", "size", "(", "self", ".", "structure", ")", "struct_format", "=", "{", "1", ":", "'B'", ",", "2", ":", "'H'", ",", "4", ":", "'L'", ",", "8", ":", "'Q'", "}", "if", "size", "not", "in", "struct_format", ".", "keys", "(", ")", ":", "raise", "InvalidFieldDefinition", "(", "\"Cannot struct format of size %s\"", "%", "size", ")", "return", "struct_format", "[", "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 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", "." ]
d8eb00fbc824f97d0f4946e3f768c5e6c723499a
https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/structure.py#L296-L317