repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
wgnet/webium | webium/cookie.py | add_cookies_to_web_driver | def add_cookies_to_web_driver(driver, cookies):
"""
Sets cookies in an existing WebDriver session.
"""
for cookie in cookies:
driver.add_cookie(convert_cookie_to_dict(cookie))
return driver | python | def add_cookies_to_web_driver(driver, cookies):
"""
Sets cookies in an existing WebDriver session.
"""
for cookie in cookies:
driver.add_cookie(convert_cookie_to_dict(cookie))
return driver | Sets cookies in an existing WebDriver session. | https://github.com/wgnet/webium/blob/ccb09876a201e75f5c5810392d4db7a8708b90cb/webium/cookie.py#L41-L47 |
wgnet/webium | webium/plugins/browser_closer.py | BrowserCloserPlugin.configure | def configure(self, options, conf):
"""Configure plugin. Plugin is enabled by default.
"""
self.conf = conf
self.when = options.browser_closer_when | python | def configure(self, options, conf):
"""Configure plugin. Plugin is enabled by default.
"""
self.conf = conf
self.when = options.browser_closer_when | Configure plugin. Plugin is enabled by default. | https://github.com/wgnet/webium/blob/ccb09876a201e75f5c5810392d4db7a8708b90cb/webium/plugins/browser_closer.py#L25-L29 |
alecthomas/importmagic | importmagic/index.py | SymbolIndex.index_path | def index_path(self, root):
"""Index a path.
:param root: Either a package directory, a .so or a .py module.
"""
basename = os.path.basename(root)
if os.path.splitext(basename)[0] != '__init__' and basename.startswith('_'):
return
location = self._determine_location_for(root)
if os.path.isfile(root):
self._index_module(root, location)
elif os.path.isdir(root) and os.path.exists(os.path.join(root, '__init__.py')):
self._index_package(root, location) | python | def index_path(self, root):
"""Index a path.
:param root: Either a package directory, a .so or a .py module.
"""
basename = os.path.basename(root)
if os.path.splitext(basename)[0] != '__init__' and basename.startswith('_'):
return
location = self._determine_location_for(root)
if os.path.isfile(root):
self._index_module(root, location)
elif os.path.isdir(root) and os.path.exists(os.path.join(root, '__init__.py')):
self._index_package(root, location) | Index a path.
:param root: Either a package directory, a .so or a .py module. | https://github.com/alecthomas/importmagic/blob/c00f2b282d933e0a9780146a20792f9e31fc8e6f/importmagic/index.py#L148-L160 |
alecthomas/importmagic | importmagic/index.py | SymbolIndex.get_or_create_index | def get_or_create_index(self, paths=None, name=None, refresh=False):
"""
Get index with given name from cache. Create if it doesn't exists.
"""
if not paths:
paths = sys.path
if not name:
name = 'default'
self._name = name
idx_dir = get_cache_dir()
idx_file = os.path.join(idx_dir, name + '.json')
if os.path.exists(idx_file) and not refresh:
with open(idx_file) as fd:
self.deserialize(fd)
else:
self.build_index(paths)
with open(idx_file, 'w') as fd:
self.serialize(fd)
return self | python | def get_or_create_index(self, paths=None, name=None, refresh=False):
"""
Get index with given name from cache. Create if it doesn't exists.
"""
if not paths:
paths = sys.path
if not name:
name = 'default'
self._name = name
idx_dir = get_cache_dir()
idx_file = os.path.join(idx_dir, name + '.json')
if os.path.exists(idx_file) and not refresh:
with open(idx_file) as fd:
self.deserialize(fd)
else:
self.build_index(paths)
with open(idx_file, 'w') as fd:
self.serialize(fd)
return self | Get index with given name from cache. Create if it doesn't exists. | https://github.com/alecthomas/importmagic/blob/c00f2b282d933e0a9780146a20792f9e31fc8e6f/importmagic/index.py#L208-L229 |
alecthomas/importmagic | importmagic/index.py | SymbolIndex.symbol_scores | def symbol_scores(self, symbol):
"""Find matches for symbol.
:param symbol: A . separated symbol. eg. 'os.path.basename'
:returns: A list of tuples of (score, package, reference|None),
ordered by score from highest to lowest.
"""
scores = []
path = []
# sys.path sys path -> import sys
# os.path.basename os.path basename -> import os.path
# basename os.path basename -> from os.path import basename
# path.basename os.path basename -> from os import path
def fixup(module, variable):
prefix = module.split('.')
if variable is not None:
prefix.append(variable)
seeking = symbol.split('.')
new_module = []
while prefix and seeking[0] != prefix[0]:
new_module.append(prefix.pop(0))
if new_module:
module, variable = '.'.join(new_module), prefix[0]
else:
variable = None
return module, variable
def score_walk(scope, scale):
sub_path, score = self._score_key(scope, full_key)
if score > 0.1:
try:
i = sub_path.index(None)
sub_path, from_symbol = sub_path[:i], '.'.join(sub_path[i + 1:])
except ValueError:
from_symbol = None
package_path = '.'.join(path + sub_path)
package_path, from_symbol = fixup(package_path, from_symbol)
scores.append((score * scale, package_path, from_symbol))
for key, subscope in scope._tree.items():
if type(subscope) is not float:
path.append(key)
score_walk(subscope, subscope.score * scale - 0.1)
path.pop()
full_key = symbol.split('.')
score_walk(self, 1.0)
scores.sort(reverse=True)
return scores | python | def symbol_scores(self, symbol):
"""Find matches for symbol.
:param symbol: A . separated symbol. eg. 'os.path.basename'
:returns: A list of tuples of (score, package, reference|None),
ordered by score from highest to lowest.
"""
scores = []
path = []
# sys.path sys path -> import sys
# os.path.basename os.path basename -> import os.path
# basename os.path basename -> from os.path import basename
# path.basename os.path basename -> from os import path
def fixup(module, variable):
prefix = module.split('.')
if variable is not None:
prefix.append(variable)
seeking = symbol.split('.')
new_module = []
while prefix and seeking[0] != prefix[0]:
new_module.append(prefix.pop(0))
if new_module:
module, variable = '.'.join(new_module), prefix[0]
else:
variable = None
return module, variable
def score_walk(scope, scale):
sub_path, score = self._score_key(scope, full_key)
if score > 0.1:
try:
i = sub_path.index(None)
sub_path, from_symbol = sub_path[:i], '.'.join(sub_path[i + 1:])
except ValueError:
from_symbol = None
package_path = '.'.join(path + sub_path)
package_path, from_symbol = fixup(package_path, from_symbol)
scores.append((score * scale, package_path, from_symbol))
for key, subscope in scope._tree.items():
if type(subscope) is not float:
path.append(key)
score_walk(subscope, subscope.score * scale - 0.1)
path.pop()
full_key = symbol.split('.')
score_walk(self, 1.0)
scores.sort(reverse=True)
return scores | Find matches for symbol.
:param symbol: A . separated symbol. eg. 'os.path.basename'
:returns: A list of tuples of (score, package, reference|None),
ordered by score from highest to lowest. | https://github.com/alecthomas/importmagic/blob/c00f2b282d933e0a9780146a20792f9e31fc8e6f/importmagic/index.py#L231-L280 |
alecthomas/importmagic | importmagic/index.py | SymbolIndex.find | def find(self, path):
"""Return the node for a path, or None."""
path = path.split('.')
node = self
while node._parent:
node = node._parent
for name in path:
node = node._tree.get(name, None)
if node is None or type(node) is float:
return None
return node | python | def find(self, path):
"""Return the node for a path, or None."""
path = path.split('.')
node = self
while node._parent:
node = node._parent
for name in path:
node = node._tree.get(name, None)
if node is None or type(node) is float:
return None
return node | Return the node for a path, or None. | https://github.com/alecthomas/importmagic/blob/c00f2b282d933e0a9780146a20792f9e31fc8e6f/importmagic/index.py#L302-L312 |
alecthomas/importmagic | importmagic/index.py | SymbolIndex.location_for | def location_for(self, path):
"""Return the location code for a path."""
path = path.split('.')
node = self
while node._parent:
node = node._parent
location = node.location
for name in path:
tree = node._tree.get(name, None)
if tree is None or type(tree) is float:
return location
location = tree.location
return location | python | def location_for(self, path):
"""Return the location code for a path."""
path = path.split('.')
node = self
while node._parent:
node = node._parent
location = node.location
for name in path:
tree = node._tree.get(name, None)
if tree is None or type(tree) is float:
return location
location = tree.location
return location | Return the location code for a path. | https://github.com/alecthomas/importmagic/blob/c00f2b282d933e0a9780146a20792f9e31fc8e6f/importmagic/index.py#L314-L326 |
wgnet/webium | webium/controls/select.py | Select.select_option | def select_option(self, option):
"""
Performs selection of provided item from Web List
@params option - string item name
"""
items_list = self.get_options()
for item in items_list:
if item.get_attribute("value") == option:
item.click()
break | python | def select_option(self, option):
"""
Performs selection of provided item from Web List
@params option - string item name
"""
items_list = self.get_options()
for item in items_list:
if item.get_attribute("value") == option:
item.click()
break | Performs selection of provided item from Web List
@params option - string item name | https://github.com/wgnet/webium/blob/ccb09876a201e75f5c5810392d4db7a8708b90cb/webium/controls/select.py#L15-L25 |
wgnet/webium | webium/controls/select.py | Select.get_attribute_selected | def get_attribute_selected(self, attribute):
"""
Performs search of selected item from Web List
Return attribute of selected item
@params attribute - string attribute name
"""
items_list = self.get_options()
return next(iter([item.get_attribute(attribute) for item in items_list if item.is_selected()]), None) | python | def get_attribute_selected(self, attribute):
"""
Performs search of selected item from Web List
Return attribute of selected item
@params attribute - string attribute name
"""
items_list = self.get_options()
return next(iter([item.get_attribute(attribute) for item in items_list if item.is_selected()]), None) | Performs search of selected item from Web List
Return attribute of selected item
@params attribute - string attribute name | https://github.com/wgnet/webium/blob/ccb09876a201e75f5c5810392d4db7a8708b90cb/webium/controls/select.py#L33-L41 |
wgnet/webium | webium/controls/select.py | Select.select_by_visible_text | def select_by_visible_text(self, text):
"""
Performs search of selected item from Web List
@params text - string visible text
"""
xpath = './/option[normalize-space(.) = {0}]'.format(self._escape_string(text))
opts = self.find_elements_by_xpath(xpath)
matched = False
for opt in opts:
self._set_selected(opt)
if not self.is_multiple:
return
matched = True
# in case the target option isn't found by xpath
# attempt to find it by direct comparison among options which contain at least the longest token from the text
if len(opts) == 0 and ' ' in text:
sub_string_without_space = self._get_longest_token(text)
if sub_string_without_space == "":
candidates = self.get_options()
else:
xpath = ".//option[contains(.,{0})]".format(self._escape_string(sub_string_without_space))
candidates = self.find_elements_by_xpath(xpath)
for candidate in candidates:
if text == candidate.text:
self._set_selected(candidate)
if not self.is_multiple:
return
matched = True
if not matched:
raise NoSuchElementException("Could not locate element with visible text: " + str(text)) | python | def select_by_visible_text(self, text):
"""
Performs search of selected item from Web List
@params text - string visible text
"""
xpath = './/option[normalize-space(.) = {0}]'.format(self._escape_string(text))
opts = self.find_elements_by_xpath(xpath)
matched = False
for opt in opts:
self._set_selected(opt)
if not self.is_multiple:
return
matched = True
# in case the target option isn't found by xpath
# attempt to find it by direct comparison among options which contain at least the longest token from the text
if len(opts) == 0 and ' ' in text:
sub_string_without_space = self._get_longest_token(text)
if sub_string_without_space == "":
candidates = self.get_options()
else:
xpath = ".//option[contains(.,{0})]".format(self._escape_string(sub_string_without_space))
candidates = self.find_elements_by_xpath(xpath)
for candidate in candidates:
if text == candidate.text:
self._set_selected(candidate)
if not self.is_multiple:
return
matched = True
if not matched:
raise NoSuchElementException("Could not locate element with visible text: " + str(text)) | Performs search of selected item from Web List
@params text - string visible text | https://github.com/wgnet/webium/blob/ccb09876a201e75f5c5810392d4db7a8708b90cb/webium/controls/select.py#L57-L87 |
wgnet/webium | webium/wait.py | wait | def wait(*args, **kwargs):
"""
Wrapping 'wait()' method of 'waiting' library with default parameter values.
WebDriverException is ignored in the expected exceptions by default.
"""
kwargs.setdefault('sleep_seconds', (1, None))
kwargs.setdefault('expected_exceptions', WebDriverException)
kwargs.setdefault('timeout_seconds', webium.settings.wait_timeout)
return wait_lib(*args, **kwargs) | python | def wait(*args, **kwargs):
"""
Wrapping 'wait()' method of 'waiting' library with default parameter values.
WebDriverException is ignored in the expected exceptions by default.
"""
kwargs.setdefault('sleep_seconds', (1, None))
kwargs.setdefault('expected_exceptions', WebDriverException)
kwargs.setdefault('timeout_seconds', webium.settings.wait_timeout)
return wait_lib(*args, **kwargs) | Wrapping 'wait()' method of 'waiting' library with default parameter values.
WebDriverException is ignored in the expected exceptions by default. | https://github.com/wgnet/webium/blob/ccb09876a201e75f5c5810392d4db7a8708b90cb/webium/wait.py#L7-L16 |
alecthomas/importmagic | importmagic/util.py | parse_ast | def parse_ast(source, filename=None):
"""Parse source into a Python AST, taking care of encoding."""
if isinstance(source, text_type) and sys.version_info[0] == 2:
# ast.parse() on Python 2 doesn't like encoding declarations
# in Unicode strings
source = CODING_COOKIE_RE.sub(r'\1', source, 1)
return ast.parse(source, filename or '<unknown>') | python | def parse_ast(source, filename=None):
"""Parse source into a Python AST, taking care of encoding."""
if isinstance(source, text_type) and sys.version_info[0] == 2:
# ast.parse() on Python 2 doesn't like encoding declarations
# in Unicode strings
source = CODING_COOKIE_RE.sub(r'\1', source, 1)
return ast.parse(source, filename or '<unknown>') | Parse source into a Python AST, taking care of encoding. | https://github.com/alecthomas/importmagic/blob/c00f2b282d933e0a9780146a20792f9e31fc8e6f/importmagic/util.py#L14-L20 |
alecthomas/importmagic | importmagic/symbols.py | Scope.find_unresolved_and_unreferenced_symbols | def find_unresolved_and_unreferenced_symbols(self):
"""Find any unresolved symbols, and unreferenced symbols from this scope.
:returns: ({unresolved}, {unreferenced})
"""
unresolved = set()
unreferenced = self._definitions.copy()
self._collect_unresolved_and_unreferenced(set(), set(), unresolved, unreferenced,
frozenset(self._definitions), start=True)
return unresolved, unreferenced - Scope.ALL_BUILTINS | python | def find_unresolved_and_unreferenced_symbols(self):
"""Find any unresolved symbols, and unreferenced symbols from this scope.
:returns: ({unresolved}, {unreferenced})
"""
unresolved = set()
unreferenced = self._definitions.copy()
self._collect_unresolved_and_unreferenced(set(), set(), unresolved, unreferenced,
frozenset(self._definitions), start=True)
return unresolved, unreferenced - Scope.ALL_BUILTINS | Find any unresolved symbols, and unreferenced symbols from this scope.
:returns: ({unresolved}, {unreferenced}) | https://github.com/alecthomas/importmagic/blob/c00f2b282d933e0a9780146a20792f9e31fc8e6f/importmagic/symbols.py#L116-L125 |
netpieio/microgear-python | microgear/cache.py | get_item | def get_item(key):
"""Return content in cached file in JSON format"""
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
try:
return json.loads(open(CACHED_KEY_FILE, "rb").read().decode('UTF-8'))["_"]
except (IOError, ValueError):
return None | python | def get_item(key):
"""Return content in cached file in JSON format"""
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
try:
return json.loads(open(CACHED_KEY_FILE, "rb").read().decode('UTF-8'))["_"]
except (IOError, ValueError):
return None | Return content in cached file in JSON format | https://github.com/netpieio/microgear-python/blob/ea9bb352c7dd84b92f3462177645eaa4d448d50b/microgear/cache.py#L9-L16 |
netpieio/microgear-python | microgear/cache.py | set_item | def set_item(key,value):
"""Write JSON content from value argument to cached file and return"""
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
open(CACHED_KEY_FILE, "wb").write(json.dumps({"_": value}).encode('UTF-8'))
return value | python | def set_item(key,value):
"""Write JSON content from value argument to cached file and return"""
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
open(CACHED_KEY_FILE, "wb").write(json.dumps({"_": value}).encode('UTF-8'))
return value | Write JSON content from value argument to cached file and return | https://github.com/netpieio/microgear-python/blob/ea9bb352c7dd84b92f3462177645eaa4d448d50b/microgear/cache.py#L19-L25 |
netpieio/microgear-python | microgear/cache.py | delete_item | def delete_item(key):
"""Delete cached file if present"""
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
if os.path.isfile(CACHED_KEY_FILE):
os.remove(CACHED_KEY_FILE) | python | def delete_item(key):
"""Delete cached file if present"""
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
if os.path.isfile(CACHED_KEY_FILE):
os.remove(CACHED_KEY_FILE) | Delete cached file if present | https://github.com/netpieio/microgear-python/blob/ea9bb352c7dd84b92f3462177645eaa4d448d50b/microgear/cache.py#L28-L33 |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.__parse_json_data | def __parse_json_data(self, data):
"""Process Json data
:@param data
:@type data: json/dict
:throws TypeError
"""
if isinstance(data, dict) or isinstance(data, list):
self._raw_data = data
self._json_data = copy.deepcopy(self._raw_data)
else:
raise TypeError("Provided Data is not json") | python | def __parse_json_data(self, data):
"""Process Json data
:@param data
:@type data: json/dict
:throws TypeError
"""
if isinstance(data, dict) or isinstance(data, list):
self._raw_data = data
self._json_data = copy.deepcopy(self._raw_data)
else:
raise TypeError("Provided Data is not json") | Process Json data
:@param data
:@type data: json/dict
:throws TypeError | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L32-L44 |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.__parse_json_file | def __parse_json_file(self, file_path):
"""Process Json file data
:@param file_path
:@type file_path: string
:@throws IOError
"""
if file_path == '' or os.path.splitext(file_path)[1] != '.json':
raise IOError('Invalid Json file')
with open(file_path) as json_file:
self._raw_data = json.load(json_file)
self._json_data = copy.deepcopy(self._raw_data) | python | def __parse_json_file(self, file_path):
"""Process Json file data
:@param file_path
:@type file_path: string
:@throws IOError
"""
if file_path == '' or os.path.splitext(file_path)[1] != '.json':
raise IOError('Invalid Json file')
with open(file_path) as json_file:
self._raw_data = json.load(json_file)
self._json_data = copy.deepcopy(self._raw_data) | Process Json file data
:@param file_path
:@type file_path: string
:@throws IOError | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L46-L60 |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.__get_value_from_data | def __get_value_from_data(self, key, data):
"""Find value from json data
:@pram key
:@type: string
:@pram data
:@type data: dict
:@return object
:@throws KeyError
"""
if key.isdigit():
return data[int(key)]
if key not in data:
raise KeyError("Key not exists")
return data.get(key) | python | def __get_value_from_data(self, key, data):
"""Find value from json data
:@pram key
:@type: string
:@pram data
:@type data: dict
:@return object
:@throws KeyError
"""
if key.isdigit():
return data[int(key)]
if key not in data:
raise KeyError("Key not exists")
return data.get(key) | Find value from json data
:@pram key
:@type: string
:@pram data
:@type data: dict
:@return object
:@throws KeyError | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L62-L80 |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.at | def at(self, root):
"""Set root where PyJsonq start to prepare
:@param root
:@type root: string
:@return self
:@throws KeyError
"""
leafs = root.strip(" ").split('.')
for leaf in leafs:
if leaf:
self._json_data = self.__get_value_from_data(leaf, self._json_data)
return self | python | def at(self, root):
"""Set root where PyJsonq start to prepare
:@param root
:@type root: string
:@return self
:@throws KeyError
"""
leafs = root.strip(" ").split('.')
for leaf in leafs:
if leaf:
self._json_data = self.__get_value_from_data(leaf, self._json_data)
return self | Set root where PyJsonq start to prepare
:@param root
:@type root: string
:@return self
:@throws KeyError | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L101-L114 |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.reset | def reset(self, data={}):
"""JsonQuery object cen be reset to new data
according to given data or previously given raw Json data
:@param data: {}
:@type data: json/dict
:@return self
"""
if data and (isinstance(data, dict) or isinstance(data, list)):
self._json_data = data
else:
self._json_data = copy.deepcopy(self._raw_data)
self.__reset_queries()
return self | python | def reset(self, data={}):
"""JsonQuery object cen be reset to new data
according to given data or previously given raw Json data
:@param data: {}
:@type data: json/dict
:@return self
"""
if data and (isinstance(data, dict) or isinstance(data, list)):
self._json_data = data
else:
self._json_data = copy.deepcopy(self._raw_data)
self.__reset_queries()
return self | JsonQuery object cen be reset to new data
according to given data or previously given raw Json data
:@param data: {}
:@type data: json/dict
:@return self | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L120-L136 |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.__store_query | def __store_query(self, query_items):
"""Make where clause
:@param query_items
:@type query_items: dict
"""
temp_index = self._current_query_index
if len(self._queries) - 1 < temp_index:
self._queries.append([])
self._queries[temp_index].append(query_items) | python | def __store_query(self, query_items):
"""Make where clause
:@param query_items
:@type query_items: dict
"""
temp_index = self._current_query_index
if len(self._queries) - 1 < temp_index:
self._queries.append([])
self._queries[temp_index].append(query_items) | Make where clause
:@param query_items
:@type query_items: dict | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L138-L148 |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.__execute_queries | def __execute_queries(self):
"""Execute all condition and filter result data"""
def func(item):
or_check = False
for queries in self._queries:
and_check = True
for query in queries:
and_check &= self._matcher._match(
item.get(query.get('key'), None),
query.get('operator'),
query.get('value')
)
or_check |= and_check
return or_check
self._json_data = list(filter(lambda item: func(item), self._json_data)) | python | def __execute_queries(self):
"""Execute all condition and filter result data"""
def func(item):
or_check = False
for queries in self._queries:
and_check = True
for query in queries:
and_check &= self._matcher._match(
item.get(query.get('key'), None),
query.get('operator'),
query.get('value')
)
or_check |= and_check
return or_check
self._json_data = list(filter(lambda item: func(item), self._json_data)) | Execute all condition and filter result data | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L157-L173 |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.where | def where(self, key, operator, value):
"""Make where clause
:@param key
:@param operator
:@param value
:@type key,operator,value: string
:@return self
"""
self.__store_query({"key": key, "operator": operator, "value": value})
return self | python | def where(self, key, operator, value):
"""Make where clause
:@param key
:@param operator
:@param value
:@type key,operator,value: string
:@return self
"""
self.__store_query({"key": key, "operator": operator, "value": value})
return self | Make where clause
:@param key
:@param operator
:@param value
:@type key,operator,value: string
:@return self | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L177-L188 |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.or_where | def or_where(self, key, operator, value):
"""Make or_where clause
:@param key
:@param operator
:@param value
:@type key, operator, value: string
:@return self
"""
if len(self._queries) > 0:
self._current_query_index += 1
self.__store_query({"key": key, "operator": operator, "value": value})
return self | python | def or_where(self, key, operator, value):
"""Make or_where clause
:@param key
:@param operator
:@param value
:@type key, operator, value: string
:@return self
"""
if len(self._queries) > 0:
self._current_query_index += 1
self.__store_query({"key": key, "operator": operator, "value": value})
return self | Make or_where clause
:@param key
:@param operator
:@param value
:@type key, operator, value: string
:@return self | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L190-L203 |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.nth | def nth(self, index):
"""Getting the nth element of the collection
:@param index
:@type index: int
:@return object
"""
self.__prepare()
return None if self.count() < math.fabs(index) else self._json_data[index] | python | def nth(self, index):
"""Getting the nth element of the collection
:@param index
:@type index: int
:@return object
"""
self.__prepare()
return None if self.count() < math.fabs(index) else self._json_data[index] | Getting the nth element of the collection
:@param index
:@type index: int
:@return object | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L321-L330 |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.sum | def sum(self, property):
"""Getting the sum according to the given property
:@param property
:@type property: string
:@return int/float
"""
self.__prepare()
total = 0
for i in self._json_data:
total += i.get(property)
return total | python | def sum(self, property):
"""Getting the sum according to the given property
:@param property
:@type property: string
:@return int/float
"""
self.__prepare()
total = 0
for i in self._json_data:
total += i.get(property)
return total | Getting the sum according to the given property
:@param property
:@type property: string
:@return int/float | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L332-L345 |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.max | def max(self, property):
"""Getting the maximum value from the prepared data
:@param property
:@type property: string
:@return object
:@throws KeyError
"""
self.__prepare()
try:
return max(self._json_data, key=lambda x: x[property]).get(property)
except KeyError:
raise KeyError("Key is not exists") | python | def max(self, property):
"""Getting the maximum value from the prepared data
:@param property
:@type property: string
:@return object
:@throws KeyError
"""
self.__prepare()
try:
return max(self._json_data, key=lambda x: x[property]).get(property)
except KeyError:
raise KeyError("Key is not exists") | Getting the maximum value from the prepared data
:@param property
:@type property: string
:@return object
:@throws KeyError | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L347-L360 |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.avg | def avg(self, property):
"""Getting average according to given property
:@param property
:@type property: string
:@return average: int/float
"""
self.__prepare()
return self.sum(property) / self.count() | python | def avg(self, property):
"""Getting average according to given property
:@param property
:@type property: string
:@return average: int/float
"""
self.__prepare()
return self.sum(property) / self.count() | Getting average according to given property
:@param property
:@type property: string
:@return average: int/float | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L377-L386 |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.chunk | def chunk(self, size=0):
"""Group the resulted collection to multiple chunk
:@param size: 0
:@type size: integer
:@return Chunked List
"""
if size == 0:
raise ValueError('Invalid chunk size')
self.__prepare()
_new_content = []
while(len(self._json_data) > 0):
_new_content.append(self._json_data[0:size])
self._json_data = self._json_data[size:]
self._json_data = _new_content
return self._json_data | python | def chunk(self, size=0):
"""Group the resulted collection to multiple chunk
:@param size: 0
:@type size: integer
:@return Chunked List
"""
if size == 0:
raise ValueError('Invalid chunk size')
self.__prepare()
_new_content = []
while(len(self._json_data) > 0):
_new_content.append(self._json_data[0:size])
self._json_data = self._json_data[size:]
self._json_data = _new_content
return self._json_data | Group the resulted collection to multiple chunk
:@param size: 0
:@type size: integer
:@return Chunked List | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L388-L409 |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.group_by | def group_by(self, property):
"""Getting the grouped result by the given property
:@param property
:@type property: string
:@return self
"""
self.__prepare()
group_data = {}
for data in self._json_data:
if data[property] not in group_data:
group_data[data[property]] = []
group_data[data[property]].append(data)
self._json_data = group_data
return self | python | def group_by(self, property):
"""Getting the grouped result by the given property
:@param property
:@type property: string
:@return self
"""
self.__prepare()
group_data = {}
for data in self._json_data:
if data[property] not in group_data:
group_data[data[property]] = []
group_data[data[property]].append(data)
self._json_data = group_data
return self | Getting the grouped result by the given property
:@param property
:@type property: string
:@return self | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L411-L427 |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.sort | def sort(self, order="asc"):
"""Getting the sorted result of the given list
:@param order: "asc"
:@type order: string
:@return self
"""
self.__prepare()
if isinstance(self._json_data, list):
if order == "asc":
self._json_data = sorted(self._json_data)
else:
self._json_data = sorted(self._json_data, reverse=True)
return self | python | def sort(self, order="asc"):
"""Getting the sorted result of the given list
:@param order: "asc"
:@type order: string
:@return self
"""
self.__prepare()
if isinstance(self._json_data, list):
if order == "asc":
self._json_data = sorted(self._json_data)
else:
self._json_data = sorted(self._json_data, reverse=True)
return self | Getting the sorted result of the given list
:@param order: "asc"
:@type order: string
:@return self | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L429-L444 |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.sort_by | def sort_by(self, property, order="asc"):
"""Getting the sorted result by the given property
:@param property, order: "asc"
:@type property, order: string
:@return self
"""
self.__prepare()
if isinstance(self._json_data, list):
if order == "asc":
self._json_data = sorted(
self._json_data,
key=lambda x: x.get(property)
)
else:
self._json_data = sorted(
self._json_data,
key=lambda x: x.get(property),
reverse=True
)
return self | python | def sort_by(self, property, order="asc"):
"""Getting the sorted result by the given property
:@param property, order: "asc"
:@type property, order: string
:@return self
"""
self.__prepare()
if isinstance(self._json_data, list):
if order == "asc":
self._json_data = sorted(
self._json_data,
key=lambda x: x.get(property)
)
else:
self._json_data = sorted(
self._json_data,
key=lambda x: x.get(property),
reverse=True
)
return self | Getting the sorted result by the given property
:@param property, order: "asc"
:@type property, order: string
:@return self | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L446-L468 |
s1s1ty/py-jsonq | pyjsonq/matcher.py | Matcher._match | def _match(self, x, op, y):
"""Compare the given `x` and `y` based on `op`
:@param x, y, op
:@type x, y: mixed
:@type op: string
:@return bool
:@throws ValueError
"""
if (op not in self.condition_mapper):
raise ValueError('Invalid where condition given')
func = getattr(self, self.condition_mapper.get(op))
return func(x, y) | python | def _match(self, x, op, y):
"""Compare the given `x` and `y` based on `op`
:@param x, y, op
:@type x, y: mixed
:@type op: string
:@return bool
:@throws ValueError
"""
if (op not in self.condition_mapper):
raise ValueError('Invalid where condition given')
func = getattr(self, self.condition_mapper.get(op))
return func(x, y) | Compare the given `x` and `y` based on `op`
:@param x, y, op
:@type x, y: mixed
:@type op: string
:@return bool
:@throws ValueError | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/matcher.py#L162-L176 |
mkorpela/overrides | overrides/overrides.py | overrides | def overrides(method):
"""Decorator to indicate that the decorated method overrides a method in
superclass.
The decorator code is executed while loading class. Using this method
should have minimal runtime performance implications.
This is based on my idea about how to do this and fwc:s highly improved
algorithm for the implementation fwc:s
algorithm : http://stackoverflow.com/a/14631397/308189
my answer : http://stackoverflow.com/a/8313042/308189
How to use:
from overrides import overrides
class SuperClass(object):
def method(self):
return 2
class SubClass(SuperClass):
@overrides
def method(self):
return 1
:raises AssertionError if no match in super classes for the method name
:return method with possibly added (if the method doesn't have one)
docstring from super class
"""
for super_class in _get_base_classes(sys._getframe(2), method.__globals__):
if hasattr(super_class, method.__name__):
super_method = getattr(super_class, method.__name__)
if hasattr(super_method, "__finalized__"):
finalized = getattr(super_method, "__finalized__")
if finalized:
raise AssertionError('Method "%s" is finalized' %
method.__name__)
if not method.__doc__:
method.__doc__ = super_method.__doc__
return method
raise AssertionError('No super class method found for "%s"' %
method.__name__) | python | def overrides(method):
"""Decorator to indicate that the decorated method overrides a method in
superclass.
The decorator code is executed while loading class. Using this method
should have minimal runtime performance implications.
This is based on my idea about how to do this and fwc:s highly improved
algorithm for the implementation fwc:s
algorithm : http://stackoverflow.com/a/14631397/308189
my answer : http://stackoverflow.com/a/8313042/308189
How to use:
from overrides import overrides
class SuperClass(object):
def method(self):
return 2
class SubClass(SuperClass):
@overrides
def method(self):
return 1
:raises AssertionError if no match in super classes for the method name
:return method with possibly added (if the method doesn't have one)
docstring from super class
"""
for super_class in _get_base_classes(sys._getframe(2), method.__globals__):
if hasattr(super_class, method.__name__):
super_method = getattr(super_class, method.__name__)
if hasattr(super_method, "__finalized__"):
finalized = getattr(super_method, "__finalized__")
if finalized:
raise AssertionError('Method "%s" is finalized' %
method.__name__)
if not method.__doc__:
method.__doc__ = super_method.__doc__
return method
raise AssertionError('No super class method found for "%s"' %
method.__name__) | Decorator to indicate that the decorated method overrides a method in
superclass.
The decorator code is executed while loading class. Using this method
should have minimal runtime performance implications.
This is based on my idea about how to do this and fwc:s highly improved
algorithm for the implementation fwc:s
algorithm : http://stackoverflow.com/a/14631397/308189
my answer : http://stackoverflow.com/a/8313042/308189
How to use:
from overrides import overrides
class SuperClass(object):
def method(self):
return 2
class SubClass(SuperClass):
@overrides
def method(self):
return 1
:raises AssertionError if no match in super classes for the method name
:return method with possibly added (if the method doesn't have one)
docstring from super class | https://github.com/mkorpela/overrides/blob/196c2fa3c79fe7a7d319d2ade25bb25f6d78f1c2/overrides/overrides.py#L30-L70 |
mkorpela/overrides | overrides/overrides.py | _get_base_class_names | def _get_base_class_names(frame):
""" Get baseclass names from the code object """
co, lasti = frame.f_code, frame.f_lasti
code = co.co_code
extends = []
for (op, oparg) in op_stream(code, lasti):
if op in dis.hasconst:
if type(co.co_consts[oparg]) == str:
extends = []
elif op in dis.hasname:
if dis.opname[op] == 'LOAD_NAME':
extends.append(('name', co.co_names[oparg]))
if dis.opname[op] == 'LOAD_ATTR':
extends.append(('attr', co.co_names[oparg]))
if dis.opname[op] == 'LOAD_GLOBAL':
extends.append(('name', co.co_names[oparg]))
items = []
previous_item = []
for t, s in extends:
if t == 'name':
if previous_item:
items.append(previous_item)
previous_item = [s]
else:
previous_item += [s]
if previous_item:
items.append(previous_item)
return items | python | def _get_base_class_names(frame):
""" Get baseclass names from the code object """
co, lasti = frame.f_code, frame.f_lasti
code = co.co_code
extends = []
for (op, oparg) in op_stream(code, lasti):
if op in dis.hasconst:
if type(co.co_consts[oparg]) == str:
extends = []
elif op in dis.hasname:
if dis.opname[op] == 'LOAD_NAME':
extends.append(('name', co.co_names[oparg]))
if dis.opname[op] == 'LOAD_ATTR':
extends.append(('attr', co.co_names[oparg]))
if dis.opname[op] == 'LOAD_GLOBAL':
extends.append(('name', co.co_names[oparg]))
items = []
previous_item = []
for t, s in extends:
if t == 'name':
if previous_item:
items.append(previous_item)
previous_item = [s]
else:
previous_item += [s]
if previous_item:
items.append(previous_item)
return items | Get baseclass names from the code object | https://github.com/mkorpela/overrides/blob/196c2fa3c79fe7a7d319d2ade25bb25f6d78f1c2/overrides/overrides.py#L126-L155 |
firecat53/urlscan | urlscan/urlscan.py | get_charset | def get_charset(message, default="utf-8"):
"""Get the message charset"""
if message.get_content_charset():
return message.get_content_charset()
if message.get_charset():
return message.get_charset()
return default | python | def get_charset(message, default="utf-8"):
"""Get the message charset"""
if message.get_content_charset():
return message.get_content_charset()
if message.get_charset():
return message.get_charset()
return default | Get the message charset | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlscan.py#L30-L36 |
firecat53/urlscan | urlscan/urlscan.py | load_tlds | def load_tlds():
"""Load all legal TLD extensions from assets
"""
file = os.path.join(os.path.dirname(__file__),
'assets',
'tlds-alpha-by-domain.txt')
with open(file) as fobj:
return [elem for elem in fobj.read().lower().splitlines()[1:]
if "--" not in elem] | python | def load_tlds():
"""Load all legal TLD extensions from assets
"""
file = os.path.join(os.path.dirname(__file__),
'assets',
'tlds-alpha-by-domain.txt')
with open(file) as fobj:
return [elem for elem in fobj.read().lower().splitlines()[1:]
if "--" not in elem] | Load all legal TLD extensions from assets | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlscan.py#L268-L277 |
firecat53/urlscan | urlscan/urlscan.py | parse_text_urls | def parse_text_urls(mesg):
"""Parse a block of text, splitting it into its url and non-url
components."""
rval = []
loc = 0
for match in URLRE.finditer(mesg):
if loc < match.start():
rval.append(Chunk(mesg[loc:match.start()], None))
# Turn email addresses into mailto: links
email = match.group("email")
if email and "mailto" not in email:
mailto = "mailto:{}".format(email)
else:
mailto = match.group(1)
rval.append(Chunk(None, mailto))
loc = match.end()
if loc < len(mesg):
rval.append(Chunk(mesg[loc:], None))
return rval | python | def parse_text_urls(mesg):
"""Parse a block of text, splitting it into its url and non-url
components."""
rval = []
loc = 0
for match in URLRE.finditer(mesg):
if loc < match.start():
rval.append(Chunk(mesg[loc:match.start()], None))
# Turn email addresses into mailto: links
email = match.group("email")
if email and "mailto" not in email:
mailto = "mailto:{}".format(email)
else:
mailto = match.group(1)
rval.append(Chunk(None, mailto))
loc = match.end()
if loc < len(mesg):
rval.append(Chunk(mesg[loc:], None))
return rval | Parse a block of text, splitting it into its url and non-url
components. | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlscan.py#L309-L332 |
firecat53/urlscan | urlscan/urlscan.py | extract_with_context | def extract_with_context(lst, pred, before_context, after_context):
"""Extract URL and context from a given chunk.
"""
rval = []
start = 0
length = 0
while start < len(lst):
usedfirst = False
usedlast = False
# Extend to the next match.
while start + length < len(lst) and length < before_context + 1 \
and not pred(lst[start + length]):
length += 1
# Slide to the next match.
while start + length < len(lst) and not pred(lst[start + length]):
start += 1
# If there was no next match, abort here (it's easier
# to do this than to try to detect this case later).
if start + length == len(lst):
break
# Now extend repeatedly until we can't find anything.
while start + length < len(lst) and pred(lst[start + length]):
extendlength = 1
# Read in the 'after' context and see if it holds a URL.
while extendlength < after_context + 1 and start + length + \
extendlength < len(lst) and \
not pred(lst[start + length + extendlength]):
extendlength += 1
length += extendlength
if start + length < len(lst) and not pred(lst[start + length]):
# Didn't find a matching line, so we either
# hit the end or extended to after_context + 1..
#
# Now read in possible 'before' context
# from the next URL; if we don't find one,
# we discard the readahead.
extendlength = 1
while extendlength < before_context and start + length + \
extendlength < len(lst) and \
not pred(lst[start + length + extendlength]):
extendlength += 1
if start + length + extendlength < len(lst) and \
pred(lst[start + length + extendlength]):
length += extendlength
if length > 0 and start + length <= len(lst):
if start == 0:
usedfirst = True
if start + length == len(lst):
usedlast = True
rval.append((lst[start:start + length], usedfirst, usedlast))
start += length
length = 0
return rval | python | def extract_with_context(lst, pred, before_context, after_context):
"""Extract URL and context from a given chunk.
"""
rval = []
start = 0
length = 0
while start < len(lst):
usedfirst = False
usedlast = False
# Extend to the next match.
while start + length < len(lst) and length < before_context + 1 \
and not pred(lst[start + length]):
length += 1
# Slide to the next match.
while start + length < len(lst) and not pred(lst[start + length]):
start += 1
# If there was no next match, abort here (it's easier
# to do this than to try to detect this case later).
if start + length == len(lst):
break
# Now extend repeatedly until we can't find anything.
while start + length < len(lst) and pred(lst[start + length]):
extendlength = 1
# Read in the 'after' context and see if it holds a URL.
while extendlength < after_context + 1 and start + length + \
extendlength < len(lst) and \
not pred(lst[start + length + extendlength]):
extendlength += 1
length += extendlength
if start + length < len(lst) and not pred(lst[start + length]):
# Didn't find a matching line, so we either
# hit the end or extended to after_context + 1..
#
# Now read in possible 'before' context
# from the next URL; if we don't find one,
# we discard the readahead.
extendlength = 1
while extendlength < before_context and start + length + \
extendlength < len(lst) and \
not pred(lst[start + length + extendlength]):
extendlength += 1
if start + length + extendlength < len(lst) and \
pred(lst[start + length + extendlength]):
length += extendlength
if length > 0 and start + length <= len(lst):
if start == 0:
usedfirst = True
if start + length == len(lst):
usedlast = True
rval.append((lst[start:start + length], usedfirst, usedlast))
start += length
length = 0
return rval | Extract URL and context from a given chunk. | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlscan.py#L335-L394 |
firecat53/urlscan | urlscan/urlscan.py | extracturls | def extracturls(mesg):
"""Given a text message, extract all the URLs found in the message, along
with their surrounding context. The output is a list of sequences of Chunk
objects, corresponding to the contextual regions extracted from the string.
"""
lines = NLRE.split(mesg)
# The number of lines of context above to provide.
# above_context = 1
# The number of lines of context below to provide.
# below_context = 1
# Plan here is to first transform lines into the form
# [line_fragments] where each fragment is a chunk as
# seen by parse_text_urls. Note that this means that
# lines with more than one entry or one entry that's
# a URL are the only lines containing URLs.
linechunks = [parse_text_urls(l) for l in lines]
return extract_with_context(linechunks,
lambda chunk: len(chunk) > 1 or
(len(chunk) == 1 and chunk[0].url is not None),
1, 1) | python | def extracturls(mesg):
"""Given a text message, extract all the URLs found in the message, along
with their surrounding context. The output is a list of sequences of Chunk
objects, corresponding to the contextual regions extracted from the string.
"""
lines = NLRE.split(mesg)
# The number of lines of context above to provide.
# above_context = 1
# The number of lines of context below to provide.
# below_context = 1
# Plan here is to first transform lines into the form
# [line_fragments] where each fragment is a chunk as
# seen by parse_text_urls. Note that this means that
# lines with more than one entry or one entry that's
# a URL are the only lines containing URLs.
linechunks = [parse_text_urls(l) for l in lines]
return extract_with_context(linechunks,
lambda chunk: len(chunk) > 1 or
(len(chunk) == 1 and chunk[0].url is not None),
1, 1) | Given a text message, extract all the URLs found in the message, along
with their surrounding context. The output is a list of sequences of Chunk
objects, corresponding to the contextual regions extracted from the string. | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlscan.py#L400-L424 |
firecat53/urlscan | urlscan/urlscan.py | extracthtmlurls | def extracthtmlurls(mesg):
"""Extract URLs with context from html type message. Similar to extracturls.
"""
chunk = HTMLChunker()
chunk.feed(mesg)
chunk.close()
# above_context = 1
# below_context = 1
def somechunkisurl(chunks):
for chnk in chunks:
if chnk.url is not None:
return True
return False
return extract_with_context(chunk.rval, somechunkisurl, 1, 1) | python | def extracthtmlurls(mesg):
"""Extract URLs with context from html type message. Similar to extracturls.
"""
chunk = HTMLChunker()
chunk.feed(mesg)
chunk.close()
# above_context = 1
# below_context = 1
def somechunkisurl(chunks):
for chnk in chunks:
if chnk.url is not None:
return True
return False
return extract_with_context(chunk.rval, somechunkisurl, 1, 1) | Extract URLs with context from html type message. Similar to extracturls. | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlscan.py#L427-L443 |
firecat53/urlscan | urlscan/urlscan.py | decode_bytes | def decode_bytes(byt, enc='utf-8'):
"""Given a string or bytes input, return a string.
Args: bytes - bytes or string
enc - encoding to use for decoding the byte string.
"""
try:
strg = byt.decode(enc)
except UnicodeDecodeError as err:
strg = "Unable to decode message:\n{}\n{}".format(str(byt), err)
except (AttributeError, UnicodeEncodeError):
# If byt is already a string, just return it
return byt
return strg | python | def decode_bytes(byt, enc='utf-8'):
"""Given a string or bytes input, return a string.
Args: bytes - bytes or string
enc - encoding to use for decoding the byte string.
"""
try:
strg = byt.decode(enc)
except UnicodeDecodeError as err:
strg = "Unable to decode message:\n{}\n{}".format(str(byt), err)
except (AttributeError, UnicodeEncodeError):
# If byt is already a string, just return it
return byt
return strg | Given a string or bytes input, return a string.
Args: bytes - bytes or string
enc - encoding to use for decoding the byte string. | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlscan.py#L446-L460 |
firecat53/urlscan | urlscan/urlscan.py | decode_msg | def decode_msg(msg, enc='utf-8'):
"""
Decodes a message fragment.
Args: msg - A Message object representing the fragment
enc - The encoding to use for decoding the message
"""
# We avoid the get_payload decoding machinery for raw
# content-transfer-encodings potentially containing non-ascii characters,
# such as 8bit or binary, as these are encoded using raw-unicode-escape which
# seems to prevent subsequent utf-8 decoding.
cte = str(msg.get('content-transfer-encoding', '')).lower()
decode = cte not in ("8bit", "7bit", "binary")
res = msg.get_payload(decode=decode)
return decode_bytes(res, enc) | python | def decode_msg(msg, enc='utf-8'):
"""
Decodes a message fragment.
Args: msg - A Message object representing the fragment
enc - The encoding to use for decoding the message
"""
# We avoid the get_payload decoding machinery for raw
# content-transfer-encodings potentially containing non-ascii characters,
# such as 8bit or binary, as these are encoded using raw-unicode-escape which
# seems to prevent subsequent utf-8 decoding.
cte = str(msg.get('content-transfer-encoding', '')).lower()
decode = cte not in ("8bit", "7bit", "binary")
res = msg.get_payload(decode=decode)
return decode_bytes(res, enc) | Decodes a message fragment.
Args: msg - A Message object representing the fragment
enc - The encoding to use for decoding the message | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlscan.py#L463-L477 |
firecat53/urlscan | urlscan/urlscan.py | msgurls | def msgurls(msg, urlidx=1):
"""Main entry function for urlscan.py
"""
# Written as a generator so I can easily choose only
# one subpart in the future (e.g., for
# multipart/alternative). Actually, I might even add
# a browser for the message structure?
enc = get_charset(msg)
if msg.is_multipart():
for part in msg.get_payload():
for chunk in msgurls(part, urlidx):
urlidx += 1
yield chunk
elif msg.get_content_type() == "text/plain":
decoded = decode_msg(msg, enc)
for chunk in extracturls(decoded):
urlidx += 1
yield chunk
elif msg.get_content_type() == "text/html":
decoded = decode_msg(msg, enc)
for chunk in extracthtmlurls(decoded):
urlidx += 1
yield chunk | python | def msgurls(msg, urlidx=1):
"""Main entry function for urlscan.py
"""
# Written as a generator so I can easily choose only
# one subpart in the future (e.g., for
# multipart/alternative). Actually, I might even add
# a browser for the message structure?
enc = get_charset(msg)
if msg.is_multipart():
for part in msg.get_payload():
for chunk in msgurls(part, urlidx):
urlidx += 1
yield chunk
elif msg.get_content_type() == "text/plain":
decoded = decode_msg(msg, enc)
for chunk in extracturls(decoded):
urlidx += 1
yield chunk
elif msg.get_content_type() == "text/html":
decoded = decode_msg(msg, enc)
for chunk in extracthtmlurls(decoded):
urlidx += 1
yield chunk | Main entry function for urlscan.py | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlscan.py#L480-L503 |
firecat53/urlscan | urlscan/urlchoose.py | shorten_url | def shorten_url(url, cols, shorten):
"""Shorten long URLs to fit on one line.
"""
cols = ((cols - 6) * .85) # 6 cols for urlref and don't use while line
if shorten is False or len(url) < cols:
return url
split = int(cols * .5)
return url[:split] + "..." + url[-split:] | python | def shorten_url(url, cols, shorten):
"""Shorten long URLs to fit on one line.
"""
cols = ((cols - 6) * .85) # 6 cols for urlref and don't use while line
if shorten is False or len(url) < cols:
return url
split = int(cols * .5)
return url[:split] + "..." + url[-split:] | Shorten long URLs to fit on one line. | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L43-L51 |
firecat53/urlscan | urlscan/urlchoose.py | grp_list | def grp_list(items):
"""Organize list of items [a,2,3,4,a,4,2,a,1, etc...] like:
[[a,2,3,4], [a,4,2], [a,1]], where 'a' is a urwid.Divider
"""
grp = []
res = []
for item in items:
if isinstance(item, urwid.Divider):
res.append(grp)
grp = [items[0]]
else:
grp.append(item)
res.append(grp)
return res[1:] | python | def grp_list(items):
"""Organize list of items [a,2,3,4,a,4,2,a,1, etc...] like:
[[a,2,3,4], [a,4,2], [a,1]], where 'a' is a urwid.Divider
"""
grp = []
res = []
for item in items:
if isinstance(item, urwid.Divider):
res.append(grp)
grp = [items[0]]
else:
grp.append(item)
res.append(grp)
return res[1:] | Organize list of items [a,2,3,4,a,4,2,a,1, etc...] like:
[[a,2,3,4], [a,4,2], [a,1]], where 'a' is a urwid.Divider | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L54-L68 |
firecat53/urlscan | urlscan/urlchoose.py | splittext | def splittext(text, search, attr):
"""Split a text string by search string and add Urwid display attribute to
the search term.
Args: text - string
search - search string
attr - attribute string to add
Returns: urwid markup list ["string", ("default", " mo"), "re string"]
for search="mo", text="string more string" and attr="default"
"""
if search:
pat = re.compile("({})".format(re.escape(search)), re.IGNORECASE)
else:
return text
final = pat.split(text)
final = [(attr, i) if i.lower() == search.lower() else i for i in final]
return final | python | def splittext(text, search, attr):
"""Split a text string by search string and add Urwid display attribute to
the search term.
Args: text - string
search - search string
attr - attribute string to add
Returns: urwid markup list ["string", ("default", " mo"), "re string"]
for search="mo", text="string more string" and attr="default"
"""
if search:
pat = re.compile("({})".format(re.escape(search)), re.IGNORECASE)
else:
return text
final = pat.split(text)
final = [(attr, i) if i.lower() == search.lower() else i for i in final]
return final | Split a text string by search string and add Urwid display attribute to
the search term.
Args: text - string
search - search string
attr - attribute string to add
Returns: urwid markup list ["string", ("default", " mo"), "re string"]
for search="mo", text="string more string" and attr="default" | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L71-L89 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser.main | def main(self):
"""Urwid main event loop
"""
self.loop = urwid.MainLoop(self.top, self.palettes[self.palette_names[0]], screen=self.tui,
handle_mouse=False, input_filter=self.handle_keys,
unhandled_input=self.unhandled)
self.loop.run() | python | def main(self):
"""Urwid main event loop
"""
self.loop = urwid.MainLoop(self.top, self.palettes[self.palette_names[0]], screen=self.tui,
handle_mouse=False, input_filter=self.handle_keys,
unhandled_input=self.unhandled)
self.loop.run() | Urwid main event loop | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L213-L220 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser.handle_keys | def handle_keys(self, keys, raw):
"""Handle widget default keys
- 'Enter' or 'space' to load URL
- 'Enter' to end search mode
- add 'space' to search string in search mode
- Workaround some small positioning bugs
"""
for j, k in enumerate(keys):
if self.search is True:
text = "Search: {}".format(self.search_string)
if k == 'enter':
# Catch 'enter' key to prevent opening URL in mkbrowseto
self.enter = True
if not self.items:
self.search = False
self.enter = False
if self.search_string:
footer = 'search'
else:
footer = 'default'
text = ""
footerwid = urwid.AttrMap(urwid.Text(text), footer)
self.top.footer = footerwid
elif k in self.activate_keys:
self.search_string += k
self._search()
elif k == 'backspace':
self.search_string = self.search_string[:-1]
self._search()
elif k in self.activate_keys and \
self.urls and \
self.search is False and \
self.help_menu is False:
self._open_url()
elif self.help_menu is True:
self._help_menu()
return []
if k == 'up':
# Works around bug where the up arrow goes higher than the top list
# item and unintentionally triggers context and palette switches.
# Remaps 'up' to 'k'
keys[j] = 'k'
if k == 'home':
# Remap 'home' to 'g'. Works around small bug where 'home' takes the cursor
# above the top list item.
keys[j] = 'g'
# filter backspace out before the widget, it has a weird interaction
return [i for i in keys if i != 'backspace'] | python | def handle_keys(self, keys, raw):
"""Handle widget default keys
- 'Enter' or 'space' to load URL
- 'Enter' to end search mode
- add 'space' to search string in search mode
- Workaround some small positioning bugs
"""
for j, k in enumerate(keys):
if self.search is True:
text = "Search: {}".format(self.search_string)
if k == 'enter':
# Catch 'enter' key to prevent opening URL in mkbrowseto
self.enter = True
if not self.items:
self.search = False
self.enter = False
if self.search_string:
footer = 'search'
else:
footer = 'default'
text = ""
footerwid = urwid.AttrMap(urwid.Text(text), footer)
self.top.footer = footerwid
elif k in self.activate_keys:
self.search_string += k
self._search()
elif k == 'backspace':
self.search_string = self.search_string[:-1]
self._search()
elif k in self.activate_keys and \
self.urls and \
self.search is False and \
self.help_menu is False:
self._open_url()
elif self.help_menu is True:
self._help_menu()
return []
if k == 'up':
# Works around bug where the up arrow goes higher than the top list
# item and unintentionally triggers context and palette switches.
# Remaps 'up' to 'k'
keys[j] = 'k'
if k == 'home':
# Remap 'home' to 'g'. Works around small bug where 'home' takes the cursor
# above the top list item.
keys[j] = 'g'
# filter backspace out before the widget, it has a weird interaction
return [i for i in keys if i != 'backspace'] | Handle widget default keys
- 'Enter' or 'space' to load URL
- 'Enter' to end search mode
- add 'space' to search string in search mode
- Workaround some small positioning bugs | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L222-L271 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser.unhandled | def unhandled(self, key):
"""Handle other keyboard actions not handled by the ListBox widget.
"""
self.key = key
self.size = self.tui.get_cols_rows()
if self.search is True:
if self.enter is False and self.no_matches is False:
if len(key) == 1 and key.isprintable():
self.search_string += key
self._search()
elif self.enter is True and not self.search_string:
self.search = False
self.enter = False
return
if not self.urls and key not in "Qq":
return # No other actions are useful with no URLs
if self.help_menu is False:
try:
self.keys[key]()
except KeyError:
pass | python | def unhandled(self, key):
"""Handle other keyboard actions not handled by the ListBox widget.
"""
self.key = key
self.size = self.tui.get_cols_rows()
if self.search is True:
if self.enter is False and self.no_matches is False:
if len(key) == 1 and key.isprintable():
self.search_string += key
self._search()
elif self.enter is True and not self.search_string:
self.search = False
self.enter = False
return
if not self.urls and key not in "Qq":
return # No other actions are useful with no URLs
if self.help_menu is False:
try:
self.keys[key]()
except KeyError:
pass | Handle other keyboard actions not handled by the ListBox widget. | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L273-L294 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser._open_url | def _open_url(self):
"""<Enter> or <space>"""
load_text = "Loading URL..." if not self.run else "Executing: {}".format(self.run)
if os.environ.get('BROWSER') not in ['elinks', 'links', 'w3m', 'lynx']:
self._footer_start_thread(load_text, 5) | python | def _open_url(self):
"""<Enter> or <space>"""
load_text = "Loading URL..." if not self.run else "Executing: {}".format(self.run)
if os.environ.get('BROWSER') not in ['elinks', 'links', 'w3m', 'lynx']:
self._footer_start_thread(load_text, 5) | <Enter> or <space> | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L300-L304 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser._help_menu | def _help_menu(self):
"""F1"""
if self.help_menu is False:
self.focus_pos_saved = self.top.body.focus_position
help_men = "\n".join(["{} - {}".format(i, j.__name__.strip('_'))
for i, j in self.keys.items() if j.__name__ !=
'_digits'])
help_men = "KEYBINDINGS\n" + help_men + "\n<0-9> - Jump to item"
docs = ("OPTIONS\n"
"all_escape -- toggle unescape all URLs\n"
"all_shorten -- toggle shorten all URLs\n"
"bottom -- move cursor to last item\n"
"clear_screen -- redraw screen\n"
"clipboard -- copy highlighted URL to clipboard using xsel/xclip\n"
"clipboard_pri -- copy highlighted URL to primary selection using xsel/xclip\n"
"config_create -- create ~/.config/urlscan/config.json\n"
"context -- show/hide context\n"
"down -- cursor down\n"
"help_menu -- show/hide help menu\n"
"open_url -- open selected URL\n"
"palette -- cycle through palettes\n"
"quit -- quit\n"
"shorten -- toggle shorten highlighted URL\n"
"top -- move to first list item\n"
"up -- cursor up\n")
self.top.body = \
urwid.ListBox(urwid.SimpleListWalker([urwid.Columns([(30, urwid.Text(help_men)),
urwid.Text(docs)])]))
else:
self.top.body = urwid.ListBox(self.items)
self.top.body.focus_position = self.focus_pos_saved
self.help_menu = not self.help_menu | python | def _help_menu(self):
"""F1"""
if self.help_menu is False:
self.focus_pos_saved = self.top.body.focus_position
help_men = "\n".join(["{} - {}".format(i, j.__name__.strip('_'))
for i, j in self.keys.items() if j.__name__ !=
'_digits'])
help_men = "KEYBINDINGS\n" + help_men + "\n<0-9> - Jump to item"
docs = ("OPTIONS\n"
"all_escape -- toggle unescape all URLs\n"
"all_shorten -- toggle shorten all URLs\n"
"bottom -- move cursor to last item\n"
"clear_screen -- redraw screen\n"
"clipboard -- copy highlighted URL to clipboard using xsel/xclip\n"
"clipboard_pri -- copy highlighted URL to primary selection using xsel/xclip\n"
"config_create -- create ~/.config/urlscan/config.json\n"
"context -- show/hide context\n"
"down -- cursor down\n"
"help_menu -- show/hide help menu\n"
"open_url -- open selected URL\n"
"palette -- cycle through palettes\n"
"quit -- quit\n"
"shorten -- toggle shorten highlighted URL\n"
"top -- move to first list item\n"
"up -- cursor up\n")
self.top.body = \
urwid.ListBox(urwid.SimpleListWalker([urwid.Columns([(30, urwid.Text(help_men)),
urwid.Text(docs)])]))
else:
self.top.body = urwid.ListBox(self.items)
self.top.body.focus_position = self.focus_pos_saved
self.help_menu = not self.help_menu | F1 | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L306-L337 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser._search_key | def _search_key(self):
""" / """
if self.urls:
self.search = True
if self.compact is True:
self.compact = False
self.items, self.items_com = self.items_com, self.items
else:
return
self.no_matches = False
self.search_string = ""
# Reset the search highlighting
self._search()
footerwid = urwid.AttrMap(urwid.Text("Search: "), 'footer')
self.top.footer = footerwid
self.items = self.items_orig
self.top.body = urwid.ListBox(self.items) | python | def _search_key(self):
""" / """
if self.urls:
self.search = True
if self.compact is True:
self.compact = False
self.items, self.items_com = self.items_com, self.items
else:
return
self.no_matches = False
self.search_string = ""
# Reset the search highlighting
self._search()
footerwid = urwid.AttrMap(urwid.Text("Search: "), 'footer')
self.top.footer = footerwid
self.items = self.items_orig
self.top.body = urwid.ListBox(self.items) | / | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L339-L355 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser._digits | def _digits(self):
""" 0-9 """
self.number += self.key
try:
if self.compact is False:
self.top.body.focus_position = \
self.items.index(self.items_com[max(int(self.number) - 1, 0)])
else:
self.top.body.focus_position = \
self.items.index(self.items[max(int(self.number) - 1, 0)])
except IndexError:
self.number = self.number[:-1]
self.top.keypress(self.size, "") # Trick urwid into redisplaying the cursor
if self.number:
self._footer_start_thread("Selection: {}".format(self.number), 1) | python | def _digits(self):
""" 0-9 """
self.number += self.key
try:
if self.compact is False:
self.top.body.focus_position = \
self.items.index(self.items_com[max(int(self.number) - 1, 0)])
else:
self.top.body.focus_position = \
self.items.index(self.items[max(int(self.number) - 1, 0)])
except IndexError:
self.number = self.number[:-1]
self.top.keypress(self.size, "") # Trick urwid into redisplaying the cursor
if self.number:
self._footer_start_thread("Selection: {}".format(self.number), 1) | 0-9 | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L357-L371 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser._top | def _top(self):
""" g """
# Goto top of the list
self.top.body.focus_position = 2 if self.compact is False else 0
self.top.keypress(self.size, "") | python | def _top(self):
""" g """
# Goto top of the list
self.top.body.focus_position = 2 if self.compact is False else 0
self.top.keypress(self.size, "") | g | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L385-L389 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser._bottom | def _bottom(self):
""" G """
# Goto bottom of the list
self.top.body.focus_position = len(self.items) - 1
self.top.keypress(self.size, "") | python | def _bottom(self):
""" G """
# Goto bottom of the list
self.top.body.focus_position = len(self.items) - 1
self.top.keypress(self.size, "") | G | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L391-L395 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser._shorten | def _shorten(self):
""" s """
# Toggle shortened URL for selected item
fpo = self.top.body.focus_position
url_idx = len([i for i in self.items[:fpo + 1]
if isinstance(i, urwid.Columns)]) - 1
if self.compact is False and fpo <= 1:
return
url = self.urls[url_idx]
short = not "..." in self.items[fpo][1].label
self.items[fpo][1].set_label(shorten_url(url, self.size[0], short)) | python | def _shorten(self):
""" s """
# Toggle shortened URL for selected item
fpo = self.top.body.focus_position
url_idx = len([i for i in self.items[:fpo + 1]
if isinstance(i, urwid.Columns)]) - 1
if self.compact is False and fpo <= 1:
return
url = self.urls[url_idx]
short = not "..." in self.items[fpo][1].label
self.items[fpo][1].set_label(shorten_url(url, self.size[0], short)) | s | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L397-L407 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser._all_shorten | def _all_shorten(self):
""" S """
# Toggle all shortened URLs
self.shorten = not self.shorten
urls = iter(self.urls)
for item in self.items:
# Each Column has (Text, Button). Update the Button label
if isinstance(item, urwid.Columns):
item[1].set_label(shorten_url(next(urls),
self.size[0],
self.shorten)) | python | def _all_shorten(self):
""" S """
# Toggle all shortened URLs
self.shorten = not self.shorten
urls = iter(self.urls)
for item in self.items:
# Each Column has (Text, Button). Update the Button label
if isinstance(item, urwid.Columns):
item[1].set_label(shorten_url(next(urls),
self.size[0],
self.shorten)) | S | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L409-L419 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser._all_escape | def _all_escape(self):
""" u """
# Toggle all escaped URLs
self.unesc = not self.unesc
self.urls, self.urls_unesc = self.urls_unesc, self.urls
urls = iter(self.urls)
for item in self.items:
# Each Column has (Text, Button). Update the Button label
if isinstance(item, urwid.Columns):
item[1].set_label(shorten_url(next(urls),
self.size[0],
self.shorten)) | python | def _all_escape(self):
""" u """
# Toggle all escaped URLs
self.unesc = not self.unesc
self.urls, self.urls_unesc = self.urls_unesc, self.urls
urls = iter(self.urls)
for item in self.items:
# Each Column has (Text, Button). Update the Button label
if isinstance(item, urwid.Columns):
item[1].set_label(shorten_url(next(urls),
self.size[0],
self.shorten)) | u | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L420-L431 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser._context | def _context(self):
""" c """
# Show/hide context
if self.search_string:
# Reset search when toggling compact mode
footerwid = urwid.AttrMap(urwid.Text(""), 'default')
self.top.footer = footerwid
self.search_string = ""
self.items = self.items_orig
fpo = self.top.body.focus_position
self.items, self.items_com = self.items_com, self.items
self.top.body = urwid.ListBox(self.items)
self.top.body.focus_position = self._cur_focus(fpo)
self.compact = not self.compact | python | def _context(self):
""" c """
# Show/hide context
if self.search_string:
# Reset search when toggling compact mode
footerwid = urwid.AttrMap(urwid.Text(""), 'default')
self.top.footer = footerwid
self.search_string = ""
self.items = self.items_orig
fpo = self.top.body.focus_position
self.items, self.items_com = self.items_com, self.items
self.top.body = urwid.ListBox(self.items)
self.top.body.focus_position = self._cur_focus(fpo)
self.compact = not self.compact | c | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L433-L446 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser._clipboard | def _clipboard(self, pri=False):
""" C """
# Copy highlighted url to clipboard
fpo = self.top.body.focus_position
url_idx = len([i for i in self.items[:fpo + 1]
if isinstance(i, urwid.Columns)]) - 1
if self.compact is False and fpo <= 1:
return
url = self.urls[url_idx]
if pri is True:
cmds = ("xsel -i", "xclip -i")
else:
cmds = ("xsel -ib", "xclip -i -selection clipboard")
for cmd in cmds:
try:
proc = Popen(shlex.split(cmd), stdin=PIPE)
proc.communicate(input=url.encode(sys.getdefaultencoding()))
self._footer_start_thread("Copied url to {} selection".format(
"primary" if pri is True else "clipboard"), 5)
except OSError:
continue
break | python | def _clipboard(self, pri=False):
""" C """
# Copy highlighted url to clipboard
fpo = self.top.body.focus_position
url_idx = len([i for i in self.items[:fpo + 1]
if isinstance(i, urwid.Columns)]) - 1
if self.compact is False and fpo <= 1:
return
url = self.urls[url_idx]
if pri is True:
cmds = ("xsel -i", "xclip -i")
else:
cmds = ("xsel -ib", "xclip -i -selection clipboard")
for cmd in cmds:
try:
proc = Popen(shlex.split(cmd), stdin=PIPE)
proc.communicate(input=url.encode(sys.getdefaultencoding()))
self._footer_start_thread("Copied url to {} selection".format(
"primary" if pri is True else "clipboard"), 5)
except OSError:
continue
break | C | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L448-L469 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser._palette | def _palette(self):
""" p """
# Loop through available palettes
self.palette_idx += 1
try:
self.loop.screen.register_palette(self.palettes[self.palette_names[self.palette_idx]])
except IndexError:
self.loop.screen.register_palette(self.palettes[self.palette_names[0]])
self.palette_idx = 0
self.loop.screen.clear() | python | def _palette(self):
""" p """
# Loop through available palettes
self.palette_idx += 1
try:
self.loop.screen.register_palette(self.palettes[self.palette_names[self.palette_idx]])
except IndexError:
self.loop.screen.register_palette(self.palettes[self.palette_names[0]])
self.palette_idx = 0
self.loop.screen.clear() | p | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L476-L485 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser._config_create | def _config_create(self):
""" --genconf """
# Create ~/.config/urlscan/config.json if if doesn't exist
if not exists(self.conf):
try:
# Python 2/3 compatible recursive directory creation
os.makedirs(dirname(expanduser(self.conf)))
except OSError as err:
if errno.EEXIST != err.errno:
raise
keys = dict(zip(self.keys.keys(),
[i.__name__.strip('_') for i in self.keys.values()]))
with open(expanduser(self.conf), 'w') as pals:
pals.writelines(json.dumps({"palettes": self.palettes, "keys": keys},
indent=4))
print("Created ~/.config/urlscan/config.json")
else:
print("~/.config/urlscan/config.json already exists") | python | def _config_create(self):
""" --genconf """
# Create ~/.config/urlscan/config.json if if doesn't exist
if not exists(self.conf):
try:
# Python 2/3 compatible recursive directory creation
os.makedirs(dirname(expanduser(self.conf)))
except OSError as err:
if errno.EEXIST != err.errno:
raise
keys = dict(zip(self.keys.keys(),
[i.__name__.strip('_') for i in self.keys.values()]))
with open(expanduser(self.conf), 'w') as pals:
pals.writelines(json.dumps({"palettes": self.palettes, "keys": keys},
indent=4))
print("Created ~/.config/urlscan/config.json")
else:
print("~/.config/urlscan/config.json already exists") | --genconf | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L487-L504 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser._footer_start_thread | def _footer_start_thread(self, text, time):
"""Display given text in the footer. Clears after <time> seconds
"""
footerwid = urwid.AttrMap(urwid.Text(text), 'footer')
self.top.footer = footerwid
load_thread = Thread(target=self._loading_thread, args=(time,))
load_thread.daemon = True
load_thread.start() | python | def _footer_start_thread(self, text, time):
"""Display given text in the footer. Clears after <time> seconds
"""
footerwid = urwid.AttrMap(urwid.Text(text), 'footer')
self.top.footer = footerwid
load_thread = Thread(target=self._loading_thread, args=(time,))
load_thread.daemon = True
load_thread.start() | Display given text in the footer. Clears after <time> seconds | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L507-L515 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser._loading_thread | def _loading_thread(self, time):
"""Simple thread to wait <time> seconds after launching a URL or
displaying a URL selection number, clearing the screen and clearing the
footer loading message.
"""
sleep(time)
self.number = "" # Clear URL selection number
text = "Search: {}".format(self.search_string)
if self.search_string:
footer = 'search'
else:
footer = 'default'
text = ""
footerwid = urwid.AttrMap(urwid.Text(text), footer)
self.top.footer = footerwid
size = self.tui.get_cols_rows()
self.draw_screen(size) | python | def _loading_thread(self, time):
"""Simple thread to wait <time> seconds after launching a URL or
displaying a URL selection number, clearing the screen and clearing the
footer loading message.
"""
sleep(time)
self.number = "" # Clear URL selection number
text = "Search: {}".format(self.search_string)
if self.search_string:
footer = 'search'
else:
footer = 'default'
text = ""
footerwid = urwid.AttrMap(urwid.Text(text), footer)
self.top.footer = footerwid
size = self.tui.get_cols_rows()
self.draw_screen(size) | Simple thread to wait <time> seconds after launching a URL or
displaying a URL selection number, clearing the screen and clearing the
footer loading message. | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L517-L534 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser._search | def _search(self):
""" Search - search URLs and text.
"""
text = "Search: {}".format(self.search_string)
footerwid = urwid.AttrMap(urwid.Text(text), 'footer')
self.top.footer = footerwid
search_items = []
for grp in self.items_org:
done = False
for idx, item in enumerate(grp):
if isinstance(item, urwid.Columns):
for col_idx, col in enumerate(item.contents):
if isinstance(col[0], urwid.decoration.AttrMap):
grp[idx][col_idx].set_label(splittext(col[0].base_widget.label,
self.search_string,
''))
if self.search_string.lower() in col[0].base_widget.label.lower():
grp[idx][col_idx].set_label(splittext(col[0].base_widget.label,
self.search_string,
'search'))
done = True
elif isinstance(item, urwid.Text):
grp[idx].set_text(splittext(item.text, self.search_string, ''))
if self.search_string.lower() in item.text.lower():
grp[idx].set_text(splittext(item.text, self.search_string, 'search'))
done = True
if done is True:
search_items.extend(grp)
self.items = search_items
self.top.body = urwid.ListBox(self.items)
if self.items:
self.top.body.focus_position = 2 if self.compact is False else 0
# Trick urwid into redisplaying the cursor
self.top.keypress(self.tui.get_cols_rows(), "")
self.no_matches = False
else:
self.no_matches = True
footerwid = urwid.AttrMap(urwid.Text(text + " No Matches"), 'footer')
self.top.footer = footerwid | python | def _search(self):
""" Search - search URLs and text.
"""
text = "Search: {}".format(self.search_string)
footerwid = urwid.AttrMap(urwid.Text(text), 'footer')
self.top.footer = footerwid
search_items = []
for grp in self.items_org:
done = False
for idx, item in enumerate(grp):
if isinstance(item, urwid.Columns):
for col_idx, col in enumerate(item.contents):
if isinstance(col[0], urwid.decoration.AttrMap):
grp[idx][col_idx].set_label(splittext(col[0].base_widget.label,
self.search_string,
''))
if self.search_string.lower() in col[0].base_widget.label.lower():
grp[idx][col_idx].set_label(splittext(col[0].base_widget.label,
self.search_string,
'search'))
done = True
elif isinstance(item, urwid.Text):
grp[idx].set_text(splittext(item.text, self.search_string, ''))
if self.search_string.lower() in item.text.lower():
grp[idx].set_text(splittext(item.text, self.search_string, 'search'))
done = True
if done is True:
search_items.extend(grp)
self.items = search_items
self.top.body = urwid.ListBox(self.items)
if self.items:
self.top.body.focus_position = 2 if self.compact is False else 0
# Trick urwid into redisplaying the cursor
self.top.keypress(self.tui.get_cols_rows(), "")
self.no_matches = False
else:
self.no_matches = True
footerwid = urwid.AttrMap(urwid.Text(text + " No Matches"), 'footer')
self.top.footer = footerwid | Search - search URLs and text. | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L547-L586 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser.draw_screen | def draw_screen(self, size):
"""Render curses screen
"""
self.tui.clear()
canvas = self.top.render(size, focus=True)
self.tui.draw_screen(size, canvas) | python | def draw_screen(self, size):
"""Render curses screen
"""
self.tui.clear()
canvas = self.top.render(size, focus=True)
self.tui.draw_screen(size, canvas) | Render curses screen | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L588-L594 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser.mkbrowseto | def mkbrowseto(self, url):
"""Create the urwid callback function to open the web browser or call
another function with the URL.
"""
# Try-except block to work around webbrowser module bug
# https://bugs.python.org/issue31014
try:
browser = os.environ['BROWSER']
except KeyError:
pass
else:
del os.environ['BROWSER']
webbrowser.register(browser, None, webbrowser.GenericBrowser(browser))
try_idx = webbrowser._tryorder.index(browser)
webbrowser._tryorder.insert(0, webbrowser._tryorder.pop(try_idx))
def browse(*args):
# double ()() to ensure self.search evaluated at runtime, not when
# browse() is _created_. [0] is self.search, [1] is self.enter
# self.enter prevents opening URL when in search mode
if self._get_search()[0]() is True:
if self._get_search()[1]() is True:
self.search = False
self.enter = False
elif not self.run:
webbrowser.open(url)
elif self.run and self.pipe:
process = Popen(shlex.split(self.run), stdout=PIPE, stdin=PIPE)
process.communicate(input=url.encode(sys.getdefaultencoding()))
else:
Popen(self.run.format(url), shell=True).communicate()
size = self.tui.get_cols_rows()
self.draw_screen(size)
return browse | python | def mkbrowseto(self, url):
"""Create the urwid callback function to open the web browser or call
another function with the URL.
"""
# Try-except block to work around webbrowser module bug
# https://bugs.python.org/issue31014
try:
browser = os.environ['BROWSER']
except KeyError:
pass
else:
del os.environ['BROWSER']
webbrowser.register(browser, None, webbrowser.GenericBrowser(browser))
try_idx = webbrowser._tryorder.index(browser)
webbrowser._tryorder.insert(0, webbrowser._tryorder.pop(try_idx))
def browse(*args):
# double ()() to ensure self.search evaluated at runtime, not when
# browse() is _created_. [0] is self.search, [1] is self.enter
# self.enter prevents opening URL when in search mode
if self._get_search()[0]() is True:
if self._get_search()[1]() is True:
self.search = False
self.enter = False
elif not self.run:
webbrowser.open(url)
elif self.run and self.pipe:
process = Popen(shlex.split(self.run), stdout=PIPE, stdin=PIPE)
process.communicate(input=url.encode(sys.getdefaultencoding()))
else:
Popen(self.run.format(url), shell=True).communicate()
size = self.tui.get_cols_rows()
self.draw_screen(size)
return browse | Create the urwid callback function to open the web browser or call
another function with the URL. | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L599-L634 |
firecat53/urlscan | urlscan/urlchoose.py | URLChooser.process_urls | def process_urls(self, extractedurls, dedupe, shorten):
"""Process the 'extractedurls' and ready them for either the curses browser
or non-interactive output
Args: extractedurls
dedupe - Remove duplicate URLs from list
Returns: items - List of widgets for the ListBox
urls - List of all URLs
"""
cols, _ = urwid.raw_display.Screen().get_cols_rows()
items = []
urls = []
first = True
for group, usedfirst, usedlast in extractedurls:
if first:
first = False
items.append(urwid.Divider(div_char='-', top=1, bottom=1))
if dedupe is True:
# If no unique URLs exist, then skip the group completely
if not [chunk for chunks in group for chunk in chunks
if chunk.url is not None and chunk.url not in urls]:
continue
groupurls = []
markup = []
if not usedfirst:
markup.append(('msgtext:ellipses', '...\n'))
for chunks in group:
i = 0
while i < len(chunks):
chunk = chunks[i]
i += 1
if chunk.url is None:
markup.append(('msgtext', chunk.markup))
else:
if (dedupe is True and chunk.url not in urls) \
or dedupe is False:
urls.append(chunk.url)
groupurls.append(chunk.url)
# Collect all immediately adjacent
# chunks with the same URL.
tmpmarkup = []
if chunk.markup:
tmpmarkup.append(('msgtext', chunk.markup))
while i < len(chunks) and \
chunks[i].url == chunk.url:
if chunks[i].markup:
tmpmarkup.append(chunks[i].markup)
i += 1
url_idx = urls.index(chunk.url) + 1 if dedupe is True else len(urls)
markup += [tmpmarkup or '<URL>',
('urlref:number:braces', ' ['),
('urlref:number', repr(url_idx)),
('urlref:number:braces', ']')]
markup += '\n'
if not usedlast:
markup += [('msgtext:ellipses', '...\n\n')]
items.append(urwid.Text(markup))
i = len(urls) - len(groupurls)
for url in groupurls:
i += 1
markup = [(6, urwid.Text([('urlref:number:braces', '['),
('urlref:number', repr(i)),
('urlref:number:braces', ']'),
' '])),
urwid.AttrMap(urwid.Button(shorten_url(url,
cols,
shorten),
self.mkbrowseto(url),
user_data=url),
'urlref:url', 'url:sel')]
items.append(urwid.Columns(markup))
return items, urls | python | def process_urls(self, extractedurls, dedupe, shorten):
"""Process the 'extractedurls' and ready them for either the curses browser
or non-interactive output
Args: extractedurls
dedupe - Remove duplicate URLs from list
Returns: items - List of widgets for the ListBox
urls - List of all URLs
"""
cols, _ = urwid.raw_display.Screen().get_cols_rows()
items = []
urls = []
first = True
for group, usedfirst, usedlast in extractedurls:
if first:
first = False
items.append(urwid.Divider(div_char='-', top=1, bottom=1))
if dedupe is True:
# If no unique URLs exist, then skip the group completely
if not [chunk for chunks in group for chunk in chunks
if chunk.url is not None and chunk.url not in urls]:
continue
groupurls = []
markup = []
if not usedfirst:
markup.append(('msgtext:ellipses', '...\n'))
for chunks in group:
i = 0
while i < len(chunks):
chunk = chunks[i]
i += 1
if chunk.url is None:
markup.append(('msgtext', chunk.markup))
else:
if (dedupe is True and chunk.url not in urls) \
or dedupe is False:
urls.append(chunk.url)
groupurls.append(chunk.url)
# Collect all immediately adjacent
# chunks with the same URL.
tmpmarkup = []
if chunk.markup:
tmpmarkup.append(('msgtext', chunk.markup))
while i < len(chunks) and \
chunks[i].url == chunk.url:
if chunks[i].markup:
tmpmarkup.append(chunks[i].markup)
i += 1
url_idx = urls.index(chunk.url) + 1 if dedupe is True else len(urls)
markup += [tmpmarkup or '<URL>',
('urlref:number:braces', ' ['),
('urlref:number', repr(url_idx)),
('urlref:number:braces', ']')]
markup += '\n'
if not usedlast:
markup += [('msgtext:ellipses', '...\n\n')]
items.append(urwid.Text(markup))
i = len(urls) - len(groupurls)
for url in groupurls:
i += 1
markup = [(6, urwid.Text([('urlref:number:braces', '['),
('urlref:number', repr(i)),
('urlref:number:braces', ']'),
' '])),
urwid.AttrMap(urwid.Button(shorten_url(url,
cols,
shorten),
self.mkbrowseto(url),
user_data=url),
'urlref:url', 'url:sel')]
items.append(urwid.Columns(markup))
return items, urls | Process the 'extractedurls' and ready them for either the curses browser
or non-interactive output
Args: extractedurls
dedupe - Remove duplicate URLs from list
Returns: items - List of widgets for the ListBox
urls - List of all URLs | https://github.com/firecat53/urlscan/blob/2d10807d01167873733da3b478c784f8fa21bbc0/urlscan/urlchoose.py#L636-L711 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient._get_key_file_path | def _get_key_file_path():
"""Return the key file path."""
if os.getenv(USER_HOME) is not None and os.access(os.getenv(USER_HOME),
os.W_OK):
return os.path.join(os.getenv(USER_HOME), KEY_FILE_NAME)
return os.path.join(os.getcwd(), KEY_FILE_NAME) | python | def _get_key_file_path():
"""Return the key file path."""
if os.getenv(USER_HOME) is not None and os.access(os.getenv(USER_HOME),
os.W_OK):
return os.path.join(os.getenv(USER_HOME), KEY_FILE_NAME)
return os.path.join(os.getcwd(), KEY_FILE_NAME) | Return the key file path. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L39-L45 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient.load_key_file | def load_key_file(self):
"""Try to load the client key for the current ip."""
self.client_key = None
if self.key_file_path:
key_file_path = self.key_file_path
else:
key_file_path = self._get_key_file_path()
key_dict = {}
logger.debug('load keyfile from %s', key_file_path);
if os.path.isfile(key_file_path):
with open(key_file_path, 'r') as f:
raw_data = f.read()
if raw_data:
key_dict = json.loads(raw_data)
logger.debug('getting client_key for %s from %s', self.ip, key_file_path);
if self.ip in key_dict:
self.client_key = key_dict[self.ip] | python | def load_key_file(self):
"""Try to load the client key for the current ip."""
self.client_key = None
if self.key_file_path:
key_file_path = self.key_file_path
else:
key_file_path = self._get_key_file_path()
key_dict = {}
logger.debug('load keyfile from %s', key_file_path);
if os.path.isfile(key_file_path):
with open(key_file_path, 'r') as f:
raw_data = f.read()
if raw_data:
key_dict = json.loads(raw_data)
logger.debug('getting client_key for %s from %s', self.ip, key_file_path);
if self.ip in key_dict:
self.client_key = key_dict[self.ip] | Try to load the client key for the current ip. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L47-L66 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient.save_key_file | def save_key_file(self):
"""Save the current client key."""
if self.client_key is None:
return
if self.key_file_path:
key_file_path = self.key_file_path
else:
key_file_path = self._get_key_file_path()
logger.debug('save keyfile to %s', key_file_path);
with open(key_file_path, 'w+') as f:
raw_data = f.read()
key_dict = {}
if raw_data:
key_dict = json.loads(raw_data)
key_dict[self.ip] = self.client_key
f.write(json.dumps(key_dict)) | python | def save_key_file(self):
"""Save the current client key."""
if self.client_key is None:
return
if self.key_file_path:
key_file_path = self.key_file_path
else:
key_file_path = self._get_key_file_path()
logger.debug('save keyfile to %s', key_file_path);
with open(key_file_path, 'w+') as f:
raw_data = f.read()
key_dict = {}
if raw_data:
key_dict = json.loads(raw_data)
key_dict[self.ip] = self.client_key
f.write(json.dumps(key_dict)) | Save the current client key. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L68-L89 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient._send_register_payload | def _send_register_payload(self, websocket):
"""Send the register payload."""
file = os.path.join(os.path.dirname(__file__), HANDSHAKE_FILE_NAME)
data = codecs.open(file, 'r', 'utf-8')
raw_handshake = data.read()
handshake = json.loads(raw_handshake)
handshake['payload']['client-key'] = self.client_key
yield from websocket.send(json.dumps(handshake))
raw_response = yield from websocket.recv()
response = json.loads(raw_response)
if response['type'] == 'response' and \
response['payload']['pairingType'] == 'PROMPT':
raw_response = yield from websocket.recv()
response = json.loads(raw_response)
if response['type'] == 'registered':
self.client_key = response['payload']['client-key']
self.save_key_file() | python | def _send_register_payload(self, websocket):
"""Send the register payload."""
file = os.path.join(os.path.dirname(__file__), HANDSHAKE_FILE_NAME)
data = codecs.open(file, 'r', 'utf-8')
raw_handshake = data.read()
handshake = json.loads(raw_handshake)
handshake['payload']['client-key'] = self.client_key
yield from websocket.send(json.dumps(handshake))
raw_response = yield from websocket.recv()
response = json.loads(raw_response)
if response['type'] == 'response' and \
response['payload']['pairingType'] == 'PROMPT':
raw_response = yield from websocket.recv()
response = json.loads(raw_response)
if response['type'] == 'registered':
self.client_key = response['payload']['client-key']
self.save_key_file() | Send the register payload. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L92-L112 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient._register | def _register(self):
"""Register wrapper."""
logger.debug('register on %s', "ws://{}:{}".format(self.ip, self.port));
try:
websocket = yield from websockets.connect(
"ws://{}:{}".format(self.ip, self.port), timeout=self.timeout_connect)
except:
logger.error('register failed to connect to %s', "ws://{}:{}".format(self.ip, self.port));
return False
logger.debug('register websocket connected to %s', "ws://{}:{}".format(self.ip, self.port));
try:
yield from self._send_register_payload(websocket)
finally:
logger.debug('close register connection to %s', "ws://{}:{}".format(self.ip, self.port));
yield from websocket.close() | python | def _register(self):
"""Register wrapper."""
logger.debug('register on %s', "ws://{}:{}".format(self.ip, self.port));
try:
websocket = yield from websockets.connect(
"ws://{}:{}".format(self.ip, self.port), timeout=self.timeout_connect)
except:
logger.error('register failed to connect to %s', "ws://{}:{}".format(self.ip, self.port));
return False
logger.debug('register websocket connected to %s', "ws://{}:{}".format(self.ip, self.port));
try:
yield from self._send_register_payload(websocket)
finally:
logger.debug('close register connection to %s', "ws://{}:{}".format(self.ip, self.port));
yield from websocket.close() | Register wrapper. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L119-L137 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient.register | def register(self):
"""Pair client with tv."""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(self._register()) | python | def register(self):
"""Pair client with tv."""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(self._register()) | Pair client with tv. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L139-L143 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient._command | def _command(self, msg):
"""Send a command to the tv."""
logger.debug('send command to %s', "ws://{}:{}".format(self.ip, self.port));
try:
websocket = yield from websockets.connect(
"ws://{}:{}".format(self.ip, self.port), timeout=self.timeout_connect)
except:
logger.debug('command failed to connect to %s', "ws://{}:{}".format(self.ip, self.port));
return False
logger.debug('command websocket connected to %s', "ws://{}:{}".format(self.ip, self.port));
try:
yield from self._send_register_payload(websocket)
if not self.client_key:
raise PyLGTVPairException("Unable to pair")
yield from websocket.send(json.dumps(msg))
if msg['type'] == 'request':
raw_response = yield from websocket.recv()
self.last_response = json.loads(raw_response)
finally:
logger.debug('close command connection to %s', "ws://{}:{}".format(self.ip, self.port));
yield from websocket.close() | python | def _command(self, msg):
"""Send a command to the tv."""
logger.debug('send command to %s', "ws://{}:{}".format(self.ip, self.port));
try:
websocket = yield from websockets.connect(
"ws://{}:{}".format(self.ip, self.port), timeout=self.timeout_connect)
except:
logger.debug('command failed to connect to %s', "ws://{}:{}".format(self.ip, self.port));
return False
logger.debug('command websocket connected to %s', "ws://{}:{}".format(self.ip, self.port));
try:
yield from self._send_register_payload(websocket)
if not self.client_key:
raise PyLGTVPairException("Unable to pair")
yield from websocket.send(json.dumps(msg))
if msg['type'] == 'request':
raw_response = yield from websocket.recv()
self.last_response = json.loads(raw_response)
finally:
logger.debug('close command connection to %s', "ws://{}:{}".format(self.ip, self.port));
yield from websocket.close() | Send a command to the tv. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L146-L172 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient.command | def command(self, request_type, uri, payload):
"""Build and send a command."""
self.command_count += 1
if payload is None:
payload = {}
message = {
'id': "{}_{}".format(type, self.command_count),
'type': request_type,
'uri': "ssap://{}".format(uri),
'payload': payload,
}
self.last_response = None
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(asyncio.wait_for(self._command(message), self.timeout_connect, loop=loop))
finally:
loop.close() | python | def command(self, request_type, uri, payload):
"""Build and send a command."""
self.command_count += 1
if payload is None:
payload = {}
message = {
'id': "{}_{}".format(type, self.command_count),
'type': request_type,
'uri': "ssap://{}".format(uri),
'payload': payload,
}
self.last_response = None
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(asyncio.wait_for(self._command(message), self.timeout_connect, loop=loop))
finally:
loop.close() | Build and send a command. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L174-L195 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient.send_message | def send_message(self, message, icon_path=None):
"""Show a floating message."""
icon_encoded_string = ''
icon_extension = ''
if icon_path is not None:
icon_extension = os.path.splitext(icon_path)[1][1:]
with open(icon_path, 'rb') as icon_file:
icon_encoded_string = base64.b64encode(icon_file.read()).decode('ascii')
self.request(EP_SHOW_MESSAGE, {
'message': message,
'iconData': icon_encoded_string,
'iconExtension': icon_extension
}) | python | def send_message(self, message, icon_path=None):
"""Show a floating message."""
icon_encoded_string = ''
icon_extension = ''
if icon_path is not None:
icon_extension = os.path.splitext(icon_path)[1][1:]
with open(icon_path, 'rb') as icon_file:
icon_encoded_string = base64.b64encode(icon_file.read()).decode('ascii')
self.request(EP_SHOW_MESSAGE, {
'message': message,
'iconData': icon_encoded_string,
'iconExtension': icon_extension
}) | Show a floating message. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L201-L215 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient.get_apps | def get_apps(self):
"""Return all apps."""
self.request(EP_GET_APPS)
return {} if self.last_response is None else self.last_response.get('payload').get('launchPoints') | python | def get_apps(self):
"""Return all apps."""
self.request(EP_GET_APPS)
return {} if self.last_response is None else self.last_response.get('payload').get('launchPoints') | Return all apps. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L218-L221 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient.get_current_app | def get_current_app(self):
"""Get the current app id."""
self.request(EP_GET_CURRENT_APP_INFO)
return None if self.last_response is None else self.last_response.get('payload').get('appId') | python | def get_current_app(self):
"""Get the current app id."""
self.request(EP_GET_CURRENT_APP_INFO)
return None if self.last_response is None else self.last_response.get('payload').get('appId') | Get the current app id. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L223-L226 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient.get_services | def get_services(self):
"""Get all services."""
self.request(EP_GET_SERVICES)
return {} if self.last_response is None else self.last_response.get('payload').get('services') | python | def get_services(self):
"""Get all services."""
self.request(EP_GET_SERVICES)
return {} if self.last_response is None else self.last_response.get('payload').get('services') | Get all services. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L255-L258 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient.get_software_info | def get_software_info(self):
"""Return the current software status."""
self.request(EP_GET_SOFTWARE_INFO)
return {} if self.last_response is None else self.last_response.get('payload') | python | def get_software_info(self):
"""Return the current software status."""
self.request(EP_GET_SOFTWARE_INFO)
return {} if self.last_response is None else self.last_response.get('payload') | Return the current software status. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L260-L263 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient.get_inputs | def get_inputs(self):
"""Get all inputs."""
self.request(EP_GET_INPUTS)
return {} if self.last_response is None else self.last_response.get('payload').get('devices') | python | def get_inputs(self):
"""Get all inputs."""
self.request(EP_GET_INPUTS)
return {} if self.last_response is None else self.last_response.get('payload').get('devices') | Get all inputs. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L283-L286 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient.get_audio_status | def get_audio_status(self):
"""Get the current audio status"""
self.request(EP_GET_AUDIO_STATUS)
return {} if self.last_response is None else self.last_response.get('payload') | python | def get_audio_status(self):
"""Get the current audio status"""
self.request(EP_GET_AUDIO_STATUS)
return {} if self.last_response is None else self.last_response.get('payload') | Get the current audio status | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L299-L302 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient.get_volume | def get_volume(self):
"""Get the current volume."""
self.request(EP_GET_VOLUME)
return 0 if self.last_response is None else self.last_response.get('payload').get('volume') | python | def get_volume(self):
"""Get the current volume."""
self.request(EP_GET_VOLUME)
return 0 if self.last_response is None else self.last_response.get('payload').get('volume') | Get the current volume. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L314-L317 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient.set_volume | def set_volume(self, volume):
"""Set volume."""
volume = max(0, volume)
self.request(EP_SET_VOLUME, {
'volume': volume
}) | python | def set_volume(self, volume):
"""Set volume."""
volume = max(0, volume)
self.request(EP_SET_VOLUME, {
'volume': volume
}) | Set volume. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L319-L324 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient.get_channels | def get_channels(self):
"""Get all tv channels."""
self.request(EP_GET_TV_CHANNELS)
return {} if self.last_response is None else self.last_response.get('payload').get('channelList') | python | def get_channels(self):
"""Get all tv channels."""
self.request(EP_GET_TV_CHANNELS)
return {} if self.last_response is None else self.last_response.get('payload').get('channelList') | Get all tv channels. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L343-L346 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient.get_current_channel | def get_current_channel(self):
"""Get the current tv channel."""
self.request(EP_GET_CURRENT_CHANNEL)
return {} if self.last_response is None else self.last_response.get('payload') | python | def get_current_channel(self):
"""Get the current tv channel."""
self.request(EP_GET_CURRENT_CHANNEL)
return {} if self.last_response is None else self.last_response.get('payload') | Get the current tv channel. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L348-L351 |
TheRealLink/pylgtv | pylgtv/webos_client.py | WebOsClient.get_channel_info | def get_channel_info(self):
"""Get the current channel info."""
self.request(EP_GET_CHANNEL_INFO)
return {} if self.last_response is None else self.last_response.get('payload') | python | def get_channel_info(self):
"""Get the current channel info."""
self.request(EP_GET_CHANNEL_INFO)
return {} if self.last_response is None else self.last_response.get('payload') | Get the current channel info. | https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L353-L356 |
ssato/python-anyconfig | src/anyconfig/processors.py | _load_plugins_itr | def _load_plugins_itr(pgroup, safe=True):
"""
.. seealso:: the doc of :func:`load_plugins`
"""
for res in pkg_resources.iter_entry_points(pgroup):
try:
yield res.load()
except ImportError:
if safe:
continue
raise | python | def _load_plugins_itr(pgroup, safe=True):
"""
.. seealso:: the doc of :func:`load_plugins`
"""
for res in pkg_resources.iter_entry_points(pgroup):
try:
yield res.load()
except ImportError:
if safe:
continue
raise | .. seealso:: the doc of :func:`load_plugins` | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/processors.py#L27-L37 |
ssato/python-anyconfig | src/anyconfig/processors.py | select_by_key | def select_by_key(items, sort_fn=sorted):
"""
:param items: A list of tuples of keys and values, [([key], val)]
:return: A list of tuples of key and values, [(key, [val])]
>>> select_by_key([(["a", "aaa"], 1), (["b", "bb"], 2), (["a"], 3)])
[('a', [1, 3]), ('aaa', [1]), ('b', [2]), ('bb', [2])]
"""
itr = anyconfig.utils.concat(((k, v) for k in ks) for ks, v in items)
return list((k, sort_fn(t[1] for t in g))
for k, g
in anyconfig.utils.groupby(itr, operator.itemgetter(0))) | python | def select_by_key(items, sort_fn=sorted):
"""
:param items: A list of tuples of keys and values, [([key], val)]
:return: A list of tuples of key and values, [(key, [val])]
>>> select_by_key([(["a", "aaa"], 1), (["b", "bb"], 2), (["a"], 3)])
[('a', [1, 3]), ('aaa', [1]), ('b', [2]), ('bb', [2])]
"""
itr = anyconfig.utils.concat(((k, v) for k in ks) for ks, v in items)
return list((k, sort_fn(t[1] for t in g))
for k, g
in anyconfig.utils.groupby(itr, operator.itemgetter(0))) | :param items: A list of tuples of keys and values, [([key], val)]
:return: A list of tuples of key and values, [(key, [val])]
>>> select_by_key([(["a", "aaa"], 1), (["b", "bb"], 2), (["a"], 3)])
[('a', [1, 3]), ('aaa', [1]), ('b', [2]), ('bb', [2])] | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/processors.py#L57-L68 |
ssato/python-anyconfig | src/anyconfig/processors.py | list_by_x | def list_by_x(prs, key):
"""
:param key: Grouping key, "type" or "extensions"
:return:
A list of :class:`Processor` or its children classes grouped by
given 'item', [(cid, [:class:`Processor`)]] by default
"""
if key == "type":
kfn = operator.methodcaller(key)
res = sorted(((k, sort_by_prio(g)) for k, g
in anyconfig.utils.groupby(prs, kfn)),
key=operator.itemgetter(0))
elif key == "extensions":
res = select_by_key(((p.extensions(), p) for p in prs),
sort_fn=sort_by_prio)
else:
raise ValueError("Argument 'key' must be 'type' or "
"'extensions' but it was '%s'" % key)
return res | python | def list_by_x(prs, key):
"""
:param key: Grouping key, "type" or "extensions"
:return:
A list of :class:`Processor` or its children classes grouped by
given 'item', [(cid, [:class:`Processor`)]] by default
"""
if key == "type":
kfn = operator.methodcaller(key)
res = sorted(((k, sort_by_prio(g)) for k, g
in anyconfig.utils.groupby(prs, kfn)),
key=operator.itemgetter(0))
elif key == "extensions":
res = select_by_key(((p.extensions(), p) for p in prs),
sort_fn=sort_by_prio)
else:
raise ValueError("Argument 'key' must be 'type' or "
"'extensions' but it was '%s'" % key)
return res | :param key: Grouping key, "type" or "extensions"
:return:
A list of :class:`Processor` or its children classes grouped by
given 'item', [(cid, [:class:`Processor`)]] by default | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/processors.py#L71-L91 |
ssato/python-anyconfig | src/anyconfig/processors.py | findall_with_pred | def findall_with_pred(predicate, prs):
"""
:param predicate: any callable to filter results
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:return: A list of appropriate processor classes or []
"""
return sorted((p for p in prs if predicate(p)),
key=operator.methodcaller("priority"), reverse=True) | python | def findall_with_pred(predicate, prs):
"""
:param predicate: any callable to filter results
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:return: A list of appropriate processor classes or []
"""
return sorted((p for p in prs if predicate(p)),
key=operator.methodcaller("priority"), reverse=True) | :param predicate: any callable to filter results
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:return: A list of appropriate processor classes or [] | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/processors.py#L94-L101 |
ssato/python-anyconfig | src/anyconfig/processors.py | maybe_processor | def maybe_processor(type_or_id, cls=anyconfig.models.processor.Processor):
"""
:param type_or_id:
Type of the data to process or ID of the processor class or
:class:`anyconfig.models.processor.Processor` class object or its
instance
:param cls: A class object to compare with 'type_or_id'
:return: Processor instance or None
"""
if isinstance(type_or_id, cls):
return type_or_id
if type(type_or_id) == type(cls) and issubclass(type_or_id, cls):
return type_or_id()
return None | python | def maybe_processor(type_or_id, cls=anyconfig.models.processor.Processor):
"""
:param type_or_id:
Type of the data to process or ID of the processor class or
:class:`anyconfig.models.processor.Processor` class object or its
instance
:param cls: A class object to compare with 'type_or_id'
:return: Processor instance or None
"""
if isinstance(type_or_id, cls):
return type_or_id
if type(type_or_id) == type(cls) and issubclass(type_or_id, cls):
return type_or_id()
return None | :param type_or_id:
Type of the data to process or ID of the processor class or
:class:`anyconfig.models.processor.Processor` class object or its
instance
:param cls: A class object to compare with 'type_or_id'
:return: Processor instance or None | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/processors.py#L104-L119 |
ssato/python-anyconfig | src/anyconfig/processors.py | find_by_type_or_id | def find_by_type_or_id(type_or_id, prs):
"""
:param type_or_id: Type of the data to process or ID of the processor class
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:return:
A list of processor classes to process files of given data type or
processor 'type_or_id' found by its ID
:raises: UnknownProcessorTypeError
"""
def pred(pcls):
"""Predicate"""
return pcls.cid() == type_or_id or pcls.type() == type_or_id
pclss = findall_with_pred(pred, prs)
if not pclss:
raise UnknownProcessorTypeError(type_or_id)
return pclss | python | def find_by_type_or_id(type_or_id, prs):
"""
:param type_or_id: Type of the data to process or ID of the processor class
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:return:
A list of processor classes to process files of given data type or
processor 'type_or_id' found by its ID
:raises: UnknownProcessorTypeError
"""
def pred(pcls):
"""Predicate"""
return pcls.cid() == type_or_id or pcls.type() == type_or_id
pclss = findall_with_pred(pred, prs)
if not pclss:
raise UnknownProcessorTypeError(type_or_id)
return pclss | :param type_or_id: Type of the data to process or ID of the processor class
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:return:
A list of processor classes to process files of given data type or
processor 'type_or_id' found by its ID
:raises: UnknownProcessorTypeError | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/processors.py#L122-L139 |
ssato/python-anyconfig | src/anyconfig/processors.py | find_by_fileext | def find_by_fileext(fileext, prs):
"""
:param fileext: File extension
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:return: A list of processor class to processor files with given extension
:raises: UnknownFileTypeError
"""
def pred(pcls):
"""Predicate"""
return fileext in pcls.extensions()
pclss = findall_with_pred(pred, prs)
if not pclss:
raise UnknownFileTypeError("file extension={}".format(fileext))
return pclss | python | def find_by_fileext(fileext, prs):
"""
:param fileext: File extension
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:return: A list of processor class to processor files with given extension
:raises: UnknownFileTypeError
"""
def pred(pcls):
"""Predicate"""
return fileext in pcls.extensions()
pclss = findall_with_pred(pred, prs)
if not pclss:
raise UnknownFileTypeError("file extension={}".format(fileext))
return pclss | :param fileext: File extension
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:return: A list of processor class to processor files with given extension
:raises: UnknownFileTypeError | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/processors.py#L142-L157 |
ssato/python-anyconfig | src/anyconfig/processors.py | find_by_maybe_file | def find_by_maybe_file(obj, prs):
"""
:param obj:
a file path, file or file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo' (namedtuple) object
:param cps_by_ext: A list of processor classes
:return: A list of processor classes to process given (maybe) file
:raises: UnknownFileTypeError
"""
if not isinstance(obj, IOInfo):
obj = anyconfig.ioinfo.make(obj)
return find_by_fileext(obj.extension, prs) | python | def find_by_maybe_file(obj, prs):
"""
:param obj:
a file path, file or file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo' (namedtuple) object
:param cps_by_ext: A list of processor classes
:return: A list of processor classes to process given (maybe) file
:raises: UnknownFileTypeError
"""
if not isinstance(obj, IOInfo):
obj = anyconfig.ioinfo.make(obj)
return find_by_fileext(obj.extension, prs) | :param obj:
a file path, file or file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo' (namedtuple) object
:param cps_by_ext: A list of processor classes
:return: A list of processor classes to process given (maybe) file
:raises: UnknownFileTypeError | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/processors.py#L160-L172 |
ssato/python-anyconfig | src/anyconfig/processors.py | findall | def findall(obj, prs, forced_type=None,
cls=anyconfig.models.processor.Processor):
"""
:param obj:
a file path, file, file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo` (namedtuple) object
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:param forced_type:
Forced processor type of the data to process or ID of the processor
class or None
:param cls: A class object to compare with 'forced_type' later
:return: A list of instances of processor classes to process 'obj' data
:raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
"""
if (obj is None or not obj) and forced_type is None:
raise ValueError("The first argument 'obj' or the second argument "
"'forced_type' must be something other than "
"None or False.")
if forced_type is None:
pclss = find_by_maybe_file(obj, prs) # :: [Processor], never []
else:
pclss = find_by_type_or_id(forced_type, prs) # Do.
return pclss | python | def findall(obj, prs, forced_type=None,
cls=anyconfig.models.processor.Processor):
"""
:param obj:
a file path, file, file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo` (namedtuple) object
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:param forced_type:
Forced processor type of the data to process or ID of the processor
class or None
:param cls: A class object to compare with 'forced_type' later
:return: A list of instances of processor classes to process 'obj' data
:raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
"""
if (obj is None or not obj) and forced_type is None:
raise ValueError("The first argument 'obj' or the second argument "
"'forced_type' must be something other than "
"None or False.")
if forced_type is None:
pclss = find_by_maybe_file(obj, prs) # :: [Processor], never []
else:
pclss = find_by_type_or_id(forced_type, prs) # Do.
return pclss | :param obj:
a file path, file, file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo` (namedtuple) object
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:param forced_type:
Forced processor type of the data to process or ID of the processor
class or None
:param cls: A class object to compare with 'forced_type' later
:return: A list of instances of processor classes to process 'obj' data
:raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/processors.py#L175-L200 |
ssato/python-anyconfig | src/anyconfig/processors.py | find | def find(obj, prs, forced_type=None, cls=anyconfig.models.processor.Processor):
"""
:param obj:
a file path, file, file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo' (namedtuple) object
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:param forced_type:
Forced processor type of the data to process or ID of the processor
class or :class:`anyconfig.models.processor.Processor` class object or
its instance itself
:param cls: A class object to compare with 'forced_type' later
:return: an instance of processor class to process 'obj' data
:raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
"""
if forced_type is not None:
processor = maybe_processor(forced_type, cls=cls)
if processor is not None:
return processor
pclss = findall(obj, prs, forced_type=forced_type, cls=cls)
return pclss[0]() | python | def find(obj, prs, forced_type=None, cls=anyconfig.models.processor.Processor):
"""
:param obj:
a file path, file, file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo' (namedtuple) object
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:param forced_type:
Forced processor type of the data to process or ID of the processor
class or :class:`anyconfig.models.processor.Processor` class object or
its instance itself
:param cls: A class object to compare with 'forced_type' later
:return: an instance of processor class to process 'obj' data
:raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
"""
if forced_type is not None:
processor = maybe_processor(forced_type, cls=cls)
if processor is not None:
return processor
pclss = findall(obj, prs, forced_type=forced_type, cls=cls)
return pclss[0]() | :param obj:
a file path, file, file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo' (namedtuple) object
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:param forced_type:
Forced processor type of the data to process or ID of the processor
class or :class:`anyconfig.models.processor.Processor` class object or
its instance itself
:param cls: A class object to compare with 'forced_type' later
:return: an instance of processor class to process 'obj' data
:raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/processors.py#L203-L224 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.